/** @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 EncoachDashboard extends Component {
    static template = "encoach_core.Dashboard";
    static components = { Layout };
    static props = ["*"];

    setup() {
        this.orm = useService("orm");
        this.action = useService("action");
        this.state = useState({
            loading: true,
            stats: {
                total_students: 0,
                total_teachers: 0,
                total_courses: 0,
                total_exams: 0,
                active_sessions: 0,
                pending_grading: 0,
                pending_approval: 0,
                total_entities: 0,
            },
            recentAttempts: [],
        });

        onWillStart(async () => {
            await this.loadDashboardData();
        });
    }

    async loadDashboardData() {
        try {
            const [students, teachers, courses, exams, sessions, pendingGrading, pendingApproval, entities] = await Promise.all([
                this.orm.searchCount("res.users", [["account_source", "!=", false]]),
                this.orm.searchCount("res.users", [["user_type", "=", "teacher"]]),
                this.orm.searchCount("op.course", []),
                this.orm.searchCount("encoach.exam.custom", []),
                this.orm.searchCount("encoach.student.attempt", [["status", "=", "in_progress"]]),
                this.orm.searchCount("encoach.student.attempt", [["status", "=", "scoring"]]),
                this.orm.searchCount("encoach.student.attempt", [["status", "=", "pending_approval"]]),
                this.orm.searchCount("encoach.entity", []),
            ]);

            this.state.stats = {
                total_students: students,
                total_teachers: teachers,
                total_courses: courses,
                total_exams: exams,
                active_sessions: sessions,
                pending_grading: pendingGrading,
                pending_approval: pendingApproval,
                total_entities: entities,
            };

            const attempts = await this.orm.searchRead(
                "encoach.student.attempt",
                [],
                ["student_id", "exam_id", "status", "overall_band", "started_at"],
                { limit: 10, order: "started_at desc" },
            );
            this.state.recentAttempts = attempts;

        } catch (e) {
            console.error("Dashboard load error:", e);
        } finally {
            this.state.loading = false;
        }
    }

    openAction(model, name, domain = []) {
        this.action.doAction({
            type: "ir.actions.act_window",
            name: name,
            res_model: model,
            views: [[false, "list"], [false, "form"]],
            domain: domain,
        });
    }

    openStudents() { this.openAction("res.users", "Students", [["account_source", "!=", false]]); }
    openTeachers() { this.openAction("res.users", "Teachers", [["user_type", "=", "teacher"]]); }
    openCourses() { this.openAction("op.course", "Courses"); }
    openExams() { this.openAction("encoach.exam.custom", "Exams"); }
    openGradingQueue() { this.openAction("encoach.student.attempt", "Grading Queue", [["status", "=", "scoring"]]); }
    openPendingApproval() { this.openAction("encoach.student.attempt", "Score Approval", [["status", "=", "pending_approval"]]); }
    openEntities() { this.openAction("encoach.entity", "Entities"); }
}

registry.category("actions").add("encoach_dashboard", EncoachDashboard);
