// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
"use client";
import { useState } from "react";
import Link from "next/link";
import { useLang } from "./LangContext";
import LeadForm from "./LeadForm";
import RadarMap from "./RadarMap";
import {
  BuildingGlyph,
  ConfidenceDial,
  CountUp,
  EraLine,
  locNum,
  LotDiagram,
  ValueSplit,
} from "./MetricViz";
import type { EstimateResult } from "@/lib/engine";
import type { UnitEstimate } from "@/lib/estimator";
import type { TKey } from "@/lib/i18n";

const fmt = (v: number | null | undefined, lang: string) =>
  v == null
    ? "—"
    : new Intl.NumberFormat(lang === "fr" ? "fr-CA" : "en-CA", {
        style: "currency",
        currency: "CAD",
        maximumFractionDigits: 0,
      }).format(v);

const signed = (v: number, lang: string) =>
  `${v >= 0 ? "+" : "−"}${fmt(Math.abs(Math.round(v)), lang)}`;

function Chip({ k, v }: { k: string; v: string | number }) {
  return (
    <div className="kv-cell">
      <p className="k">{k}</p>
      <p className="v break-words">{v}</p>
    </div>
  );
}

export default function ResultView({ data }: { data: UnitEstimate }) {
  const { lang, t } = useLang();
  const [activeComp, setActiveComp] = useState<string | null>(null);
  const r: EstimateResult = data.result;
  const u = data.unit;
  const s = u?.specs;
  const fr = lang === "fr";
  const histMax = Math.max(...(u?.history.map((h) => h.value ?? 0) ?? [0]), 1);
  const moneyFmt = (v: number) =>
    new Intl.NumberFormat(fr ? "fr-CA" : "en-CA", {
      style: "currency",
      currency: "CAD",
      maximumFractionDigits: 0,
    }).format(Math.round(v / 100) * 100);

  return (
    <div className="space-y-10 py-8">
      {/* fil d'ariane */}
      <nav className="vp-mono flex flex-wrap items-center gap-2 text-[11.5px] uppercase tracking-[0.06em] text-ink-3">
        <Link href="/" className="border-b-[1.5px] border-transparent hover:border-green hover:text-green">
          Vrai-Prix
        </Link>
        <span>/</span>
        <span>{u ? `${u.adresse ?? ""} · ${u.municipalite ?? ""}` : t("manualTitle")}</span>
      </nav>

      {/* ---- Panneau prix ---- */}
      <section className="vp-card rise p-6 sm:p-8">
        <div className="flex flex-wrap items-start justify-between gap-6">
          <div className="min-w-0 flex-1">
            <span className="kicker">{t("estimatedValue")}</span>
            {u && (
              <h1 className="vp-display mt-2 text-[clamp(20px,3vw,28px)] font-bold uppercase leading-tight tracking-[-0.02em]">
                {u.adresse}
                {s?.apt ? ` app. ${s.apt}` : ""}
                {u.municipalite ? <span className="text-ink-3"> · {u.municipalite}</span> : null}
              </h1>
            )}
            <p className="vp-display mt-3 text-[clamp(44px,7vw,72px)] font-bold leading-none tracking-[-0.04em]">
              <CountUp value={r.estimate} format={moneyFmt} />
            </p>
            <div className="mt-5 flex flex-wrap items-center gap-x-6 gap-y-3">
              <div>
                <p className="klabel">{t("range")}</p>
                <p className="vp-display text-[19px] font-bold">
                  {fmt(r.low, lang)} <span className="text-ink-3">→</span> {fmt(r.high, lang)}
                </p>
              </div>
              {u?.valeurRole != null && (
                <div>
                  <p className="klabel">{t("assessed")}</p>
                  <p className="vp-display text-[19px] font-bold text-ink-2">{fmt(u.valeurRole, lang)}</p>
                </div>
              )}
              {u?.valeurRole != null && u.valeurRole > 0 && r.estimate > 0 && (
                <div>
                  <p className="klabel">{fr ? "Écart vs rôle" : "vs assessment"}</p>
                  <p className="vp-display text-[19px] font-bold text-green-deep">
                    {r.estimate >= u.valeurRole ? "+" : ""}
                    {((r.estimate / u.valeurRole - 1) * 100).toFixed(0)} %
                  </p>
                </div>
              )}
            </div>
            {u && (
              <div className="mt-6 flex flex-wrap gap-2.5">
                <a
                  href={`/api/report?id=${encodeURIComponent(u.id)}`}
                  className="btn btn-primary"
                  download
                >
                  {fr ? "Rapport PDF" : "PDF report"} ↓
                </a>
                <a
                  href={`/api/report/pro?id=${encodeURIComponent(u.id)}`}
                  className="btn btn-ghost"
                  download
                  title={fr ? "Structure de rapport d'évaluation — présentation bancaire" : "Appraisal-style structure — bank presentation"}
                >
                  {fr ? "Rapport détaillé format professionnel (banque)" : "Detailed professional report (bank)"} ↓
                </a>
              </div>
            )}
          </div>
          <div className="shrink-0">
            <ConfidenceDial
              pct={r.confidencePct}
              level={r.confidenceLevel}
              label={`${t("confidence")} — ${t(`conf${r.confidenceLevel}` as TKey)}`}
            />
          </div>
        </div>
        <p className="vp-mono mt-5 border-t-[1.5px] border-dashed border-[rgba(20,24,20,0.14)] pt-3 text-[10.5px] uppercase tracking-[0.05em] text-ink-3">
          {t("disclaimer")}
        </p>
      </section>

      {/* ---- Portrait de la propriété (bento du registre) ---- */}
      {u && s && (
        <section>
          <span className="kicker">{fr ? "Registre officiel — dessiné par les données" : "Official record — drawn by the data"}</span>
          <h2 className="vp-display mt-2 text-[22px] font-bold uppercase tracking-[-0.02em]">
            {fr ? "Portrait de la propriété" : "Property portrait"}
          </h2>
          <div className="mt-4 grid gap-4 lg:grid-cols-3">
            {/* Bâtiment */}
            <div className="vp-card vp-card-hover rise p-5" style={{ animationDelay: "60ms" }}>
              <p className="klabel mb-1 border-b-[1.5px] border-dashed border-[rgba(20,24,20,0.14)] pb-2">
                {fr ? "Bâtiment" : "Building"}
              </p>
              <div className="flex justify-center py-2">
                <BuildingGlyph
                  floors={s.nbEtages}
                  dwellings={u.nbLogements}
                  genre={s.genreConstruction}
                  yearBuilt={u.anneeConstruction}
                  floorAreaM2={u.aireEtagesM2}
                  lang={lang}
                />
              </div>
              <EraLine year={u.anneeConstruction} lang={lang} />
              <div className="mt-3 grid grid-cols-2 gap-2">
                <Chip k={fr ? "Aire d'étages" : "Floor area"} v={u.aireEtagesM2 ? locNum(u.aireEtagesM2, lang, { unit: "m²" }) : "—"} />
                <Chip k={fr ? "Étages × logements" : "Storeys × dwellings"} v={`${s.nbEtages ?? "—"} × ${u.nbLogements ?? "—"}`} />
                <Chip k={fr ? "Genre" : "Style"} v={s.genreConstruction ?? "—"} />
                <Chip k={fr ? "Lien physique" : "Physical link"} v={s.lienPhysique ?? "—"} />
              </div>
            </div>
            {/* Terrain */}
            <div className="vp-card vp-card-hover rise p-5" style={{ animationDelay: "140ms" }}>
              <p className="klabel mb-1 border-b-[1.5px] border-dashed border-[rgba(20,24,20,0.14)] pb-2">
                {fr ? "Terrain — à l'échelle" : "Lot — to scale"}
              </p>
              <div className="flex justify-center py-2">
                <LotDiagram
                  areaM2={u.superficieTerrainM2}
                  frontageM={s.frontTerrainM}
                  footprintM2={
                    u.aireEtagesM2 && s.nbEtages ? u.aireEtagesM2 / Math.max(1, s.nbEtages) : u.aireEtagesM2
                  }
                  lang={lang}
                  isCondo={!!s.apt || (u.nbLogements != null && u.nbLogements >= 1 && !u.superficieTerrainM2)}
                />
              </div>
              <div className="mt-3 grid grid-cols-2 gap-2">
                <Chip k={fr ? "Superficie" : "Area"} v={u.superficieTerrainM2 ? locNum(u.superficieTerrainM2, lang, { unit: "m²" }) : "—"} />
                <Chip k={fr ? "Frontage" : "Frontage"} v={s.frontTerrainM ? locNum(s.frontTerrainM, lang, { unit: "m" }) : "—"} />
                <Chip k="CUBF" v={s.cubf ?? "—"} />
                <Chip k={fr ? "Usage" : "Use"} v={s.cubfLibelle ?? "—"} />
              </div>
            </div>
            {/* Valeur au rôle */}
            <div className="vp-card vp-card-hover rise p-5" style={{ animationDelay: "220ms" }}>
              <p className="klabel mb-1 border-b-[1.5px] border-dashed border-[rgba(20,24,20,0.14)] pb-2">
                {fr ? "Valeur au rôle 2026 — composition" : "2026 assessed value — split"}
              </p>
              <p className="vp-display py-2 text-[26px] font-bold tracking-[-0.02em]">
                {fmt(u.valeurRole, lang)}
              </p>
              <ValueSplit
                land={s.valeurTerrain}
                building={s.valeurBatiment}
                previous={s.valeurAnterieure}
                total={u.valeurRole}
                lang={lang}
                labels={{
                  land: fr ? "Terrain" : "Land",
                  building: fr ? "Bâtiment" : "Building",
                  previous: fr ? "Rôle antérieur" : "Previous roll",
                }}
              />
              <div className="mt-3 grid grid-cols-2 gap-2">
                <Chip k={fr ? "Cond. marché au" : "Market cond."} v={s.datCondMarche ?? "—"} />
                <Chip k={fr ? "Matricule" : "Roll no."} v={s.matricule ?? "—"} />
              </div>
            </div>
          </div>
          {/* registre brut complet */}
          <details className="vp-card mt-4 p-5">
            <summary className="vp-mono cursor-pointer text-[11px] font-bold uppercase tracking-[0.08em] text-green-deep">
              {fr ? "▸ Toutes les données du registre (brutes)" : "▸ All registry data (raw)"}
            </summary>
            <div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
              <Chip k={fr ? "Année construction" : "Year built"} v={u.anneeConstruction ? `${u.anneeConstruction}${s.anneeEstimee === "E" ? (fr ? " (estimée)" : " (est.)") : ""}` : "—"} />
              <Chip k={fr ? "Locaux non résid." : "Non-res. units"} v={s.nbLocauxNonResid ?? "—"} />
              <Chip k={fr ? "Chambres locatives" : "Rental rooms"} v={s.nbChambresLocatives ?? "—"} />
              <Chip k={fr ? "Unité de voisinage" : "Neighbourhood"} v={s.uniteVoisinage || "—"} />
              <Chip k={fr ? "Arrondissement" : "Borough"} v={s.arrond || "—"} />
              <Chip k={fr ? "Adresses sur l'unité" : "Addresses"} v={s.nAdresses ?? "—"} />
              <Chip k={fr ? "Valeur terrain" : "Land value"} v={fmt(s.valeurTerrain, lang)} />
              <Chip k={fr ? "Valeur bâtiment" : "Building value"} v={fmt(s.valeurBatiment, lang)} />
              <Chip k={fr ? "Rôle antérieur" : "Previous roll"} v={fmt(s.valeurAnterieure, lang)} />
              <Chip k="ID provincial" v={u.id} />
            </div>
          </details>
        </section>
      )}

      {/* ---- Transparence du calcul ---- */}
      <section>
        <span className="kicker">{fr ? "Transparence" : "Transparency"}</span>
        <h2 className="vp-display mt-2 text-[22px] font-bold uppercase tracking-[-0.02em]">
          {t("whyTitle")}
        </h2>
        <div className="mt-4 grid gap-4 sm:grid-cols-2">
          <div className="vp-card vp-card-hover rise p-5">
            <p className="klabel">{t("modelPart")}</p>
            <p className="vp-display mt-2 text-[30px] font-bold tracking-[-0.03em]">
              {r.modelEstimate != null ? (
                <CountUp value={r.modelEstimate} format={moneyFmt} />
              ) : (
                "—"
              )}
            </p>
            <p className="vp-mono mt-1 text-[11px] uppercase tracking-[0.06em] text-green-deep">
              {t("weightModel")} : {(r.modelWeight * 100).toFixed(0)} %
            </p>
          </div>
          <div className="vp-card vp-card-hover rise p-5" style={{ animationDelay: "100ms" }}>
            <p className="klabel">{t("compsPart")}</p>
            <p className="vp-display mt-2 text-[30px] font-bold tracking-[-0.03em]">
              {r.compsEstimate != null ? (
                <CountUp value={r.compsEstimate} format={moneyFmt} />
              ) : (
                "—"
              )}
            </p>
            <p className="vp-mono mt-1 text-[11px] uppercase tracking-[0.06em] text-green-deep">
              {t("weightComps")} : {((1 - r.modelWeight) * 100).toFixed(0)} % · {r.nCompsUsed} comps
              {r.compsDispersionPct != null ? ` · ±${r.compsDispersionPct} %` : ""}
            </p>
          </div>
        </div>
      </section>

      {/* ---- Historique ---- */}
      {u && u.history.some((h) => h.value != null) && (
        <section>
          <span className="kicker">2021 → 2026</span>
          <h2 className="vp-display mt-2 text-[22px] font-bold uppercase tracking-[-0.02em]">
            {t("history")}
          </h2>
          <div className="vp-card rise mt-4 p-5 sm:p-6">
            <div className="flex flex-col gap-2">
              {u.history.map((h, i) => {
                const prev = i > 0 ? u.history[i - 1].value : null;
                const yoy =
                  h.value != null && prev != null && prev > 0
                    ? ((h.value / prev - 1) * 100)
                    : null;
                return (
                  <div key={h.year} className="hbar-row grid grid-cols-[44px_1fr_auto] items-center gap-2 sm:grid-cols-[52px_1fr_auto] sm:gap-3">
                    <span className="vp-mono text-[12px] font-bold">{h.year}</span>
                    <span className="hbar-track">
                      <span
                        className="hbar-fill grow-x"
                        style={{
                          width: `${((h.value ?? 0) / histMax) * 100}%`,
                          animationDelay: `${i * 90}ms`,
                          background: h.year === 2026 ? "var(--ink)" : undefined,
                        }}
                      />
                    </span>
                    <span className="vp-mono flex items-center justify-end gap-2 text-[12px] font-bold">
                      {fmt(h.value, lang)}
                      {yoy != null && (
                        <span className={`rounded-[4px] border border-ink px-1 py-px text-[9px] ${yoy >= 0 ? "bg-lime-soft text-green-deep" : "bg-[var(--danger-soft)] text-[var(--danger)]"}`}>
                          {yoy >= 0 ? "+" : ""}
                          {yoy.toFixed(0)} %
                        </span>
                      )}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>
        </section>
      )}

      {/* ---- Plan des comparables (carte maison) ---- */}
      <section>
        <span className="kicker">
          {r.nCompsUsed} {fr ? "ventes réelles" : "real sales"}
        </span>
        <h2 className="vp-display mt-2 text-[22px] font-bold uppercase tracking-[-0.02em]">
          {t("compsTitle")}
        </h2>
        <div className="mt-4 grid items-start gap-4 lg:grid-cols-[1.05fr_1fr]">
          <div className="overflow-hidden rounded-[10px] border-[1.5px] border-ink shadow-[8px_8px_0_rgba(20,24,20,0.08)]">
            <RadarMap
              subject={{
                lat: u?.lat ?? r.comps[0]?.lat ?? 46.81,
                lng: u?.lng ?? r.comps[0]?.lng ?? -71.21,
                label: u?.adresse ?? (fr ? "Propriété estimée" : "Subject property"),
              }}
              comps={r.comps.map((c) => ({
                id: c.id,
                lat: c.lat,
                lng: c.lng,
                label: `${c.street ?? ""}, ${c.city ?? ""}`,
                price: fmt(c.amount, lang),
                adjusted: fmt(Math.round(c.adjustedPrice), lang),
                date: c.date,
                distanceM: c.distanceM,
                weight: c.weight,
              }))}
              highlight={activeComp}
              onHover={setActiveComp}
            />
          </div>
          <div className="src-wrap max-h-[560px] overflow-y-auto">
            <table className="src-table">
              <thead className="sticky top-0 z-10">
                <tr>
                  <th>#</th>
                  <th>{fr ? "Vente" : "Sale"}</th>
                  <th className="text-right">{t("adjusted")}</th>
                </tr>
              </thead>
              <tbody>
                {r.comps.map((c, i) => (
                  <tr
                    key={c.id}
                    onMouseEnter={() => setActiveComp(c.id)}
                    onMouseLeave={() => setActiveComp(null)}
                    className={activeComp === c.id ? "!bg-lime-soft" : ""}
                  >
                    <td>
                      <span
                        className={`vp-mono inline-flex h-6 w-6 items-center justify-center rounded-full border-[1.5px] border-ink text-[11px] font-bold ${
                          activeComp === c.id ? "bg-lime text-ink" : "bg-green text-paper"
                        }`}
                      >
                        {i + 1}
                      </span>
                    </td>
                    <td>
                      <p className="font-semibold leading-tight">
                        {c.street}, {c.city}
                      </p>
                      <p className="vp-mono mt-0.5 text-[10.5px] uppercase tracking-[0.04em] text-ink-3">
                        {c.date} · {c.distanceM < 1000 ? `${Math.round(c.distanceM)} m` : `${(c.distanceM / 1000).toFixed(1)} km`} ·{" "}
                        {t("sold")} {fmt(c.amount, lang)}
                      </p>
                      <p className="vp-mono mt-0.5 text-[10.5px] text-ink-2">
                        {t("adjTime")} {signed(c.adjTime, lang)} · {t("adjArea")} {signed(c.adjArea, lang)} ·{" "}
                        {t("adjAge")} {signed(c.adjAge, lang)}
                      </p>
                    </td>
                    <td className="vp-display text-right font-bold">
                      {fmt(Math.round(c.adjustedPrice), lang)}
                      <p className="vp-mono text-[10px] font-normal text-ink-3">
                        {t("weight")} {(c.weight * 100).toFixed(0)} %
                      </p>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </section>

      {/* ---- Lead ---- */}
      <section className="rounded-[10px] border-[1.5px] border-ink bg-ink p-6 text-paper shadow-[8px_8px_0_rgba(20,24,20,0.2)] sm:p-8">
        <h2 className="vp-display text-[22px] font-bold uppercase tracking-[-0.02em] text-lime">
          {t("leadTitle")}
        </h2>
        <div className="mt-4 max-w-xl">
          <LeadForm unitId={u?.id ?? null} estimate={r.estimate} />
        </div>
      </section>
    </div>
  );
}
