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

    setup() {
        this.orm = useService("orm");
        this.action = useService("action");
        this.state = useState({
            loading: true,
            studentId: null,
            student: null,
            gapProfile: null,
            skillGaps: [],
            weakTopics: [],
            recommendations: [],
        });

        onWillStart(async () => {
            const ctx = this.props.action?.context || {};
            this.state.studentId = ctx.student_id || ctx.active_id || null;
            if (this.state.studentId) {
                await this.loadGapData();
            } else {
                await this.loadStudentList();
            }
        });
    }

    async loadStudentList() {
        try {
            this.state.studentList = await this.orm.searchRead(
                "res.users",
                [["account_source", "!=", false]],
                ["name", "email", "login"],
                { limit: 50, order: "name" },
            );
        } catch (e) {
            console.error("Failed to load students:", e);
        } finally {
            this.state.loading = false;
        }
    }

    async selectStudent(studentId) {
        this.state.studentId = studentId;
        this.state.loading = true;
        await this.loadGapData();
    }

    async loadGapData() {
        this.state.loading = true;
        try {
            const [profiles, students] = await Promise.all([
                this.orm.searchRead(
                    "encoach.gap.profile",
                    [["student_id", "=", this.state.studentId]],
                    ["student_id", "source_type", "skill_gaps", "question_type_weaknesses", "topic_weaknesses", "created_at"],
                    { limit: 1, order: "created_at desc" },
                ),
                this.orm.searchRead(
                    "res.users",
                    [["id", "=", this.state.studentId]],
                    ["name", "email"],
                ),
            ]);

            this.state.student = students.length ? students[0] : null;
            this.state.gapProfile = profiles.length ? profiles[0] : null;

            if (this.state.gapProfile) {
                this._parseGapProfile(this.state.gapProfile);
            }
        } catch (e) {
            console.error("Gap analysis load error:", e);
        } finally {
            this.state.loading = false;
        }
    }

    _parseGapProfile(profile) {
        this.state.skillGaps = this._safeParseJson(profile.skill_gaps, []);
        if (!Array.isArray(this.state.skillGaps)) {
            const obj = this.state.skillGaps;
            this.state.skillGaps = Object.entries(obj).map(([skill, data]) => ({
                skill,
                current: typeof data === "object" ? (data.current || 0) : data,
                target: typeof data === "object" ? (data.target || 100) : 100,
                gap: typeof data === "object" ? (data.gap || (data.target || 100) - (data.current || 0)) : (100 - data),
            }));
        }

        const topicRaw = this._safeParseJson(profile.topic_weaknesses, []);
        if (Array.isArray(topicRaw)) {
            this.state.weakTopics = topicRaw;
        } else if (typeof topicRaw === "object") {
            this.state.weakTopics = Object.entries(topicRaw).map(([name, score]) => ({
                name,
                score: typeof score === "number" ? score : 0,
            }));
        }

        this.state.recommendations = this._generateRecommendations();
    }

    _safeParseJson(val, fallback) {
        if (!val) return fallback;
        if (typeof val === "object") return val;
        try { return JSON.parse(val); } catch { return fallback; }
    }

    _generateRecommendations() {
        const recs = [];
        for (const gap of this.state.skillGaps) {
            const pct = gap.target > 0 ? (gap.current / gap.target) * 100 : 0;
            if (pct < 50) {
                recs.push({ icon: "fa-exclamation-triangle", color: "danger", text: `Critical gap in ${gap.skill} — intensive practice recommended` });
            } else if (pct < 75) {
                recs.push({ icon: "fa-arrow-up", color: "warning", text: `${gap.skill} needs improvement — targeted exercises suggested` });
            }
        }
        if (this.state.weakTopics.length > 0) {
            recs.push({ icon: "fa-book", color: "info", text: `Focus on ${this.state.weakTopics.length} weak topic(s) identified in the analysis` });
        }
        if (recs.length === 0) {
            recs.push({ icon: "fa-thumbs-up", color: "success", text: "Student performance is on track across all areas" });
        }
        return recs;
    }

    barWidth(current, target) {
        if (!target || target <= 0) return 0;
        return Math.min(100, Math.round((current / target) * 100));
    }

    barColor(current, target) {
        const pct = target > 0 ? (current / target) * 100 : 0;
        if (pct >= 75) return "bg-success";
        if (pct >= 50) return "bg-warning";
        return "bg-danger";
    }

    goBack() {
        this.state.studentId = null;
        this.state.student = null;
        this.state.gapProfile = null;
        this.state.skillGaps = [];
        this.state.weakTopics = [];
        this.state.recommendations = [];
        this.state.loading = true;
        this.loadStudentList();
    }
}

registry.category("actions").add("encoach_gap_analysis", GapAnalysisVisualization);
