import { useEffect, useState } from "react";
import { getCategorie, getDipendenti, getStatistiche } from "../api/client";
import FiltriRimborsi from "../components/FiltriRimborsi";
import type { CategoriaSpesa, StatisticaRimborso, Utente } from "../types";

function formatEuro(n: number) {
  return n.toLocaleString("it-IT", { style: "currency", currency: "EUR" });
}

export default function Statistiche() {
  const [stats, setStats] = useState<StatisticaRimborso[]>([]);
  const [categorie, setCategorie] = useState<CategoriaSpesa[]>([]);
  const [dipendenti, setDipendenti] = useState<Pick<Utente, "id" | "nome" | "cognome">[]>([]);
  const [filtri, setFiltri] = useState({ stato: "", categoriaId: "", mese: "", dipendenteId: "" });
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([getCategorie(), getDipendenti()])
      .then(([cats, dips]) => { setCategorie(cats); setDipendenti(dips); });
  }, []);

  useEffect(() => {
    setLoading(true);
    setError(null);
    getStatistiche({
      mese: filtri.mese || undefined,
      categoriaId: filtri.categoriaId ? Number(filtri.categoriaId) : undefined,
      dipendenteId: filtri.dipendenteId ? Number(filtri.dipendenteId) : undefined,
    })
      .then(setStats)
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, [filtri.categoriaId, filtri.mese, filtri.dipendenteId]);

  return (
    <div className="page">
      <h1>Statistiche rimborsi</h1>
      <p className="muted">Dati aggregati per mese e categoria</p>

      <FiltriRimborsi
        filtri={filtri}
        onChange={setFiltri}
        categorie={categorie}
        dipendenti={dipendenti}
        showDipendente
      />

      {error && <p className="error">{error}</p>}
      {loading ? (
        <p className="loading">Caricamento...</p>
      ) : stats.length === 0 ? (
        <p className="muted">Nessun dato disponibile.</p>
      ) : (
        <table className="table">
          <thead>
            <tr>
              <th>Mese</th>
              <th>Categoria</th>
              <th>N. richieste</th>
              <th>Totale richiesto</th>
              <th>Totale approvato</th>
              <th>Totale liquidato</th>
            </tr>
          </thead>
          <tbody>
            {stats.map((s) => (
              <tr key={`${s.mese}-${s.categoria}`}>
                <td>{s.mese}</td>
                <td>{s.categoria}</td>
                <td>{s.numeroRichieste}</td>
                <td>{formatEuro(s.totaleRichiesto)}</td>
                <td>{formatEuro(s.totaleApprovato)}</td>
                <td>{formatEuro(s.totaleLiquidato)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );
}
