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

    setup() {
        this.orm = useService("orm");
        this.action = useService("action");
        this.state = useState({
            loading: true,
            filters: { skill: "", difficulty: "", status: "active", search: "" },
            questions: [],
            selectedQuestions: [],
            totalCount: 0,
            page: 1,
            pageSize: 20,
        });
        onWillStart(() => this.loadQuestions());
    }

    async loadQuestions() {
        this.state.loading = true;
        const domain = this._buildDomain();
        try {
            const [questions, count] = await Promise.all([
                this.orm.searchRead(
                    "encoach.question",
                    domain,
                    ["skill", "question_type", "stem", "difficulty", "marks", "irt_b", "subject_id", "topic_id", "status"],
                    {
                        limit: this.state.pageSize,
                        offset: (this.state.page - 1) * this.state.pageSize,
                        order: "skill, difficulty",
                    },
                ),
                this.orm.searchCount("encoach.question", domain),
            ]);
            this.state.questions = questions;
            this.state.totalCount = count;
        } catch (e) {
            console.error("Content pool load error:", e);
        } finally {
            this.state.loading = false;
        }
    }

    _buildDomain() {
        const domain = [];
        const f = this.state.filters;
        if (f.status) domain.push(["status", "=", f.status]);
        if (f.skill) domain.push(["skill", "=", f.skill]);
        if (f.difficulty) domain.push(["difficulty", "=", f.difficulty]);
        if (f.search) domain.push(["stem", "ilike", f.search]);
        return domain;
    }

    onFilterChange(field, ev) {
        this.state.filters[field] = ev.target.value;
        this.state.page = 1;
        this.loadQuestions();
    }

    onSearchInput(ev) {
        this.state.filters.search = ev.target.value;
    }

    onSearchKeydown(ev) {
        if (ev.key === "Enter") {
            this.state.page = 1;
            this.loadQuestions();
        }
    }

    applySearch() {
        this.state.page = 1;
        this.loadQuestions();
    }

    toggleQuestion(question) {
        const idx = this.state.selectedQuestions.findIndex(q => q.id === question.id);
        if (idx >= 0) {
            this.state.selectedQuestions.splice(idx, 1);
        } else {
            this.state.selectedQuestions.push({ ...question });
        }
    }

    isSelected(questionId) {
        return this.state.selectedQuestions.some(q => q.id === questionId);
    }

    removeSelected(questionId) {
        const idx = this.state.selectedQuestions.findIndex(q => q.id === questionId);
        if (idx >= 0) this.state.selectedQuestions.splice(idx, 1);
    }

    clearSelection() {
        this.state.selectedQuestions = [];
    }

    nextPage() {
        if (this.state.page * this.state.pageSize < this.state.totalCount) {
            this.state.page++;
            this.loadQuestions();
        }
    }

    prevPage() {
        if (this.state.page > 1) {
            this.state.page--;
            this.loadQuestions();
        }
    }

    truncate(text, len) {
        if (!text) return "";
        return text.length > len ? text.substring(0, len) + "..." : text;
    }

    skillLabel(val) {
        const map = { listening: "Listening", reading: "Reading", writing: "Writing", speaking: "Speaking", grammar: "Grammar", vocabulary: "Vocabulary" };
        return map[val] || val;
    }

    difficultyClass(val) {
        return { easy: "bg-success", medium: "bg-warning text-dark", hard: "bg-danger" }[val] || "bg-secondary";
    }

    get totalPages() {
        return Math.max(1, Math.ceil(this.state.totalCount / this.state.pageSize));
    }

    get selectedCount() {
        return this.state.selectedQuestions.length;
    }

    get selectedMarks() {
        return this.state.selectedQuestions.reduce((s, q) => s + (q.marks || 1), 0);
    }
}

registry.category("actions").add("encoach_content_pool", ContentPoolBrowser);
