/* =====================================================================
 * Tableau de bord.
 * ===================================================================== */

function BarList({ items, color = 'bg-red-500' }) {
  const max = Math.max(1, ...items.map((i) => i.value));
  if (!items.length) return <p className="text-sm text-slate-400">Pas encore de données.</p>;
  return (
    <ul className="space-y-2.5">
      {items.map((i) => (
        <li key={i.label}>
          <div className="mb-1 flex justify-between text-sm">
            <span className="text-slate-700">{i.label}</span>
            <span className="font-semibold text-slate-900">{i.value}</span>
          </div>
          <div className="h-2 overflow-hidden rounded-full bg-slate-100">
            <div className={cx('h-full rounded-full', i.color || color)} style={{ width: `${(i.value / max) * 100}%` }} />
          </div>
        </li>
      ))}
    </ul>
  );
}

function Dashboard({ navigate }) {
  const { currentUser, can, bilans, jsps, jspYear } = useApp();

  const stats = useMemo(() => {
    const now = new Date();
    const thisMonth = bilans.filter((b) => {
      const d = new Date(b.circ.dateHeure || b.createdAt);
      return d.getMonth() === now.getMonth() && d.getFullYear() === now.getFullYear();
    });
    const motifs = {};
    bilans.forEach((b) => {
      const m = b.circ.motif || 'Non renseigné';
      motifs[m] = (motifs[m] || 0) + 1;
    });
    return {
      total: bilans.length,
      month: thisMonth.length,
      drafts: bilans.filter((b) => b.status === 'brouillon'),
      critiques: bilans.filter((b) => bilanSeverity(b) === 'danger').length,
      motifs: Object.entries(motifs)
        .map(([label, value]) => ({ label, value }))
        .sort((a, b) => b.value - a.value)
        .slice(0, 6),
      recent: [...bilans].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, 5),
    };
  }, [bilans]);

  const jspStats = useMemo(() => {
    const year = jsps.filter((j) => j.annee === jspYear);
    return {
      total: year.length,
      commandes: jspCommandes(year).length,
      niveaux: JSP_NIVEAUX.map((n) => ({ label: n.label, value: year.filter((j) => j.niveau === n.value).length, color: n.dot })),
    };
  }, [jsps, jspYear]);

  const hour = new Date().getHours();
  const greeting = hour < 18 ? 'Bonjour' : 'Bonsoir';

  return (
    <div className="space-y-6">
      <div className="overflow-hidden rounded-2xl bg-gradient-to-br from-red-700 via-red-600 to-orange-500 p-5 text-white shadow-lg sm:p-6">
        <p className="text-sm text-red-100">{new Date().toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}</p>
        <h1 className="mt-1 text-2xl font-bold sm:text-3xl">
          {greeting}, {currentUser.grade ? `${currentUser.grade} ` : ''}
          {currentUser.nom}
        </h1>
        <p className="mt-1 text-red-100">{roleOf(currentUser.role).label}</p>
        <div className="mt-5 grid gap-2 sm:flex sm:flex-wrap">
          {can.sap && (
            <Button size="lg" className="!bg-white !text-red-700 hover:!bg-red-50" icon={FilePlus2} onClick={() => navigate('nouveau')}>
              Nouveau bilan
            </Button>
          )}
          {can.sap && (
            <Button size="lg" variant="ghost" className="!bg-white/10 !text-white hover:!bg-white/20" icon={HistoryIcon} onClick={() => navigate('historique')}>
              Historique
            </Button>
          )}
          {can.jsp && (
            <Button size="lg" variant="ghost" className="!bg-white/10 !text-white hover:!bg-white/20" icon={Shirt} onClick={() => navigate('jsp')}>
              Habillement JSP
            </Button>
          )}
        </div>
      </div>

      {!can.sap && !can.jsp && (
        <EmptyState icon={LockIcon} title="Aucun module activé">
          Votre compte n'a accès à aucun module. Contactez un administrateur.
        </EmptyState>
      )}

      {can.sap && (
        <Fragment>
          <div className="grid grid-cols-2 gap-3 sm:gap-4 xl:grid-cols-4">
            <StatCard label="Bilans enregistrés" value={stats.total} icon={FileText} tone="slate" onClick={() => navigate('historique')} />
            <StatCard label="Bilans ce mois-ci" value={stats.month} icon={CalendarDays} tone="blue" />
            <StatCard label="Brouillons en cours" value={stats.drafts.length} icon={Pencil} tone="amber" onClick={() => navigate('historique')} />
            <StatCard label="Bilans avec détresse" value={stats.critiques} icon={Siren} tone="red" />
          </div>

          <div className="grid gap-5 lg:grid-cols-[1fr_360px]">
            <Card
              title="Activité récente"
              icon={HistoryIcon}
              actions={
                <Button size="sm" variant="ghost" onClick={() => navigate('historique')}>
                  Tout voir <ArrowRight className="h-3.5 w-3.5" />
                </Button>
              }
              bodyClassName="p-0"
            >
              {stats.recent.length === 0 ? (
                <div className="p-4">
                  <EmptyState icon={FileText} title="Aucun bilan" />
                </div>
              ) : (
                <ul className="divide-y divide-slate-100">
                  {stats.recent.map((b) => {
                    const st = BILAN_STATUS[b.status] || BILAN_STATUS.brouillon;
                    return (
                      <li key={b.id}>
                        <button type="button" onClick={() => navigate('bilan', { id: b.id })} className="flex w-full items-center gap-3 px-4 py-3 text-left hover:bg-slate-50">
                          <span className={cx('h-2.5 w-2.5 shrink-0 rounded-full', SEVERITY_DOT[bilanSeverity(b)])} />
                          <div className="min-w-0 flex-1">
                            <p className="truncate font-medium text-slate-800">
                              <span className="font-mono">{b.numero}</span> · {b.circ.motif || 'Motif non renseigné'}
                            </p>
                            <p className="truncate text-xs text-slate-500">
                              {bilanVictimeLabel(b)} · {fmtDateTime(b.circ.dateHeure)}
                            </p>
                          </div>
                          <Badge tone={st.tone}>{st.label}</Badge>
                          <ChevronRight className="h-4 w-4 text-slate-400" />
                        </button>
                      </li>
                    );
                  })}
                </ul>
              )}
            </Card>

            <Card title="Motifs de départ" icon={Ambulance}>
              <BarList items={stats.motifs} />
            </Card>
          </div>
        </Fragment>
      )}

      {can.jsp && (
        <div className="grid gap-5 lg:grid-cols-[1fr_360px]">
          <Card
            title={`Section JSP — ${jspYear}`}
            icon={Shirt}
            actions={
              <Button size="sm" variant="ghost" onClick={() => navigate('jsp')}>
                Ouvrir <ArrowRight className="h-3.5 w-3.5" />
              </Button>
            }
          >
            <BarList items={jspStats.niveaux} />
          </Card>
          <div className="grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-1">
            <StatCard label="JSP dans l'effectif" value={jspStats.total} icon={Users} tone="emerald" onClick={() => navigate('jsp')} />
            <StatCard label="Articles à commander" value={jspStats.commandes} icon={ShoppingCart} tone="amber" onClick={() => navigate('jsp')} />
          </div>
        </div>
      )}
    </div>
  );
}
