/** @odoo-module **/

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

export class FusionClockDashboard extends Component {
    static template = "fusion_clock.Dashboard";
    static props = { "*": true };

    setup() {
        this.action = useService("action");
        this.state = useState({
            loading: true,
            clocked_in: [],
            total_employees: 0,
            present_count: 0,
            absent_count: 0,
            late_count: 0,
            pending_reasons: 0,
            pending_corrections: 0,
            error: "",
        });

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

    async _fetchData() {
        this.state.loading = true;
        try {
            const data = await rpc("/fusion_clock/dashboard_data", {});
            if (data.error) {
                this.state.error = data.error;
            } else {
                Object.assign(this.state, data);
            }
        } catch (e) {
            this.state.error = "Failed to load dashboard data.";
        }
        this.state.loading = false;
    }

    async onRefresh() {
        await this._fetchData();
    }

    onViewAttendances() {
        this.action.doAction("hr_attendance.hr_attendance_action");
    }

    onViewCorrections() {
        this.action.doAction("fusion_clock.action_fusion_clock_correction");
    }

    onViewActivityLogs() {
        this.action.doAction("fusion_clock.action_fusion_clock_activity_log");
    }

    onViewPenalties() {
        this.action.doAction("fusion_clock.action_fusion_clock_penalty");
    }
}

registry.category("actions").add("fusion_clock.Dashboard", FusionClockDashboard);
