import clsx from "clsx";
import { AlertOctagon, CalendarClock, CheckCircle2, Clock, FileWarning, Wallet } from "lucide-react";
import Link from "next/link";
import { utilisateurCourant } from "@/lib/auth";
import { dateLongue, montantCompact } from "@/lib/format";
import { STATUTS_COMMERCIAUX, STATUTS_OPERATIONNELS } from "@/lib/libelles";
import { donneesTableauDeBord, NOMS_SECTIONS, SECTIONS, type EtatSection } from "@/lib/tableau-de-bord";
import { Badge, PastilleSociete, Vide } from "@/components/ui";

export const dynamic = "force-dynamic";

const SOCIETES = [
  { code: undefined, libelle: "Toutes" },
  { code: "MC", libelle: "MC" },
  { code: "ENDIRECT", libelle: "EN DIRECT" },
];

export default async function TableauDeBord({ searchParams }: { searchParams: Promise<{ societe?: string }> }) {
  const { societe } = await searchParams;
  const moi = await utilisateurCourant();
  const d = await donneesTableauDeBord(societe);
  const impayes = d.finances.IMPAYE ?? { nb: 0, montant: 0 };
  const aFacturer = ["A_FACTURER_PROFORMA", "A_FACTURER_FINALE", "A_REGULARISER"].reduce(
    (acc, s) => ({ nb: acc.nb + (d.finances[s]?.nb ?? 0), montant: acc.montant + (d.finances[s]?.montant ?? 0) }),
    { nb: 0, montant: 0 },
  );
  const pipelineTotal = d.pipeline.reduce((a, p) => ({ nb: a.nb + p.nb, montant: a.montant + p.montant }), { nb: 0, montant: 0 });
  const maxPipeline = Math.max(1, ...d.pipeline.map((p) => p.nb));
  const maxRetard = Math.max(1, ...d.retardsParResponsable.map((r) => r.nb));
  const suffixe = societe ? `&societe=${societe}` : "";

  return (
    <div className="mx-auto max-w-7xl space-y-6">
      <div className="flex flex-wrap items-end justify-between gap-3">
        <div>
          <p className="text-sm text-encre-2 first-letter:uppercase">{dateLongue(d.aujourdHui)}</p>
          <h1 className="text-2xl font-semibold tracking-tight">Bonjour {moi.nom}</h1>
        </div>
        <div className="flex rounded-lg border border-bord bg-surface p-0.5 text-sm" role="group" aria-label="Société">
          {SOCIETES.map((s) => (
            <Link
              key={s.libelle}
              href={s.code ? `/?societe=${s.code}` : "/"}
              className={clsx("rounded-md px-3 py-1.5 font-medium", societe === s.code ? "bg-accent text-white" : "text-encre-2 hover:text-encre")}
            >
              {s.libelle}
            </Link>
          ))}
        </div>
      </div>

      {/* 1. Ce qui demande une action aujourd'hui */}
      <section aria-label="Alertes" className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        <Alerte href={`/taches?vue=retard${suffixe}`} nb={d.nbRetards} libelle="Étapes de procédure en retard" icone={AlertOctagon} niveau="critique" />
        <Alerte href={`/taches?vue=jour${suffixe}`} nb={d.echeancesDuJour} libelle="Échéances aujourd'hui" icone={Clock} niveau="attention" />
        <Alerte href={`/dossiers?financier=IMPAYE${suffixe}`} nb={impayes.nb} libelle="Dossiers impayés" detail={impayes.montant ? montantCompact(impayes.montant) : undefined} icone={Wallet} niveau="critique" />
        <Alerte href={`/dossiers?commercial=DEVIS_ENVOYE${suffixe}`} nb={d.devisSansReponse} libelle="Devis sans réponse depuis 7 j" icone={FileWarning} niveau="serieux" />
      </section>

      {/* 2. Indicateurs clés */}
      <section aria-label="Indicateurs" className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        <Indicateur libelle="Dossiers actifs" valeur={d.nbActifs.toLocaleString("fr-FR")} detail="ni perdus, ni clôturés" />
        <Indicateur
          libelle="Confirmés dans les 30 j"
          valeur={d.confirmesAVenir.nb.toLocaleString("fr-FR")}
          detail={d.confirmesAVenir.montant ? `${montantCompact(d.confirmesAVenir.montant)} estimés` : "montants non saisis"}
        />
        <Indicateur
          libelle="Pipeline commercial"
          valeur={pipelineTotal.nb.toLocaleString("fr-FR")}
          detail={pipelineTotal.montant ? `${montantCompact(pipelineTotal.montant)} en jeu` : "dossiers non confirmés"}
        />
        <Indicateur
          libelle="Taux de transformation"
          valeur={`${Math.round(d.transformation.taux * 100)} %`}
          detail={`${d.transformation.gagnes} gagnés · ${d.transformation.perdus} perdus ou annulés`}
        />
      </section>

      <div className="grid grid-cols-[minmax(0,1fr)] gap-6 xl:grid-cols-3">
        {/* 3. Dossiers en cours avec voyants de procédure */}
        <section className="carte xl:col-span-2">
          <div className="flex items-center justify-between border-b border-bord px-4 py-3">
            <h2 className="titre-carte">Dossiers en cours</h2>
            <Link href="/dossiers" className="text-xs font-medium text-accent">Tous les dossiers →</Link>
          </div>
          {d.enCours.length === 0 ? (
            <Vide>Aucun dossier avec procédure ouverte.</Vide>
          ) : (
            <ul className="divide-y divide-bord">
              {d.enCours.map((dos) => (
                <li key={dos.id}>
                  <Link href={`/dossiers/${dos.id}`} className="grid grid-cols-[minmax(0,1fr)] gap-2 px-4 py-3 hover:bg-fond sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center">
                    <div className="min-w-0">
                      <div className="flex flex-wrap items-center gap-2">
                        <span className="chiffres text-xs text-encre-3">N° {dos.numero}</span>
                        <PastilleSociete code={dos.societe.code} couleur={dos.societe.couleur} />
                        <Badge ton={STATUTS_OPERATIONNELS[dos.statutOperationnel].ton}>
                          {dos.statutCommercial === "CONFIRME"
                            ? STATUTS_OPERATIONNELS[dos.statutOperationnel].libelle
                            : STATUTS_COMMERCIAUX[dos.statutCommercial].libelle}
                        </Badge>
                      </div>
                      <p className="mt-1 truncate text-sm font-medium">{dos.intitule}</p>
                      <p className="truncate text-xs text-encre-2">
                        {dos.client?.nom ?? "Client non renseigné"} · {dos.dateDebut ? dateLongue(dos.dateDebut) : "date à fixer"}
                        {dos.charge && ` · ${dos.charge.nom}`}
                      </p>
                      {dos.prochaine && (
                        <p className="mt-1 truncate text-xs text-encre-3">
                          Prochaine étape le {dateLongue(dos.prochaine.echeance)} : {dos.prochaine.libelle}
                        </p>
                      )}
                    </div>
                    <div className="flex items-center gap-1" aria-label="Avancement de la procédure par section">
                      {SECTIONS.map((s) => (
                        <Voyant key={s} section={s} {...dos.sections[s]} />
                      ))}
                    </div>
                  </Link>
                </li>
              ))}
            </ul>
          )}
          <LegendeVoyants />
        </section>

        <div className="space-y-6">
          {/* 4. Cette semaine */}
          <section className="carte">
            <h2 className="titre-carte border-b border-bord px-4 py-3">Sur le terrain cette semaine</h2>
            {d.semaine.length === 0 ? (
              <Vide>Aucun événement confirmé dans les 7 prochains jours.</Vide>
            ) : (
              <ul className="divide-y divide-bord">
                {d.semaine.map((dos) => (
                  <li key={dos.id}>
                    <Link href={`/dossiers/${dos.id}`} className="flex items-start gap-3 px-4 py-3 hover:bg-fond">
                      <CalendarClock className="mt-0.5 h-4 w-4 shrink-0 text-accent" aria-hidden />
                      <div className="min-w-0">
                        <p className="truncate text-sm font-medium">{dos.intitule}</p>
                        <p className="text-xs text-encre-2">
                          {dateLongue(dos.dateDebut)}
                          {dos.dateFin && dos.dateFin.getTime() !== dos.dateDebut?.getTime() && ` → ${dateLongue(dos.dateFin)}`} · {dos.societe.code}
                          {dos.charge && ` · ${dos.charge.nom}`}
                        </p>
                      </div>
                    </Link>
                  </li>
                ))}
              </ul>
            )}
          </section>

          {/* 5. Retards par personne */}
          <section className="carte">
            <h2 className="titre-carte border-b border-bord px-4 py-3">Étapes en retard par responsable</h2>
            {d.retardsParResponsable.length === 0 ? (
              <p className="flex items-center justify-center gap-2 px-4 py-8 text-sm text-encre-2">
                <CheckCircle2 className="h-4 w-4 text-succes" aria-hidden /> Aucun retard
              </p>
            ) : (
              <ul className="space-y-2 p-4">
                {d.retardsParResponsable.map((r) => (
                  <li key={r.nom} className="grid grid-cols-[7rem_1fr_2rem] items-center gap-2 text-sm" title={`${r.nom} : ${r.nb} étape(s) en retard`}>
                    <span className="flex items-center gap-1.5 truncate">
                      <span className="h-2 w-2 shrink-0 rounded-full" style={{ background: r.couleur ?? "#a8a7a2" }} aria-hidden />
                      {r.nom}
                    </span>
                    <span className="h-3 rounded-r bg-accent-clair">
                      <span className="block h-full rounded-r bg-accent" style={{ width: `${(r.nb / maxRetard) * 100}%` }} />
                    </span>
                    <span className="chiffres text-right text-encre-2">{r.nb}</span>
                  </li>
                ))}
              </ul>
            )}
          </section>

          {/* 6. Pipeline et facturation */}
          <section className="carte">
            <h2 className="titre-carte border-b border-bord px-4 py-3">Pipeline commercial</h2>
            <ul className="space-y-2 p-4">
              {d.pipeline.map((p) => (
                <li key={p.statut}>
                  <Link
                    href={`/dossiers?commercial=${p.statut}${suffixe}`}
                    className="grid grid-cols-[7rem_1fr_2rem] items-center gap-2 text-sm hover:text-accent"
                    title={`${STATUTS_COMMERCIAUX[p.statut].libelle} : ${p.nb} dossier(s)${p.montant ? `, ${montantCompact(p.montant)}` : ""}`}
                  >
                    <span className="truncate">{STATUTS_COMMERCIAUX[p.statut].libelle}</span>
                    <span className="h-3 rounded-r bg-accent-clair">
                      <span className="block h-full rounded-r bg-accent" style={{ width: `${(p.nb / maxPipeline) * 100}%` }} />
                    </span>
                    <span className="chiffres text-right text-encre-2">{p.nb}</span>
                  </Link>
                </li>
              ))}
            </ul>
            <p className="border-t border-bord px-4 py-3 text-xs text-encre-2">
              À facturer : <strong className="text-encre">{aFacturer.nb}</strong> dossier(s)
              {aFacturer.montant > 0 && ` · ${montantCompact(aFacturer.montant)}`}
            </p>
          </section>
        </div>
      </div>
    </div>
  );
}

