import React, { useState, useEffect, useMemo } from "react";
import { getRegionalDistribution, RegionalDistributionParams, TaxType } from "../../../api/stats";
import { RegionalDistributionPoint } from "../../../models/RegionalDistribution";
import "./CircularDiagram.css";
import { CircularDiagramControls } from "./CircularDiagramControls";
import { CircularDiagramChart, HoverPoint } from "./CircularDiagramChart"

const CircularDiagram: React.FC = () => {
    const [raw, setRaw] = useState<RegionalDistributionPoint[]>([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const [selectedTax, setSelectedTax] = useState<TaxType>("tfpb");
    const [year, setYear] = useState<number>(2019);

    useEffect(() => {
        let cancelled = false;

        async function load() {
            try {
            setLoading(true);
            setError(null);

            const params: RegionalDistributionParams = { tax: selectedTax, year };
            const res = await getRegionalDistribution(params);
            if (!cancelled) setRaw(res.member);
            } catch (e: any) {
            if (!cancelled) setError(e.message ?? "Erreur API");
            } finally {
            if (!cancelled) setLoading(false);
            }
        }

        load();
        return () => {
            cancelled = true;
        };
    }, [selectedTax, year]);

    if (loading) return <p className="loading-message">Chargement…</p>;
    if (error) return <p className="error-message">Erreur : {error}</p>;
    if (raw.length === 0) return <p className="no-data-message">Aucune donnée.</p>;

    return (
        <div className="circulardiagram-container">
          <CircularDiagramControls
            selectedTax={selectedTax}
            year={year}
            onTaxChange={(t) => {
              setSelectedTax(t);
            }}
            onYearChange={(y) => setYear(y)}
          />

          <div className="chart-and-details">
            <CircularDiagramChart
              raw={raw}
            />
          </div>
        </div>
    );
};

export default CircularDiagram;