'use client'

import { pie, arc } from "d3-shape";
import { useEffect, useMemo, useState } from "react";
import {taxes} from '@/data/taxes';
import { taxeStats } from "@/type/TaxeStats";

// Types simplifiés pour la clarté


const years = [2018, 2019, 2020, 2021, 2022, 2023];

const COLORS = ["#2563eb", "#16a34a", "#ea580c", "#7c3aed", "#06b6d4", "#f43f5e"];

export default function PieChart() {
    const [taxe, setTaxe] = useState("cves");
    const [selectedYear, setSelectedYear] = useState<number>(2022);
    const [hoveredRegion, setHoveredRegion] = useState<taxeStats | null>(null);
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [data, setData] = useState<taxeStats[]>([]);

    useEffect(() => {
        const fetchData = async () => {
            setIsLoading(true);
            try {
                const res = await fetch(`https://localhost/${taxe}/stats?annee=${selectedYear}&groupBy=region&metric=montant`);
                if (!res.ok) throw new Error("Erreur API");
                const apiData = await res.json();

                // CORRECTION : On s'assure que la clé correspond à "region" utilisée plus bas
                const formatted: taxeStats[] = apiData.member.map((d: any) => ({
                    region: d.label || d.region || "Inconnu",
                    year: selectedYear,
                    value: Number(d.value),
                }));

                setData(formatted);
            } catch (err) {
                console.error("Erreur fetch data:", err);
                setData([]);
            } finally {
                setIsLoading(false);
            }
        };
        fetchData();
    }, [taxe, selectedYear]);

    // 1. Préparation des données et calcul du total
    const { processedData, totalSum } = useMemo(() => {
        const sum = data.reduce((acc, curr) => acc + curr.value, 0);
        return { processedData: data, totalSum: sum };
    }, [data]);

    // 2. Générateurs D3
    const pieGenerator = pie<taxeStats>()
        .value(d => d.value)
        .sort(null); // Garde l'ordre original

    const arcGenerator = arc<any>()
        .innerRadius(120) // Transformé en Donut pour plus de modernité
        .outerRadius(240)
        .cornerRadius(4)
        .padAngle(0.02);

    const arcs = useMemo(() => pieGenerator(processedData), [processedData]);

    return (
        <section className="w-full max-w-5xl bg-white rounded-xl shadow-sm p-6">
            <div className="flex justify-between items-center mb-6">
                <h2 className="text-xl font-semibold text-gray-800">Impôt collecté par région</h2>
                {isLoading && <span className="text-sm text-blue-500 animate-pulse">Chargement...</span>}
            </div>

            <div className="flex gap-4 mb-8">
                <select value={taxe} onChange={e => setTaxe(e.target.value)} className="rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-700 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500m"
                >
                    {taxes.map(t => <option key={t.route} value={t.route}>{t.label}</option>)}
                </select>
                <select value={selectedYear} onChange={e => setSelectedYear(Number(e.target.value))} className="rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-700 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500m"
                >
                    {years.map(y => <option key={y} value={y}>{y}</option>)}
                </select>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-8 items-center">
                <div className="md:col-span-2 flex justify-center relative">
                    <svg width={400} height={400} viewBox="-200 -200 400 400" className="overflow-visible">
                        <g>
                            {arcs.map((d, i) => {
                                const isActive = hoveredRegion === null || hoveredRegion.region === d.data.region;
                                const percentage = ((d.data.value / totalSum) * 100).toFixed(1);

                                return (
                                    <path
                                        key={`arc-${d.data.region}`}
                                        d={arcGenerator(d)!}
                                        fill={COLORS[i % COLORS.length]}
                                        opacity={isActive ? 1 : 0.3}
                                        onMouseEnter={() => setHoveredRegion(d.data)}
                                        onMouseLeave={() => setHoveredRegion(null)}
                                        className="transition-all duration-300 cursor-pointer outline-none"
                                    />
                                );
                            })}
                        </g>
                        {/* Centre du Diagramme */}
                        {hoveredRegion && (
                            <text textAnchor="middle" className="text-lg fill-gray-700">
                                <tspan x="0" dy="0">
                                    {hoveredRegion.region}
                                </tspan>
                                <tspan x="0" dy="1.2em">
                                    {Math.round(hoveredRegion.value).toLocaleString()}€
                                </tspan>
                                <tspan x="0" dy="1.2em">
                                    {((hoveredRegion.value / totalSum) * 100).toFixed(1)}%
                                </tspan>
                            </text>
                        )}
                    </svg>
                </div>

                <div className="md:col-span-3 mt-4">
                    <div className="mt-6 flex flex-wrap gap-4 justify-center custom-scrollbar">
                        {arcs.map((d, i) => {
                            const percentage = totalSum > 0 ? ((d.data.value / totalSum) * 100).toFixed(1) : 0;
                            const isActive = hoveredRegion === null || hoveredRegion.region === d.data.region;

                            return (
                                <div
                                    key={`legend-${d.data.region}`}
                                    onMouseEnter={() => setHoveredRegion(d.data)}
                                    onMouseLeave={() => setHoveredRegion(null)}
                                    className={` flex items-center gap-2 p-2 rounded-md border transition-all ${isActive
                                        ? "bg-gray-50 shadow-sm scale-[1.02]"
                                        : "border-transparent opacity-50 grayscale-[0.5]"
                                        }`}>
                                    <span
                                        className="w-3 h-3 rounded-sm"
                                        style={{ backgroundColor: COLORS[i % COLORS.length] }}
                                    />

                                    <div className="flex flex-col min-w-0">
                                        <span className="text-xs font-bold text-gray-800 truncate">
                                            {d.data.region}
                                        </span>
                                        <div className="flex items-center gap-2">
                                            <span className="text-[10px] text-gray-600 font-semibold">{percentage}%</span>
                                            <span className="text-[10px] text-gray-400 truncate">
                                                {Math.round(d.data.value).toLocaleString()} €
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            </div>
        </section>
    );
}