const NIVEAUX = {
  critique: { couleur: "text-danger", fond: "border-l-danger" },
  serieux: { couleur: "text-serieux", fond: "border-l-serieux" },
  attention: { couleur: "text-amber-600", fond: "border-l-attention" },
};

function Alerte({
  href,
  nb,
  libelle,
  detail,
  icone: Icone,
  niveau,
}: {
  href: string;
  nb: number;
  libelle: string;
  detail?: string;
  icone: typeof Clock;
  niveau: keyof typeof NIVEAUX;
}) {
  const ok = nb === 0;
  return (
    <Link href={href} className={clsx("carte border-l-4 p-4 hover:shadow-sm", ok ? "border-l-succes" : NIVEAUX[niveau].fond)}>
      <div className="flex items-start justify-between gap-2">
        <p className="text-3xl font-semibold">{nb}</p>
        {ok ? <CheckCircle2 className="h-5 w-5 text-succes" aria-hidden /> : <Icone className={clsx("h-5 w-5", NIVEAUX[niveau].couleur)} aria-hidden />}
      </div>
      <p className="mt-1 text-sm text-encre-2">{libelle}</p>
      {detail && <p className="text-xs font-medium text-encre">{detail}</p>}
    </Link>
  );
}

function Indicateur({ libelle, valeur, detail }: { libelle: string; valeur: string; detail: string }) {
  return (
    <div className="carte p-4">
      <p className="text-sm text-encre-2">{libelle}</p>
      <p className="mt-1 text-2xl font-semibold">{valeur}</p>
      <p className="mt-0.5 text-xs text-encre-3">{detail}</p>
    </div>
  );
}

