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

type ClientGrowthPanelProps = {
    growth: DashboardClientGrowth;
};

function trendMeta(trend: DashboardClientGrowth['trend']): { className: string; icon: string } {
    if (trend === 'up') {
        return { className: 'text-success', icon: 'ti ti-trending-up' };
    }

    if (trend === 'down') {
        return { className: 'text-danger', icon: 'ti ti-trending-down' };
    }

    return { className: 'text-gray-500 dark:text-white/60', icon: 'ri-subtract-line' };
}

export function ClientGrowthPanel({ growth }: ClientGrowthPanelProps) {
    const chartRef = useRef<HTMLDivElement>(null);
    const trend = trendMeta(growth.trend);

    const changeLabel = growth.trendLabel;

    useEffect(() => {
        const element = chartRef.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: 'New clients', data: [growth.lastMonth, growth.thisMonth] }],
                    chart: {
                        type: 'bar',
                        height: 200,
                        toolbar: { show: false },
                    },
                    plotOptions: {
                        bar: {
                            horizontal: false,
                            columnWidth: '42%',
                            borderRadius: 6,
                            borderRadiusApplication: 'end',
                        },
                    },
                    colors: ['rgb(203,213,225)', 'rgb(90,102,241)'],
                    dataLabels: { enabled: true },
                    grid: { borderColor: 'rgba(107,114,128,0.1)' },
                    xaxis: {
                        categories: [growth.lastMonthLabel, growth.thisMonthLabel],
                        labels: {
                            style: { colors: 'rgb(107,114,128)', fontSize: '11px' },
                        },
                    },
                    yaxis: {
                        min: 0,
                        labels: {
                            style: { colors: 'rgb(107,114,128)', fontSize: '11px' },
                        },
                    },
                    legend: { show: false },
                });

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

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

    return (
        <div className="space-y-5">
            <div>
                <h5 className="text-base font-semibold text-gray-800 dark:text-white">Client growth</h5>
                <p className="mb-0 text-xs text-gray-500 dark:text-white/60">
                    New clients added this month compared with last month
                </p>
            </div>
            <div className="grid grid-cols-12 gap-5">
            <div className="col-span-12 md:col-span-4">
                <div className="box h-full">
                    <div className="box-body">
                        <p className="mb-1 text-sm text-gray-500 dark:text-white/70">Total clients</p>
                        <p className="mb-0 text-3xl font-medium text-gray-800 dark:text-white">{growth.total}</p>
                        <p className="mb-0 mt-2 text-xs text-gray-500 dark:text-white/60">All countries combined</p>
                    </div>
                </div>
            </div>
            <div className="col-span-12 sm:col-span-6 md:col-span-4">
                <div className="box h-full border border-primary/20 bg-primary/5 dark:bg-primary/10">
                    <div className="box-body">
                        <p className="mb-1 text-sm text-gray-500 dark:text-white/70">This month</p>
                        <p className="mb-0 text-xs text-primary">{growth.thisMonthLabel}</p>
                        <div className="mt-2 flex items-center gap-2">
                            <p className="mb-0 text-3xl font-medium text-gray-800 dark:text-white">{growth.thisMonth}</p>
                            <span className="text-sm text-gray-500 dark:text-white/60">new</span>
                        </div>
                    </div>
                </div>
            </div>
            <div className="col-span-12 sm:col-span-6 md:col-span-4">
                <div className="box h-full">
                    <div className="box-body">
                        <p className="mb-1 text-sm text-gray-500 dark:text-white/70">Last month</p>
                        <p className="mb-0 text-xs text-gray-400">{growth.lastMonthLabel}</p>
                        <div className="mt-2 flex items-center gap-2">
                            <p className="mb-0 text-3xl font-medium text-gray-800 dark:text-white">{growth.lastMonth}</p>
                            <span className="text-sm text-gray-500 dark:text-white/60">new</span>
                        </div>
                        <p className={`mb-0 mt-3 text-xs inline-flex items-center ${trend.className}`}>
                            <i className={`${trend.icon} me-1`} />
                            {changeLabel}
                        </p>
                    </div>
                </div>
            </div>
            <div className="col-span-12">
                <div className="box">
                    <div className="box-header">
                        <h5 className="box-title">New clients by month</h5>
                        <p className="mb-0 text-xs text-gray-500 dark:text-white/60">Compare additions this month vs last month</p>
                    </div>
                    <div className="box-body pt-0">
                        <div ref={chartRef} className="min-h-[200px]" />
                    </div>
                </div>
            </div>
            </div>
        </div>
    );
}
