/* =====================================================================
 * Saisie guidée d'un bilan SAP (6 étapes) avec sauvegarde automatique.
 * ===================================================================== */

const BILAN_STEPS = [
  { id: 'circ', label: 'Circonstanciel', short: 'Circ.', icon: MapPin, component: StepCirconstanciel },
  { id: 'vital', label: 'Bilan vital X-ABCDE', short: 'Vital', icon: HeartPulse, component: StepVital },
  { id: 'lesions', label: 'Lésionnel & SAMPLE', short: 'Lésions', icon: Bandage, component: StepLesionnel },
  { id: 'gestes', label: 'Gestes & surveillance', short: 'Gestes', icon: Activity, component: StepGestes },
  { id: 'transmission', label: 'Transmission & transport', short: 'Transm.', icon: Phone, component: StepTransmission },
  { id: 'synthese', label: 'Synthèse & impression', short: 'Synthèse', icon: ClipboardCheck, component: null },
];

/** Panneau « moniteur » : constantes principales + alertes en temps réel. */
function VitalMonitor({ b }) {
  const v = b.vital;
  const alerts = bilanAlerts(b);
  const gcs = glasgowScore(v.d);
  const items = [
    { label: 'FR', value: v.b.fr, unit: '/min', tone: vitalTone('fr', v.b.fr) },
    { label: 'SpO2', value: v.b.spo2, unit: '%', tone: vitalTone('spo2', v.b.spo2) },
    { label: 'FC', value: v.c.fc, unit: 'bpm', tone: vitalTone('fc', v.c.fc) },
    { label: 'TA', value: v.c.tas ? `${v.c.tas}/${v.c.tad || '?'}` : '', unit: '', tone: vitalTone('tas', v.c.tas) },
    { label: 'GCS', value: gcs, unit: '/15', tone: gcs === null ? null : gcs <= 8 ? 'danger' : gcs < 15 ? 'warning' : 'ok' },
    { label: 'Temp.', value: v.e.temp, unit: '°C', tone: vitalTone('temp', v.e.temp) },
  ];
  const toneCls = { danger: 'text-red-400', warning: 'text-amber-300', ok: 'text-emerald-300' };

  return (
    <div className="space-y-3">
      <div className="rounded-xl bg-slate-900 p-4 text-white shadow-lg">
        <p className="mb-3 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-slate-400">
          <Activity className="h-4 w-4 text-emerald-400" /> Paramètres
        </p>
        <div className="grid grid-cols-3 gap-3">
          {items.map((it) => (
            <div key={it.label}>
              <p className="text-[11px] uppercase text-slate-400">{it.label}</p>
              <p className={cx('font-mono text-xl font-bold', toneCls[it.tone] || 'text-slate-500')}>
                {it.value === null || it.value === '' || it.value === undefined ? '--' : it.value}
                {it.value !== '' && it.value !== null && it.value !== undefined && <span className="ml-0.5 text-[10px] font-normal text-slate-400">{it.unit}</span>}
              </p>
            </div>
          ))}
        </div>
      </div>

      <div className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
        <p className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-slate-500">
          <AlertTriangle className="h-4 w-4" /> Alertes ({alerts.length})
        </p>
        {alerts.length === 0 ? (
          <p className="text-sm text-slate-400">Aucune anomalie détectée.</p>
        ) : (
          <ul className="space-y-1.5">
            {alerts.map((a, i) => (
              <li
                key={i}
                className={cx('rounded-md px-2.5 py-1.5 text-sm font-medium', a.level === 'danger' ? 'bg-red-50 text-red-700' : 'bg-amber-50 text-amber-800')}
              >
                {a.text}
              </li>
            ))}
          </ul>
        )}
        <p className="mt-3 text-[11px] leading-tight text-slate-400">Seuils indicatifs adulte — ne remplace pas le jugement clinique ni l'avis du médecin régulateur.</p>
      </div>
    </div>
  );
}

/** Bandeau d'alertes pour les écrans sans panneau latéral (tablette). */
function CompactAlerts({ b }) {
  const alerts = bilanAlerts(b);
  if (!alerts.length) return null;
  const danger = alerts.some((a) => a.level === 'danger');
  return (
    <div className={cx('flex flex-wrap items-center gap-2 rounded-xl border px-3 py-2 xl:hidden', danger ? 'border-red-200 bg-red-50' : 'border-amber-200 bg-amber-50')}>
      <AlertTriangle className={cx('h-4 w-4', danger ? 'text-red-600' : 'text-amber-600')} />
      {alerts.map((a, i) => (
        <Badge key={i} tone={a.level === 'danger' ? 'red' : 'amber'}>
          {a.text}
        </Badge>
      ))}
    </div>
  );
}

