'use client'

import { useState, useEffect } from 'react'
import { Doughnut } from 'react-chartjs-2'
import { Chart as ChartJS, ArcElement, Tooltip, Legend, TooltipItem } from 'chart.js'
import ChartDataLabels from 'chartjs-plugin-datalabels'
import { TAX_TYPES, YEARS, COLORS } from '../../constants'
import { getRegionDistribution, prepareChartData, RegionDistribution } from '../../services/diagram.services'
import ErrorDiv from '../molecules/ErrorDiv'

ChartJS.register(ArcElement, Tooltip, Legend, ChartDataLabels)

export default function Diagram() {
    const [taxType, setTaxType] = useState('th')
    const [year, setYear] = useState(2019)
    const [topCount, setTopCount] = useState(9)
    const [data, setData] = useState<RegionDistribution[]>([])
    const [maxRegions, setMaxRegions] = useState(20)
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<string | null>(null)

    // Load number of regions on mount
    useEffect(() => {
        const loadMaxRegions = async () => {
            try {
                const result = await getRegionDistribution(taxType, year)
                setMaxRegions(result.length)
            } catch {
                // Keep default value on error
            }
        }
        loadMaxRegions()
    }, [taxType, year])

    const handleSubmit = async () => {
        setLoading(true)
        setError(null)
        try {
            const result = await getRegionDistribution(taxType, year)
            setMaxRegions(result.length)
            const chartData = prepareChartData(result, topCount)
            setData(chartData)
        } catch (e) {
            setData([])
            setError(e instanceof Error ? e.message : 'Une erreur est survenue')
        } finally {
            setLoading(false)
        }
    }

    const chartConfig = {
        labels: data.map(d => d.region),
        datasets: [
            {
                data: data.map(d => d.total_amount),
                backgroundColor: COLORS,
                borderColor: '#1a1d21',
                borderWidth: 2,
            },
        ],
    }

    const chartOptions = {
        responsive: true,
        maintainAspectRatio: true,
        aspectRatio: 1.5,
        plugins: {
            legend: {
                position: 'right' as const,
                labels: {
                    color: '#b0afaf',
                    padding: 25,
                    font: { size: 18 },
                    boxWidth: 30,
                    boxHeight: 30,
                },
            },
            tooltip: {
                backgroundColor: '#212529',
                borderColor: '#3a3f44',
                borderWidth: 1,
                titleFont: { size: 18 },
                bodyFont: { size: 16 },
                padding: 12,
                callbacks: {
                    label: (ctx: TooltipItem<'doughnut'>) => {
                        const region = data[ctx.dataIndex]
                        if (!region) return ''
                        const amount = region.total_amount ? (region.total_amount / 1_000_000).toFixed(2) : '0.00'
                        const percentage = region.percentage ? region.percentage.toFixed(2) : '0.00'
                        
                        const lines = [`${region.region}`, `Volume: ${amount} M€`, `Part: ${percentage}%`]
                        
                        // If it's "Others", add the list of regions
                        if (region.region === 'Autres' && region.otherRegions) {
                            lines.push('', 'Régions incluses:')
                            region.otherRegions.forEach((r: string) => lines.push(`  • ${r}`))
                        }
                        
                        return lines
                    },
                },
            },
            datalabels: {
                color: '#fff',
                font: {
                    weight: 'bold' as const,
                    size: 24,
                },
                formatter: (_value: unknown, ctx: { dataIndex: number }) => {
                    const region = data[ctx.dataIndex]
                    if (!region || !region.percentage) return ''
                    // Only display percentage if greater than 3%
                    return region.percentage >= 3 ? `${region.percentage.toFixed(1)}%` : ''
                },
            },
        },
    }

    return (
        <div className="p-6 text-white flex flex-col gap-6">
            <h2 className="text-lg font-semibold">Répartition des Volumes Collectés par Région</h2>

            <div className="flex flex-wrap gap-4 items-end">
                <div className="flex flex-col gap-1">
                    <label className="text-xs text-[#b0afaf] uppercase">Taxe</label>
                    <select
                        value={taxType}
                        onChange={e => setTaxType(e.target.value)}
                        className="bg-[#212529] border border-[#3a3f44] rounded px-3 py-1.5 text-white text-sm"
                    >
                        {TAX_TYPES.map(t => (
                            <option key={t} value={t}>
                                {t.toUpperCase()}
                            </option>
                        ))}
                    </select>
                </div>

                <div className="flex flex-col gap-1">
                    <label className="text-xs text-[#b0afaf] uppercase">Année</label>
                    <select
                        value={year}
                        onChange={e => setYear(Number(e.target.value))}
                        className="bg-[#212529] border border-[#3a3f44] rounded px-3 py-1.5 text-white text-sm"
                    >
                        {YEARS.map(y => (
                            <option key={y} value={y}>
                                {y}
                            </option>
                        ))}
                    </select>
                </div>

                <div className="flex flex-col gap-1">
                    <label className="text-xs text-[#b0afaf] uppercase">Nombre de régions</label>
                    <select
                        value={topCount}
                        onChange={e => setTopCount(Number(e.target.value))}
                        className="bg-[#212529] border border-[#3a3f44] rounded px-3 py-1.5 text-white text-sm"
                    >
                        {Array.from({ length: maxRegions - 4 }, (_, i) => i + 5).map(n => (
                            <option key={n} value={n}>
                                {n}
                            </option>
                        ))}
                    </select>
                </div>

                <button
                    onClick={handleSubmit}
                    disabled={loading}
                    className="bg-[#8884d8] hover:bg-[#7773c7] disabled:opacity-50 text-white text-sm px-4 py-1.5 rounded transition-colors"
                >
                    {loading ? 'Chargement...' : 'Afficher'}
                </button>
            </div>

            {error && <ErrorDiv message={error} />}

            {!error && data.length > 0 && (
                <div className="w-full">
                    <div className="w-full" style={{ height: '900px' }}>
                        <Doughnut data={chartConfig} options={chartOptions} />
                    </div>
                </div>
            )}
        </div>
    )
}
