/** @odoo-module **/

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

export class ExecutorBoard extends Component {
    setup() {
        this.orm = useService("orm");
        this.userId = session.user_id || session.uid || (session.storeData?.Store?.settings?.user_id?.id);

        this.rawData = {
            stages: [],
            directives: []
        };

        this.state = useState({
            columns: [],
            loading: true,
        });

        onWillStart(async () => {
            if (!this.userId) {
                const partner = session.storeData?.["res.partner"]?.find(p => p.userId);
                this.userId = partner ? partner.userId : false;
            }
            await this.loadData();
        });
    }

    async loadData() {
        if (!this.userId) return;

        this.rawData.stages = await this.orm.searchRead(
            "directive.stage",
            [],
            ["id", "name", "code"],
        );

        // 2. Грузим директивы
        this.rawData.directives = await this.orm.searchRead(
            "directive.directive",
            [["executor_user_id", "=", this.userId]],
            [
                "id", "name", "executor_stage_id",
                "deadline_display", "time_left_display",
                "planned_hours", "priority", "priority_stars", "is_overdue"
            ]
        );

        this.processData();
        this.state.loading = false;
    }

    processData() {
        this.state.columns = this.rawData.stages.map(stage => {
            return {
                id: stage.id,
                name: stage.name,
                code: stage.code,
                directives: this.rawData.directives.filter(d => d.executor_stage_id && d.executor_stage_id[0] === stage.id)
            };
        });
    }

    async quickAction(ev, directiveId, actionType) {
        ev.stopPropagation();

        let targetCode = '';
        if (actionType === 'start') targetCode = 'in_progress';
        if (actionType === 'pause') targetCode = 'paused';
        if (actionType === 'finish') targetCode = 'done';

        if (targetCode) {
            await this.orm.call("directive.directive", "action_quick_change_stage", [directiveId, targetCode]);
            await this.loadData();
        }
    }

    async openDirective(directiveId) {
    }

    async logout() {
        window.location.href = "/web/session/logout";
    }
}

ExecutorBoard.template = "directive_layer.ExecutorBoard";
registry.category("actions").add("directive_layer.executor_dashboard_action", ExecutorBoard);