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

type ContentMixChartProps = {
    items: DashboardContentMixItem[];
};

export function ContentMixChart({ items }: ContentMixChartProps) {
    const containerRef = useRef<HTMLDivElement>(null);

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

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

        const labels = items.map((item) => item.label);
        const data = items.map((item) => item.count);

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

                chart = new window.ApexCharts(element, {
                    series: [{ data }],
                    chart: {
                        type: 'bar',
                        height: 320,
                        toolbar: { show: false },
                    },
                    plotOptions: {
                        bar: {
                            horizontal: true,
                            borderRadius: 4,
                            borderRadiusApplication: 'end',
                        },
                    },
                    colors: ['#5a66f1'],
                    dataLabels: { enabled: false },
                    grid: { borderColor: 'rgba(107,114,128,0.08)' },
                    xaxis: {
                        categories: labels,
                        labels: {
                            style: { colors: 'rgb(107,114,128)', fontSize: '11px' },
                        },
                    },
                    yaxis: {
                        labels: {
                            style: { colors: 'rgb(107,114,128)', fontSize: '11px' },
                        },
                    },
                });

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

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

    return <div ref={containerRef} id="dashboard-content-mix" className="min-h-[320px]" />;
}
