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

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>("th");
    const [year, setYear] = useState<number>(2019);

    const [selectedRegion, setSelectedRegion] = useState<string | null>(null);

    const series = useMemo(() => groupByRegion(raw), [raw]);

    const filtereRaw = useMemo(() => {
      let threshold: number;
      switch (selectedTax) {
        case "tfpnb":
          threshold = 100_000;
          break;
        case "tfpb":
          threshold = 500_000_000;
          break;
        case "th":
          threshold = 20_000_000;
          break;
        case "cfe":
          threshold = 10_000_000;
          break;
        default:
          threshold = 100_000;
          break;
      }
      const others: RegionalDistributionPoint = {
        regionCode: "0",
        regionName: "Autres",
        collectedVolume: 0,
      };
      series.set("Autres", [others]);

      const filtered: RegionalDistributionPoint[] = [];

      raw.forEach((item) => {
        if (item.collectedVolume > threshold) {
            filtered.push(item);
        } else {
            others.collectedVolume += item.collectedVolume;
        }
      });

      return others.collectedVolume > 0 ? [...filtered, others] : filtered;
    }, [raw]);

    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>;

    const regionDetails = selectedRegion ? series.get(selectedRegion) : null;
    
    return (
        <div className="container">
          <CircularDiagramControls
            selectedTax={selectedTax}
            year={year}
            onTaxChange={(t) => {
              setSelectedTax(t);
              setSelectedRegion(null);
            }}
            onYearChange={(y) => setYear(y)}
          />

          {filtereRaw.length > 0 ? <div className="chart-and-details">
            <CircularDiagramChart
              filtereRaw={filtereRaw}
              onSelectRegion={(region) => setSelectedRegion(region)}
            />
          </div>
          : <p className="no-data-message">Aucune donnée.</p>}

          {selectedRegion && regionDetails && (
            <CircularDiagramDetail
              regionDetails={regionDetails}
              showClose={!!selectedRegion}
              onClose={() => setSelectedRegion(null)}
            />
          )}
        </div>
    );
};

export default CircularDiagram;