const STYLES_VOYANT: Record<EtatSection, { classe: string; libelle: string }> = {
  termine: { classe: "bg-succes text-white", libelle: "terminée" },
  retard: { classe: "bg-danger text-white", libelle: "en retard" },
  en_cours: { classe: "bg-accent-clair text-blue-900", libelle: "en cours" },
  a_venir: { classe: "bg-stone-100 text-encre-3", libelle: "à venir" },
};

function Voyant({ section, etat, faites, total, retard }: { section: string; etat: EtatSection; faites: number; total: number; retard: number }) {
  const s = STYLES_VOYANT[etat];
  const texte = `${section} · ${NOMS_SECTIONS[section]} : ${s.libelle} (${faites}/${total}${retard ? `, ${retard} en retard` : ""})`;
  return (
    <span title={texte} aria-label={texte} className={clsx("flex h-7 w-7 items-center justify-center rounded-md text-xs font-semibold", s.classe)}>
      {etat === "retard" ? "!" : section}
    </span>
  );
}

function LegendeVoyants() {
  return (
    <div className="flex flex-wrap gap-x-4 gap-y-1 border-t border-bord px-4 py-3 text-xs text-encre-2">
      <span className="font-medium">Sections A → G de la procédure :</span>
      {(Object.keys(STYLES_VOYANT) as EtatSection[]).map((e) => (
        <span key={e} className="inline-flex items-center gap-1.5">
          <span className={clsx("h-3 w-3 rounded-sm", STYLES_VOYANT[e].classe)} aria-hidden />
          {STYLES_VOYANT[e].libelle}
        </span>
      ))}
    </div>
  );
}
