// -----------------------------------------------------------------------------
// Forma-Ka — Agrégateur de formations (province de Québec)
// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
// pages/Stats.tsx : portrait de l'offre de formation — totaux, répartition par
//   type (barres), santé des synchronisations récentes.
// -----------------------------------------------------------------------------
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { Stats, fetchSources, fetchStats, registerSourceNames, sourceName } from "../api";

export default function StatsPage() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchSources().then((r) => registerSourceNames(r.sources)).catch(() => {});
    fetchStats().then(setStats).catch((e) => setError(String(e)));
  }, []);

  if (error)
    return (
      <div className="notice container">
        <div className="big">⚠️</div>
        <h2>Impossible de charger les statistiques</h2>
        <p>{error}</p>
      </div>
    );

  if (!stats)
    return (
      <div className="container">
        <div className="notice">Chargement…</div>
      </div>
    );

  const maxType = Math.max(1, ...stats.par_type.map((t) => t.n));

  return (
    <div className="container sources">
      <span className="kicker">Portrait — l'offre de formation au Québec</span>
      <h1>Statistiques</h1>
      <p className="sub">
        Portrait en direct des formations actives agrégées par Forma-Ka, tous
        établissements confondus.
      </p>

      <div className="stat-row" style={{ marginBottom: 28 }}>
        <span className="stat-chip"><b>{stats.total}</b> formations actives</span>
        <span className="stat-chip"><b>{stats.sources}</b> établissements</span>
        {(stats.gratuites ?? 0) > 0 && (
          <span className="stat-chip"><b>{stats.gratuites}</b> gratuites</span>
        )}
        {(stats.en_ligne ?? 0) > 0 && (
          <span className="stat-chip"><b>{stats.en_ligne}</b> en ligne</span>
        )}
        {stats.avg_price != null && (
          <span className="stat-chip">
            prix moyen (affiché) <b>{Math.round(stats.avg_price).toLocaleString("fr-CA")} $</b>
          </span>
        )}
        {stats.avg_hours != null && (
          <span className="stat-chip">
            durée moyenne <b>{Math.round(stats.avg_hours)} h</b>
          </span>
        )}
      </div>

      <h2 style={{ fontFamily: "var(--font-display)" }}>Par type de formation</h2>
      <div style={{ display: "grid", gap: 8, marginBottom: 36 }}>
        {stats.par_type.map((t) => (
          <Link
            key={t.t || "(sans type)"}
            to={`/?training_type=${encodeURIComponent(t.t)}`}
            style={{
              display: "grid", gridTemplateColumns: "180px 1fr 56px",
              alignItems: "center", gap: 12, color: "var(--ink)",
            }}
          >
            <span style={{ fontWeight: 600, fontSize: ".92rem" }}>{t.t || "Autre"}</span>
            <span style={{ background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 6, overflow: "hidden", height: 18 }}>
              <span style={{
                display: "block", height: "100%",
                width: `${Math.max(2, Math.round((t.n / maxType) * 100))}%`,
                background: "var(--lime)", borderRight: "1px solid var(--ink)",
              }} />
            </span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: ".85rem", textAlign: "right" }}>
              {t.n}
            </span>
          </Link>
        ))}
      </div>

      <h2 style={{ fontFamily: "var(--font-display)" }}>Synchronisations récentes</h2>
      <div className="src-wrap">
        <table className="src-table">
          <thead>
            <tr>
              <th>Source</th>
              <th>Quand</th>
              <th style={{ textAlign: "right" }}>Trouvées</th>
              <th style={{ textAlign: "right" }}>+ / ~ / −</th>
              <th>État</th>
            </tr>
          </thead>
          <tbody>
            {stats.recent_syncs.map((s, i) => (
              <tr key={i}>
                <td>{sourceName(s.source)}</td>
                <td style={{ color: "var(--ink-3)" }}>
                  {new Date(s.ts * 1000).toLocaleString("fr-CA")}
                </td>
                <td style={{ textAlign: "right" }}>{s.found}</td>
                <td style={{ textAlign: "right", fontFamily: "var(--font-mono)", fontSize: ".85rem" }}>
                  {s.added} / {s.updated} / {s.removed}
                </td>
                <td>
                  {s.ok ? (
                    s.message === "ok"
                      ? <span className="pill ok">ok</span>
                      : <span className="pill todo" title={s.message}>alerte</span>
                  ) : (
                    <span className="pill todo" title={s.message}>échec</span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
