import { ensureDashboardChartScripts } from '@admin/lib/load-dashboard-chart-scripts';
import type { DashboardEarnings } from '@admin/types/dashboard';
import { useEffect, useRef } from 'react';

declare global {
    interface Window {
        ApexCharts?: new (
            element: HTMLElement,
            options: Record<string, unknown>,
        ) => { render: () => void; destroy: () => void };
    }
}

type EarningsChartProps = {
    earnings: DashboardEarnings;
};

export function EarningsChart({ earnings }: EarningsChartProps) {
    const containerRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const element = containerRef.current;
        if (!element) {
            return;
        }

        let chart: { destroy: () => void } | null = null;
        let cancelled = false;

        ensureDashboardChartScripts()
            .then(() => {
                if (cancelled || !window.ApexCharts) {
                    return;
                }

                chart = new window.ApexCharts(element, {
                    series: [
                        {
                            name: 'Earnings',
                            data: earnings.amounts,
                        },
                    ],
                    chart: {
                        height: 300,
                        type: 'area',
                        toolbar: { show: false },
                        zoom: { enabled: false },
                    },
                    colors: ['rgb(90,102,241)'],
                    stroke: { width: 2, curve: 'smooth' },
                    fill: {
                        type: 'gradient',
                        gradient: {
                            shadeIntensity: 1,
                            opacityFrom: 0.45,
                            opacityTo: 0.05,
                            stops: [0, 90, 100],
                        },
                    },
                    grid: { borderColor: 'rgba(107,114,128,0.1)' },
                    dataLabels: { enabled: false },
                    xaxis: {
                        categories: earnings.labels,
                        labels: {
                            style: { colors: 'rgb(107,114,128)', fontSize: '12px' },
                        },
                    },
                    yaxis: {
                        min: 0,
                        labels: {
                            formatter: (value: number) => `TZS ${Math.round(value).toLocaleString()}`,
                            style: { colors: 'rgb(107,114,128)', fontSize: '11px' },
                        },
                    },
                    tooltip: {
                        y: {
                            formatter: (value: number) => `TZS ${Math.round(value).toLocaleString()}`,
                        },
                    },
                });

                chart.render();
            })
            .catch((error) => {
                console.error('[Dashboard earnings chart]', error);
            });

        return () => {
            cancelled = true;
            chart?.destroy();
        };
    }, [earnings]);

    return <div ref={containerRef} className="min-h-[300px]" />;
}
