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

    setup() {
        this.orm = useService("orm");
        this.action = useService("action");
        this.state = useState({
            loading: true,
            studentId: null,
            student: null,
            events: [],
            filteredEvents: [],
            filters: { eventType: "", dateFrom: "", dateTo: "" },
            totalCount: 0,
        });

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

    async loadStudentList() {
        try {
            this.state.studentList = await this.orm.searchRead(
                "res.users",
                [["account_source", "!=", false]],
                ["name", "email"],
                { 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.loadTimeline();
    }

    async loadTimeline() {
        this.state.loading = true;
        try {
            const domain = [["student_id", "=", this.state.studentId]];
            if (this.state.filters.eventType) {
                domain.push(["event_type", "=", this.state.filters.eventType]);
            }
            if (this.state.filters.dateFrom) {
                domain.push(["created_at", ">=", this.state.filters.dateFrom]);
            }
            if (this.state.filters.dateTo) {
                domain.push(["created_at", "<=", this.state.filters.dateTo + " 23:59:59"]);
            }

            const [events, students] = await Promise.all([
                this.orm.searchRead(
                    "encoach.adaptive.event",
                    domain,
                    ["student_id", "course_id", "event_type", "signal_name", "signal_value", "decision", "context", "created_at"],
                    { limit: 100, 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.events = events;
            this.state.filteredEvents = events;
            this.state.totalCount = events.length;
        } catch (e) {
            console.error("Timeline load error:", e);
        } finally {
            this.state.loading = false;
        }
    }

    onFilterChange(field, ev) {
        this.state.filters[field] = ev.target.value;
        if (this.state.studentId) {
            this.loadTimeline();
        }
    }

    clearFilters() {
        this.state.filters = { eventType: "", dateFrom: "", dateTo: "" };
        if (this.state.studentId) {
            this.loadTimeline();
        }
    }

    eventIcon(eventType) {
        return eventType === "signal" ? "fa-bolt" : "fa-gavel";
    }

    eventColor(eventType) {
        return eventType === "signal" ? "primary" : "success";
    }

    formatDate(dt) {
        if (!dt) return "";
        return dt.replace("T", " ").substring(0, 19);
    }

    parseContext(ctx) {
        if (!ctx) return null;
        try {
            return typeof ctx === "string" ? JSON.parse(ctx) : ctx;
        } catch {
            return null;
        }
    }

    get signalCount() {
        return this.state.filteredEvents.filter(e => e.event_type === "signal").length;
    }

    get decisionCount() {
        return this.state.filteredEvents.filter(e => e.event_type === "decision").length;
    }

    goBack() {
        this.state.studentId = null;
        this.state.student = null;
        this.state.events = [];
        this.state.filteredEvents = [];
        this.state.filters = { eventType: "", dateFrom: "", dateTo: "" };
        this.state.loading = true;
        this.loadStudentList();
    }
}

registry.category("actions").add("encoach_signal_timeline", SignalTimeline);