function BilanWizard({ bilanId, navigate }) {
  const { bilans, draftBilan, updateBilan, settings, print, notify } = useApp();
  const [step, setStep] = useState(0);
  const bilan = bilans.find((x) => x.id === bilanId) || (draftBilan && draftBilan.id === bilanId ? draftBilan : null);
  const unsaved = Boolean(bilan && bilan === draftBilan);

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [step]);

  if (!bilan) {
    return (
      <EmptyState icon={FileText} title="Bilan introuvable" action={<Button onClick={() => navigate('historique')}>Retour à l'historique</Button>}>
        Ce bilan a peut-être été supprimé.
      </EmptyState>
    );
  }

  const set = (path, value) => updateBilan(bilanId, (cur) => setIn(cur, path, value));
  const bind = (path) => ({ value: getIn(bilan, path), onChange: (value) => set(path, value) });

  const current = BILAN_STEPS[step];
  const StepComponent = current.component;
  const isLast = step === BILAN_STEPS.length - 1;
  const cloture = bilan.status === 'termine';

  const toggleCloture = () => {
    updateBilan(bilanId, (cur) => ({ ...cur, status: cloture ? 'brouillon' : 'termine' }));
    notify(cloture ? 'Bilan rouvert en brouillon' : 'Bilan clôturé et archivé');
  };

  const exportJson = () => {
    downloadFile(`${bilan.numero}.json`, JSON.stringify(bilan, null, 2), 'application/json');
  };

  return (
    <div>
      {/* En-tête */}
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-3">
          <IconButton icon={ChevronLeft} title="Retour" onClick={() => navigate('historique')} />
          <div>
            <div className="flex flex-wrap items-center gap-2">
              <h1 className="font-mono text-xl font-bold text-slate-900">{bilan.numero}</h1>
              {unsaved ? (
                <Badge tone="slate">Non enregistré</Badge>
              ) : (
                <Badge tone={(BILAN_STATUS[bilan.status] || BILAN_STATUS.brouillon).tone}>{(BILAN_STATUS[bilan.status] || BILAN_STATUS.brouillon).label}</Badge>
              )}
            </div>
            <p className="text-sm text-slate-500">
              {unsaved ? "Il apparaîtra dans l'historique dès que vous remplissez un champ." : `${bilanVictimeLabel(bilan)} · ${bilan.circ.motif || 'Motif non renseigné'}`}
            </p>
          </div>
        </div>
        <p className="flex items-center gap-2 text-xs text-slate-400">
          {unsaved ? (
            'Rien n’est enregistré tant que le bilan est vide.'
          ) : (
            <Fragment>
              <SyncIndicator className="!text-xs" /> · modifié le {fmtDateTime(bilan.updatedAt)}
            </Fragment>
          )}
        </p>
      </div>

      {/* Stepper */}
      <nav className="scrollbar-thin mb-5 overflow-x-auto rounded-xl border border-slate-200 bg-white p-2 shadow-sm">
        <ol className="flex min-w-max gap-1">
          {BILAN_STEPS.map((s, i) => {
            const active = i === step;
            const done = i < step;
            return (
              <li key={s.id} className="flex-1">
                <button
                  type="button"
                  onClick={() => setStep(i)}
                  className={cx(
                    'flex w-full items-center gap-2 rounded-lg px-3 py-2.5 text-left text-sm font-medium transition',
                    active ? 'bg-red-600 text-white shadow' : done ? 'text-slate-700 hover:bg-slate-100' : 'text-slate-500 hover:bg-slate-100',
                  )}
                >
                  <span
                    className={cx(
                      'flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-xs font-bold',
                      active ? 'bg-white text-red-600' : done ? 'bg-emerald-500 text-white' : 'bg-slate-200 text-slate-600',
                    )}
                  >
                    {done ? <Check className="h-4 w-4" /> : i + 1}
                  </span>
                  <span className="hidden whitespace-nowrap md:inline">{s.label}</span>
                  <span className="whitespace-nowrap md:hidden">{s.short}</span>
                </button>
              </li>
            );
          })}
        </ol>
      </nav>

      {/* Contenu */}
      {StepComponent ? (
        <div className="grid gap-5 xl:grid-cols-[1fr_300px]">
          <div className="min-w-0 space-y-4">
            <CompactAlerts b={bilan} />
            <StepComponent b={bilan} bind={bind} />
          </div>
          <aside className="hidden xl:block">
            <div className="sticky top-6">
              <VitalMonitor b={bilan} />
            </div>
          </aside>
        </div>
      ) : (
        <div className="space-y-4">
          <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
            <div>
              <p className="font-semibold text-slate-800">Fiche de bilan opérationnelle</p>
              <p className="text-sm text-slate-500">Téléchargez la fiche en PDF ou imprimez-la directement.</p>
            </div>
            <div className="flex flex-wrap gap-2">
              <Button variant="secondary" icon={Download} onClick={exportJson}>
                Export JSON
              </Button>
              <Button variant="secondary" icon={Printer} onClick={() => print(<BilanFiche bilan={bilan} settings={settings} />)}>
                Imprimer
              </Button>
              <PdfButton node={<BilanFiche bilan={bilan} settings={settings} />} filename={`${bilan.numero}.pdf`} />
              <Button variant={cloture ? 'secondary' : 'success'} icon={cloture ? RotateCcw : CheckCircle2} onClick={toggleCloture}>
                {cloture ? 'Rouvrir le bilan' : 'Clôturer le bilan'}
              </Button>
            </div>
          </div>
          <div className="overflow-hidden rounded-xl border border-slate-200 shadow-sm">
            <BilanFiche bilan={bilan} settings={settings} />
          </div>
        </div>
      )}

      {/* Navigation bas de page */}
      <div className="sticky bottom-0 z-20 -mx-4 mt-6 flex items-center justify-between gap-3 border-t border-slate-200 bg-white/95 px-4 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] backdrop-blur sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8">
        <Button variant="secondary" size="lg" icon={ChevronLeft} disabled={step === 0} onClick={() => setStep((s) => s - 1)}>
          <span className="hidden sm:inline">Précédent</span>
        </Button>
        <span className="text-sm text-slate-500">
          Étape {step + 1} / {BILAN_STEPS.length}
        </span>
        {isLast ? (
          <Button size="lg" icon={HistoryIcon} onClick={() => navigate('historique')}>
            Historique
          </Button>
        ) : (
          <Button size="lg" onClick={() => setStep((s) => s + 1)}>
            <span className="hidden sm:inline">{BILAN_STEPS[step + 1].label}</span>
            <span className="sm:hidden">Suivant</span>
            <ChevronRight className="h-4 w-4" />
          </Button>
        )}
      </div>
    </div>
  );
}
