/** @odoo-module */

import { Component, onWillStart, useState } from "@odoo/owl";
import { registry } from "@web/core/registry";
import { useService } from "@web/core/utils/hooks";
import { Layout } from "@web/search/layout";

class ExamValidationReport extends Component {
    static template = "encoach_exam_template.ExamValidation";
    static components = { Layout };
    static props = ["*"];

    setup() {
        this.orm = useService("orm");
        this.action = useService("action");
        this.state = useState({
            loading: true,
            examId: null,
            exam: null,
            checks: [],
            overallValid: false,
            passCount: 0,
            failCount: 0,
            warnCount: 0,
            expandedSections: {},
        });

        onWillStart(async () => {
            const ctx = this.props.action?.context || {};
            this.state.examId = ctx.active_id || ctx.exam_id || null;
            if (this.state.examId) {
                await this.runValidation();
            } else {
                await this.loadExamList();
            }
        });
    }

    async loadExamList() {
        try {
            this.state.examList = await this.orm.searchRead(
                "encoach.exam.template",
                [],
                ["name", "code", "type", "total_time_min"],
                { limit: 50, order: "name" },
            );
        } catch (e) {
            console.error("Failed to load exam list:", e);
        } finally {
            this.state.loading = false;
        }
    }

    async selectExam(examId) {
        this.state.examId = examId;
        this.state.loading = true;
        await this.runValidation();
    }

    async runValidation() {
        this.state.loading = true;
        try {
            const exams = await this.orm.searchRead(
                "encoach.exam.template",
                [["id", "=", this.state.examId]],
                ["name", "code", "type", "total_time_min", "pass_threshold", "structure", "subject_id"],
            );
            this.state.exam = exams.length ? exams[0] : null;

            if (!this.state.exam) {
                this.state.loading = false;
                return;
            }

            const questions = await this.orm.searchRead(
                "encoach.question",
                [],
                ["skill", "difficulty", "marks", "status"],
            );

            this.state.checks = this._runChecks(this.state.exam, questions);
            this.state.passCount = this.state.checks.filter(c => c.status === "pass").length;
            this.state.failCount = this.state.checks.filter(c => c.status === "fail").length;
            this.state.warnCount = this.state.checks.filter(c => c.status === "warn").length;
            this.state.overallValid = this.state.failCount === 0;
        } catch (e) {
            console.error("Validation error:", e);
        } finally {
            this.state.loading = false;
        }
    }

    _runChecks(exam, questions) {
        const checks = [];
        const active = questions.filter(q => q.status === "active");
        const skills = ["listening", "reading", "writing", "speaking", "grammar", "vocabulary"];

        checks.push({
            id: "name",
            category: "Template",
            label: "Exam name is set",
            status: exam.name ? "pass" : "fail",
            detail: exam.name || "Missing exam name",
        });

        checks.push({
            id: "time",
            category: "Template",
            label: "Time limit is configured",
            status: exam.total_time_min > 0 ? "pass" : "fail",
            detail: exam.total_time_min ? `${exam.total_time_min} minutes` : "No time limit set",
        });

        checks.push({
            id: "threshold",
            category: "Template",
            label: "Pass threshold defined",
            status: exam.pass_threshold > 0 ? "pass" : "warn",
            detail: exam.pass_threshold ? `${exam.pass_threshold}%` : "No threshold — all scores will pass",
        });

        const poolSize = active.length;
        checks.push({
            id: "pool_size",
            category: "Content Pool",
            label: "Active questions available (min 10)",
            status: poolSize >= 10 ? "pass" : poolSize >= 5 ? "warn" : "fail",
            detail: `${poolSize} active questions in the pool`,
        });

        for (const skill of skills) {
            const count = active.filter(q => q.skill === skill).length;
            if (count > 0) {
                checks.push({
                    id: `skill_${skill}`,
                    category: "Skill Coverage",
                    label: `${skill.charAt(0).toUpperCase() + skill.slice(1)} questions available`,
                    status: count >= 3 ? "pass" : "warn",
                    detail: `${count} active questions for ${skill}`,
                });
            }
        }

        const difficulties = ["easy", "medium", "hard"];
        for (const d of difficulties) {
            const count = active.filter(q => q.difficulty === d).length;
            checks.push({
                id: `diff_${d}`,
                category: "Difficulty Balance",
                label: `${d.charAt(0).toUpperCase() + d.slice(1)} questions present`,
                status: count > 0 ? "pass" : "warn",
                detail: `${count} ${d} questions`,
            });
        }

        const totalMarks = active.reduce((s, q) => s + (q.marks || 1), 0);
        checks.push({
            id: "marks",
            category: "Marks",
            label: "Sufficient total marks in pool",
            status: totalMarks >= 20 ? "pass" : totalMarks >= 10 ? "warn" : "fail",
            detail: `${totalMarks} total marks available`,
        });

        return checks;
    }

    toggleSection(category) {
        this.state.expandedSections[category] = !this.state.expandedSections[category];
    }

    isSectionExpanded(category) {
        return this.state.expandedSections[category] !== false;
    }

    checksForCategory(category) {
        return this.state.checks.filter(c => c.category === category);
    }

    get categories() {
        const seen = new Set();
        return this.state.checks.reduce((arr, c) => {
            if (!seen.has(c.category)) {
                seen.add(c.category);
                arr.push(c.category);
            }
            return arr;
        }, []);
    }

    categoryStatus(category) {
        const items = this.checksForCategory(category);
        if (items.some(c => c.status === "fail")) return "fail";
        if (items.some(c => c.status === "warn")) return "warn";
        return "pass";
    }

    goBack() {
        this.state.examId = null;
        this.state.exam = null;
        this.state.checks = [];
        this.state.loading = true;
        this.loadExamList();
    }
}

registry.category("actions").add("encoach_exam_validation", ExamValidationReport);
