import React, { useEffect, useMemo, useState } from "react";
import { getRegionEvolution, RegionEvolutionParams, TaxType } from "../../../api/stats";
import { RegionEvolutionPoint } from "../../../models/RegionEvolution";
import { groupByRegion } from "./timeseries.utils";
import { TimeSeriesControls } from "./TimeSeriesControls";
import { TimeSeriesChart} from "./TimeSeriesChart";
import { TimeSeriesDetails } from "./TimeSeriesDetails";
import "./../../utils/Chart.css";

const USE_MOCK_DATA = false;

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

  // Filters
  const [selectedTax, setSelectedTax] = useState<TaxType>("tfpb");
  const [startYear, setStartYear] = useState<number>(2019);
  const [endYear, setEndYear] = useState<number>(2022);

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

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

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

        if (USE_MOCK_DATA) {
          if (!cancelled) setRaw([]);
        } else {
          const params: RegionEvolutionParams = { tax: selectedTax, startYear, endYear };
          const res = await getRegionEvolution(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, startYear, endYear]);

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

  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 detailsRegion = selectedRegion;
  const regionDetails = detailsRegion ? series.get(detailsRegion) : null;

  return (
    <div className="container">
      <TimeSeriesControls
        selectedTax={selectedTax}
        startYear={startYear}
        endYear={endYear}
        onTaxChange={(t) => {
          setSelectedTax(t);
          setSelectedRegion(null);
        }}
        onStartYearChange={(y) => setStartYear(y)}
        onEndYearChange={(y) => setEndYear(y)}
      />

      <div className="chart-and-details">
        <TimeSeriesChart
          raw={raw}
          series={series}
          selectedRegion={selectedRegion}
          onSelectRegion={(region) => setSelectedRegion(region)}
        />

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

export default TimeSeries;
