// -----------------------------------------------------------------------------
// Auto-Ka — Agrégateur de voitures usagées à vendre (province de Québec)
// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
// Stats.tsx : tableau de bord du marché — héros, distributions, classements,
//             parts de marché, aubaines + rapport PDF téléchargeable.
// -----------------------------------------------------------------------------
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { API_BASE, fmtPrice } from "../api";
import { Datum, Donut, HBars, VBars } from "../components/Charts";

interface Detailed {
  total: number;
  sources: number;
  regions: number;
  avg_price: number | null;
  median_price: number | null;
  avg_km: number | null;
  median_km: number | null;
  avg_year: number | null;
  new_7d: number;
  electrified_pct: number;
  price_hist: Datum[];
  km_hist: Datum[];
  year_hist: Datum[];
  by_make: { label: string; n: number; avg_price: number | null }[];
  by_region: { label: string; n: number; avg_price: number | null }[];
  by_body: Datum[];
  by_fuel: Datum[];
  top_models: { label: string; n: number; avg_price: number | null; avg_km: number | null }[];
  top_dealers: { label: string; n: number; avg_price: number | null }[];
  price_drops: {
    uid: string; title: string; year: number | null; price: number;
    prev_price: number; dealer_name: string; city: string;
  }[];
}

const fmtK = (n: number | null) =>
  n == null ? "—" : `${Math.round(n / 1000)}k km`;

export default function StatsPage() {
  const [s, setS] = useState<Detailed | null>(null);

  useEffect(() => {
    fetch(`${API_BASE}/api/stats/detailed`)
      .then((r) => r.json())
      .then(setS)
      .catch(() => {});
  }, []);

  if (!s)
    return (
      <div className="container page">
        <div className="skeleton" style={{ height: 120, marginBottom: 20 }} />
        <div className="skeleton" style={{ height: 340 }} />
      </div>
    );

  const withPrice = (rows: { label: string; n: number; avg_price: number | null }[]): Datum[] =>
    rows.map((r) => ({
      label: r.label, n: r.n,
      extra: r.avg_price ? `moy. ${fmtPrice(r.avg_price)}` : undefined,
    }));

  return (
    <div className="container page">
      <div className="stats-head">
        <div>
          <span className="kicker">Marché</span>
          <h1>Le marché de l'occasion, en direct</h1>
          <p className="lead" style={{ marginBottom: 0 }}>
            Calculé en temps réel sur l'inventaire actif de {s.sources} concessionnaires
            dans {s.regions} régions du Québec.
          </p>
        </div>
        <a className="btn pdf-btn" href={`${API_BASE}/api/stats/rapport.pdf`}>
          ⬇ Télécharger le rapport PDF
        </a>
      </div>

      <div className="stat-grid" style={{ marginTop: 26 }}>
        <div className="stat-tile hero-tile">
          <b>{s.total.toLocaleString("fr-CA")}</b>
          <span>véhicules en vente</span>
        </div>
        <div className="stat-tile">
          <b>{fmtPrice(s.avg_price)}</b>
          <span>prix moyen</span>
        </div>
        <div className="stat-tile">
          <b>{fmtPrice(s.median_price)}</b>
          <span>prix médian</span>
        </div>
        <div className="stat-tile">
          <b>{fmtK(s.avg_km)}</b>
          <span>km moyen</span>
        </div>
        <div className="stat-tile">
          <b>{s.new_7d.toLocaleString("fr-CA")}</b>
          <span>arrivages · 7 jours</span>
        </div>
        <div className="stat-tile">
          <b>{s.electrified_pct} %</b>
          <span>électrifiés (VÉ + hybrides)</span>
        </div>
      </div>

      <div className="panel">
        <h3>💰 Distribution des prix</h3>
        <VBars data={s.price_hist} color="#d94f1e" />
      </div>

      <div className="vd-cols">
        <div className="panel">
          <h3>🛣 Kilométrage (milliers de km)</h3>
          <VBars data={s.km_hist} color="#1f6fb5" height={170} />
        </div>
        <div className="panel">
          <h3>📅 Années-modèles</h3>
          <VBars data={s.year_hist} color="#b58500" height={170} />
        </div>
      </div>

      <div className="vd-cols">
        <div className="panel">
          <h3>🏷 Top marques</h3>
          <HBars data={withPrice(s.by_make)} color="#d94f1e" />
        </div>
        <div className="panel">
          <h3>📍 Par région</h3>
          <HBars data={withPrice(s.by_region)} color="#1f6fb5" />
        </div>
      </div>

      <div className="vd-cols">
        <div className="panel">
          <h3>🚙 Carrosseries</h3>
          <Donut data={s.by_body} />
        </div>
        <div className="panel">
          <h3>⛽ Carburants</h3>
          <Donut data={s.by_fuel} />
        </div>
      </div>

      <div className="panel">
        <h3>🚗 Modèles les plus offerts</h3>
        <HBars
          data={s.top_models.map((m) => ({
            label: m.label, n: m.n,
            extra: `moy. ${fmtPrice(m.avg_price)} · ${fmtK(m.avg_km)}`,
          }))}
          color="#1c7a4d"
        />
      </div>

      {s.price_drops.length > 0 && (
        <section style={{ margin: "30px 0" }}>
          <h2 style={{ marginBottom: 14 }}>📉 Baisses de prix récentes</h2>
          <div className="src-grid">
            {s.price_drops.map((d) => (
              <Link key={d.uid} to={`/vehicule/${encodeURIComponent(d.uid)}`} className="src-card">
                <h3>{d.title}</h3>
                <div className="meta">{d.dealer_name} · {d.city}</div>
                <div className="n">
                  {fmtPrice(d.price)}{" "}
                  <span style={{ fontSize: 13, color: "var(--ink-3)", textDecoration: "line-through" }}>
                    {fmtPrice(d.prev_price)}
                  </span>
                </div>
                <div className="meta" style={{ color: "var(--good)", fontWeight: 700 }}>
                  −{fmtPrice(d.prev_price - d.price)}
                </div>
              </Link>
            ))}
          </div>
        </section>
      )}

      <div className="panel">
        <h3>🏢 Plus grands inventaires</h3>
        <HBars data={withPrice(s.top_dealers)} color="#7d4fc9" />
      </div>
    </div>
  );
}
