/** @odoo-module */

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

export class FusionApiDashboard extends Component {
    static template = "fusion_api.Dashboard";

    setup() {
        this.orm = useService("orm");
        this.actionService = useService("action");

        this.state = useState({
            totalProviders: 0,
            activeProviders: 0,
            totalConsumers: 0,
            activeConsumers: 0,
            monthCost: 0,
            monthRequests: 0,
            todayRequests: 0,
            topConsumers: [],
            providerStats: [],
            recentUsage: [],
            approachingLimits: [],
            loaded: false,
        });

        onWillStart(() => this.loadData());
    }

    async loadData() {
        const data = await this.orm.call(
            "fusion.api.provider",
            "get_dashboard_data",
            [],
        );
        Object.assign(this.state, {
            totalProviders: data.total_providers,
            activeProviders: data.active_providers,
            totalConsumers: data.total_consumers,
            activeConsumers: data.active_consumers,
            monthCost: data.month_cost,
            monthRequests: data.month_requests,
            todayRequests: data.today_requests,
            topConsumers: data.top_consumers || [],
            providerStats: data.provider_stats || [],
            recentUsage: data.recent_usage || [],
            approachingLimits: data.approaching_limits || [],
            loaded: true,
        });
    }

    async refresh() {
        this.state.loaded = false;
        await this.loadData();
    }

    openProviders() {
        this.actionService.doAction("fusion_api.action_api_provider");
    }

    openConsumers() {
        this.actionService.doAction("fusion_api.action_api_consumer");
    }

    openUsageLog() {
        this.actionService.doAction("fusion_api.action_api_usage");
    }

    openAccessRules() {
        this.actionService.doAction("fusion_api.action_api_access");
    }

    formatCost(value) {
        return (value || 0).toFixed(2);
    }

    formatCostDetailed(value) {
        return (value || 0).toFixed(6);
    }

    getStatusClass(status) {
        const classes = {
            success: "text-bg-success",
            error: "text-bg-danger",
            rate_limited: "text-bg-warning",
            budget_exceeded: "text-bg-warning",
        };
        return classes[status] || "text-bg-secondary";
    }

    formatTime(isoString) {
        if (!isoString) return "";
        const d = new Date(isoString);
        return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
    }
}

registry
    .category("actions")
    .add("fusion_api_dashboard", FusionApiDashboard);
