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

type PublishStatusChartProps = {
    status: DashboardPublishStatus;
};

export function PublishStatusChart({ status }: PublishStatusChartProps) {
    const containerRef = useRef<HTMLDivElement>(null);

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

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

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

                chart = new window.ApexCharts(element, {
                    series: [status.active, status.inactive],
                    labels: ['Published', 'Draft / inactive'],
                    chart: {
                        height: 260,
                        type: 'donut',
                    },
                    colors: ['rgb(90,102,241)', 'rgb(203,213,225)'],
                    legend: { position: 'bottom' },
                    dataLabels: { enabled: true },
                    plotOptions: {
                        pie: {
                            donut: {
                                size: '72%',
                                labels: {
                                    show: true,
                                    total: {
                                        show: true,
                                        label: 'Items',
                                        formatter: () => `${status.total}`,
                                    },
                                },
                            },
                        },
                    },
                });

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

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

    if (status.total === 0) {
        return (
            <p className="text-sm text-gray-500 dark:text-white/70 py-8 text-center">
                No publishable content yet. Add clients, services, or portfolio items to see status breakdown.
            </p>
        );
    }

    return <div ref={containerRef} id="dashboard-publish-status" className="min-h-[260px]" />;
}
