/**
 * Admin dashboard — Revenue vs expenses (Chart.js, light theme).
 */
import { Chart, registerables } from 'chart.js';

Chart.register(...registerables);

const CHART_REFRESH_MS = 30000;

const LIGHT = {
    text: '#475569',
    textMuted: '#94a3b8',
    grid: '#e2e8f0',
    border: '#f1f5f9',
    revenueLine: '#7c3aed',
    revenueFill: 'rgba(124, 58, 237, 0.12)',
    expenseLine: '#64748b',
    expenseFill: 'rgba(148, 163, 184, 0.08)',
    pointBorder: '#ffffff',
};

function formatAmount(value) {
    const n = Number(value);
    if (Number.isNaN(n)) return '0.00';
    return n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

/**
 * @param {HTMLElement} root — #revenue-chart-root
 */
export function mountRevenueChart(root) {
    const url = root.dataset.chartUrl;
    if (!url) return;

    const canvas = root.querySelector('canvas[data-revenue-chart-canvas]');
    if (!canvas) return;

    const loadingEl = document.getElementById('chart-loading');
    const panel = root.closest('[data-revenue-chart-panel]');
    const refreshBtn = document.getElementById('chart-refresh-btn');

    let chartInstance = null;
    let chartMonths = parseInt(root.dataset.initialMonths || '6', 10) || 6;
    let refreshInterval = null;

    const ctx = canvas.getContext('2d');

    function setLoading(on) {
        if (!loadingEl) return;
        if (on) {
            loadingEl.classList.remove('hidden');
            loadingEl.classList.add('flex');
        } else {
            loadingEl.classList.add('hidden');
            loadingEl.classList.remove('flex');
        }
    }

    function setTabActive(months) {
        const tabs = panel?.querySelectorAll('.chart-range-tab') || [];
        tabs.forEach((btn) => {
            const m = parseInt(btn.getAttribute('data-chart-months'), 10);
            const on = m === months;
            btn.classList.toggle('bg-white', on);
            btn.classList.toggle('text-violet-700', on);
            btn.classList.toggle('shadow-sm', on);
            btn.classList.toggle('ring-1', on);
            btn.classList.toggle('ring-slate-200', on);
            btn.classList.toggle('text-slate-600', !on);
        });
    }

    function destroyChart() {
        if (chartInstance) {
            chartInstance.destroy();
            chartInstance = null;
        }
    }

    function renderChart(payload) {
        const rows = payload?.data || [];
        const labels = rows.map((d) => d.month);
        const revenue = rows.map((d) => Number(d.revenue) || 0);
        const expense = rows.map((d) => Number(d.expense) || 0);

        destroyChart();

        chartInstance = new Chart(ctx, {
            type: 'line',
            data: {
                labels,
                datasets: [
                    {
                        label: 'Revenue',
                        data: revenue,
                        borderColor: LIGHT.revenueLine,
                        backgroundColor: LIGHT.revenueFill,
                        borderWidth: 2.5,
                        pointRadius: 4,
                        pointHoverRadius: 6,
                        pointBackgroundColor: LIGHT.revenueLine,
                        pointBorderColor: LIGHT.pointBorder,
                        pointBorderWidth: 2,
                        tension: 0.35,
                        fill: true,
                    },
                    {
                        label: 'Expenses',
                        data: expense,
                        borderColor: LIGHT.expenseLine,
                        backgroundColor: 'transparent',
                        borderWidth: 2,
                        borderDash: [6, 4],
                        pointRadius: 3,
                        pointHoverRadius: 5,
                        pointBackgroundColor: LIGHT.expenseLine,
                        pointBorderColor: LIGHT.pointBorder,
                        pointBorderWidth: 2,
                        tension: 0.35,
                        fill: false,
                    },
                ],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false,
                },
                plugins: {
                    legend: {
                        display: false,
                    },
                    tooltip: {
                        backgroundColor: '#ffffff',
                        titleColor: LIGHT.text,
                        bodyColor: LIGHT.text,
                        borderColor: LIGHT.grid,
                        borderWidth: 1,
                        padding: 12,
                        displayColors: true,
                        boxPadding: 4,
                        callbacks: {
                            label(context) {
                                const v = context.parsed.y;
                                return ` ${context.dataset.label}: ${formatAmount(v)}`;
                            },
                        },
                    },
                },
                scales: {
                    x: {
                        grid: {
                            color: LIGHT.border,
                            drawBorder: false,
                        },
                        ticks: {
                            color: LIGHT.textMuted,
                            font: { size: 11, weight: '500' },
                            maxRotation: 0,
                        },
                    },
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: LIGHT.grid,
                            drawBorder: false,
                        },
                        ticks: {
                            color: LIGHT.textMuted,
                            font: { size: 11, weight: '500' },
                            callback(value) {
                                if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
                                if (value >= 1000) return `${(value / 1000).toFixed(0)}k`;
                                return value;
                            },
                        },
                    },
                },
            },
        });
    }

    async function loadChart(months) {
        setLoading(true);
        try {
            const res = await fetch(`${url}?months=${months}`, {
                headers: { 'X-Requested-With': 'XMLHttpRequest', Accept: 'application/json' },
            });
            const json = await res.json();
            canvas.style.display = '';
            canvas.parentElement?.querySelector('[data-chart-error]')?.remove();
            if (json.success && Array.isArray(json.data)) {
                renderChart(json);
            } else if (canvas.parentElement) {
                destroyChart();
                const msg = document.createElement('p');
                msg.className = 'py-12 text-center text-sm text-slate-500';
                msg.textContent = 'Could not load chart data.';
                msg.setAttribute('data-chart-error', '');
                canvas.style.display = 'none';
                canvas.parentElement.appendChild(msg);
            }
        } catch {
            destroyChart();
            if (canvas.parentElement) {
                canvas.parentElement.querySelector('[data-chart-error]')?.remove();
                const msg = document.createElement('p');
                msg.className = 'py-12 text-center text-sm text-slate-500';
                msg.textContent = 'Could not load chart.';
                msg.setAttribute('data-chart-error', '');
                canvas.style.display = 'none';
                canvas.parentElement.appendChild(msg);
            }
        } finally {
            setLoading(false);
        }
    }

    panel?.querySelectorAll('.chart-range-tab').forEach((btn) => {
        btn.addEventListener('click', () => {
            chartMonths = parseInt(btn.getAttribute('data-chart-months'), 10);
            setTabActive(chartMonths);
            loadChart(chartMonths);
        });
    });

    refreshBtn?.addEventListener('click', () => loadChart(chartMonths));

    setTabActive(chartMonths);
    loadChart(chartMonths);

    function startAutoRefresh() {
        if (refreshInterval) clearInterval(refreshInterval);
        refreshInterval = setInterval(() => loadChart(chartMonths), CHART_REFRESH_MS);
    }

    startAutoRefresh();

    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            if (refreshInterval) clearInterval(refreshInterval);
            refreshInterval = null;
        } else {
            startAutoRefresh();
            loadChart(chartMonths);
        }
    });
}
