import dynamic from 'next/dynamic';
import { useMemo } from 'react';
import { useSelector } from 'react-redux';
import type { ApexOptions } from 'apexcharts';

import type { AcquisitionTableRowInput } from './AcquisitionTable';
import { IRootState } from '@/store';
import { getThemeChartColors, getThemeChartFont, getThemeChartSliceLabelColors } from '@/lib/theme-colors';
import { journeyDonutToolbar } from './journey-chart-options';

const ReactApexChart = dynamic(() => import('react-apexcharts'), { ssr: false });

/** Bucket lebar — tidak per detik/500ms, cukup rentang durasi umum */
const DURATION_BUCKETS = [
    { id: 'lt1', label: '< 1 m', min: 0, max: 1 },
    { id: '1-3', label: '1–3 m', min: 1, max: 3 },
    { id: '3-5', label: '3–5 m', min: 3, max: 5 },
    { id: '5-10', label: '5–10 m', min: 5, max: 10 },
    { id: '10+', label: '10+ m', min: 10, max: Infinity },
] as const;

function bucketForMinutes(minutes: number) {
    const m = Number(minutes) || 0;
    return (
        DURATION_BUCKETS.find((b) => m >= b.min && (b.max === Infinity ? true : m < b.max)) ||
        DURATION_BUCKETS[DURATION_BUCKETS.length - 1]
    );
}

interface LandingPageDurationDonutProps {
    rows?: AcquisitionTableRowInput[];
    isRefreshing?: boolean;
}

const LandingPageDurationDonut = ({ rows = [], isRefreshing = false }: LandingPageDurationDonutProps) => {
    const colorScheme = useSelector((state: IRootState) => state.themeConfig.colorScheme);
    const chartColors = useMemo(() => getThemeChartColors(colorScheme), [colorScheme]);
    const sliceLabelColors = useMemo(
        () => getThemeChartSliceLabelColors(chartColors, colorScheme),
        [chartColors, colorScheme]
    );
    const { labels, series, sessionTotal } = useMemo(() => {
        const counts = new Map<string, number>();
        DURATION_BUCKETS.forEach((b) => counts.set(b.id, 0));

        let total = 0;
        (rows || []).forEach((row) => {
            const weight = Number(row.sessions) || 0;
            if (weight <= 0) return;
            const bucket = bucketForMinutes(Number(row.avg_duration_min) || 0);
            counts.set(bucket.id, (counts.get(bucket.id) || 0) + weight);
            total += weight;
        });

        const activeBuckets = DURATION_BUCKETS.filter((b) => (counts.get(b.id) || 0) > 0);
        return {
            labels: activeBuckets.map((b) => b.label),
            series: activeBuckets.map((b) => counts.get(b.id) || 0),
            sessionTotal: total,
        };
    }, [rows]);

    const options = useMemo<ApexOptions>(
        () => ({
            chart: { type: 'donut', fontFamily: getThemeChartFont(colorScheme), ...journeyDonutToolbar },
            labels,
            colors: chartColors,
            legend: { position: 'bottom', fontSize: '11px' },
            dataLabels: {
                enabled: true,
                formatter: (val) => `${Math.round(Number(val))}%`,
                style: {
                    fontSize: '10px',
                    ...(sliceLabelColors ? { colors: sliceLabelColors } : {}),
                },
            },
            tooltip: {
                y: {
                    formatter: (val, opts) => {
                        const idx = opts?.seriesIndex ?? 0;
                        const count = series[idx] ?? 0;
                        const pct = sessionTotal > 0 ? Math.round((count / sessionTotal) * 1000) / 10 : 0;
                        return `${count.toLocaleString('id-ID')} sessions (${pct}%) · avg ${labels[idx] || ''}`;
                    },
                },
            },
            plotOptions: {
                pie: {
                    donut: {
                        size: '62%',
                        labels: {
                            show: true,
                            total: {
                                show: true,
                                label: 'Sessions',
                                formatter: () => sessionTotal.toLocaleString('id-ID'),
                            },
                        },
                    },
                },
            },
            stroke: { width: 0 },
        }),
        [labels, series, sessionTotal, chartColors, colorScheme, sliceLabelColors]
    );

    if (isRefreshing && !series.length) {
        return (
            <div className="flex min-h-[260px] flex-col items-center justify-center gap-3 rounded-lg border border-[#e8eaed] bg-white dark:border-[#334155] dark:bg-[#0e1726]">
                <span className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-primary border-l-transparent" />
                <p className="text-xs text-gray-500">Memuat distribusi avg time...</p>
            </div>
        );
    }

    if (!series.length) {
        return (
            <p className="text-sm text-gray-400 py-8 text-center">
                Belum ada data avg time landing page.
            </p>
        );
    }

    return (
        <div className="rounded-lg border border-[#e8eaed] bg-white p-3 dark:border-[#334155] dark:bg-[#0e1726]">
            <p className="text-xs text-gray-500 mb-1">Avg time per landing page</p>
            <p className="text-[11px] text-gray-400 mb-2">
                Distribusi sessions per rentang avg time (bucket lebar per menit)
            </p>
            <ReactApexChart options={options} series={series} type="donut" height={300} />
        </div>
    );
};

export default LandingPageDurationDonut;
