// Mock historical reports + Historique view + Detail view

const { useState: hS, useMemo: hM } = React;

// Generate 18 mock past reports
const MOCK_REPORTS = (() => {
  const endroits = window.RAPPORT_DATA.endroits;
  const patrouilleurs = window.RAPPORT_DATA.patrouilleurs;
  const codes = ["Vert", "Vert", "Vert", "Jaune", "Jaune", "Jaune", "Jaune", "Orange", "Orange", "Rouge"];
  const types = window.RAPPORT_DATA.typesEvenement;
  const activites = window.RAPPORT_DATA.activites;
  const blessures = window.RAPPORT_DATA.blessuresSoupconnees;
  const parties = window.RAPPORT_DATA.partiesCorps;
  const causes = window.RAPPORT_DATA.facteursContributifs;
  const meteos = window.RAPPORT_DATA.conditionsMeteo;
  const collisions = window.RAPPORT_DATA.collisions;

  const noms = [
    ["Marie-Pier", "TREMBLAY"], ["Jean-François", "BÉLANGER"], ["Sophie", "GAGNON"],
    ["Alexandre", "ROY"], ["Camille", "CÔTÉ"], ["Olivier", "MARTIN"],
    ["Élodie", "BOUCHARD"], ["Maxime", "FORTIN"], ["Justine", "PELLETIER"],
    ["Samuel", "OUELLET"], ["Béatrice", "LEVASSEUR"], ["Thomas", "GIRARD"],
    ["Anne-Sophie", "ROUSSEAU"], ["Philippe", "DUBÉ"], ["Émilie", "SIMARD"],
    ["Antoine", "RIVARD"], ["Sarah", "LANDRY"], ["Vincent", "MERCIER"],
  ];

  function pick(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
  function rDate(from, to) {
    const d = new Date(from.getTime() + Math.random() * (to.getTime() - from.getTime()));
    return d;
  }

  const reports = [];
  // Sorted: most recent first
  const dates = Array.from({ length: 18 }).map(() => rDate(new Date(2026, 4, 1), new Date(2026, 6, 22))).sort((a, b) => b - a);

  for (let i = 0; i < 18; i++) {
    const d = dates[i];
    const yyyymmdd = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
    const [prenom, nom] = noms[i];
    const code = codes[Math.floor(Math.random() * codes.length)];
    const t = pick(types);
    const inj = [{ partie: pick(parties), type: pick(blessures) }];
    if (Math.random() > 0.65) inj.push({ partie: pick(parties), type: pick(blessures) });

    const p1 = pick(patrouilleurs);
    let p2 = pick(patrouilleurs); while (p2 === p1) p2 = pick(patrouilleurs);

    const has911 = code === 'Rouge' || (code === 'Orange' && Math.random() > 0.5);
    const refus = code === 'Vert' && Math.random() > 0.7;

    reports.push({
      id: `R-${i}`,
      reportNumber: `ÉTÉ 2026-${yyyymmdd}-${String(100 + i).padStart(3, '0')}`,
      saison: 'ÉTÉ 2026',
      date: d.toISOString().slice(0, 10),
      heure: `${String(8 + Math.floor(Math.random() * 10)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}`,
      _ts: d.getTime(),
      code,
      endroit: pick(endroits),
      repere: pick(window.RAPPORT_DATA.reperes),
      sommet: pick(window.RAPPORT_DATA.sommets),
      meteo: pick(meteos),
      repartiteur: pick(patrouilleurs),
      appelant: p1,
      team: [p1, p2],
      patient: {
        prenom, nom,
        age: String(15 + Math.floor(Math.random() * 60)),
        genre: pick(["F", "H"]),
        activite: pick(activites),
        niveau: pick(window.RAPPORT_DATA.niveaux),
        tel: `(${["514", "438", "450", "819"][Math.floor(Math.random() * 4)]}) ${String(Math.floor(Math.random() * 900) + 100)}-${String(Math.floor(Math.random() * 9000) + 1000)}`,
        ville: pick(["Montréal", "Sutton", "Sherbrooke", "Granby", "Cowansville", "Bromont", "Magog"]),
      },
      injuries: inj,
      evenement: { cause: pick(causes), type: t, collision: pick(collisions) },
      transport: {
        methode: code === 'Rouge' ? "Civière" : code === 'Orange' ? "Soutenu par patrouilleur" : pick(["Marche autonome", "Véhicule motorisée", "Soutenu par patrouilleur"]),
        sommet: pick(window.RAPPORT_DATA.sommets),
        heureDepart: `${String(9 + Math.floor(Math.random() * 9)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}`,
      },
      appel911: has911,
      amb911Dest: has911 ? pick(window.RAPPORT_DATA.hopitaux) : null,
      refus,
      statut: refus ? 'Refus signé' : 'Soumis',
      evaluation: {
        conscience: pick(window.RAPPORT_DATA.niveauxConscience),
        airway: pick(window.RAPPORT_DATA.qualitatif),
        breathing: pick(window.RAPPORT_DATA.qualitatif),
        hemorragie: Math.random() > 0.85 ? 'OUI' : 'NON',
      },
      sample: {
        douleurNiveau: Math.floor(Math.random() * 11),
        allergies: Math.random() > 0.7 ? pick(["Aucune", "Pénicilline", "Pollen", "Arachides, noix"]) : "Aucune",
        medicaments: Math.random() > 0.7 ? pick(["Aucun", "Anti-dépresseur", "Anti-hypertenseur"]) : "Aucun",
      },
      soinsDetail: pick([
        "ABCDE fait, nettoyage des plaies, application de pansement stérile.",
        "ABCDE fait, immobilisation du membre supérieur avec écharpe simple.",
        "ABCDE fait, immobilisation cervicale, mise en position de récupération.",
        "ABCDE fait, glace appliquée sur la zone, bande de soutien.",
      ]),
      materiel: pick([
        "1 pansement 4x4, 2 tampons antiseptiques, 1 bande beige",
        "1 collet cervical, 1 planche dorsale, 4 sangles",
        "2 compresses, 1 carton, 1 écharpe, 2 bandes de transport",
        "1 sac de glace, 1 bande élastique 10cm",
      ]),
    });
  }

  return reports;
})();

window.MOCK_REPORTS = MOCK_REPORTS;

// =====================================================
// Historique view
// =====================================================
function HistoriquePage({ onOpen, onNew }) {
  const [q, setQ] = hS('');
  const [codeFilter, setCodeFilter] = hS('');
  const [periode, setPeriode] = hS('30j'); // 7j / 30j / saison / tous

  const filtered = hM(() => {
    const now = Date.now();
    const cutoff = {
      '7j': now - 7 * 86400e3,
      '30j': now - 30 * 86400e3,
      'saison': new Date(2026, 4, 1).getTime(),
      'tous': 0,
    }[periode];

    return MOCK_REPORTS.filter(r => {
      if (codeFilter && r.code !== codeFilter) return false;
      if (r._ts < cutoff) return false;
      if (q) {
        const hay = [
          r.reportNumber, r.endroit, r.patient?.prenom, r.patient?.nom,
          r.evenement?.type, r.appelant,
        ].join(' ').toLowerCase();
        if (!hay.includes(q.toLowerCase())) return false;
      }
      return true;
    });
  }, [q, codeFilter, periode]);

  // Stats for current filter
  const stats = hM(() => {
    const byCode = { Vert: 0, Jaune: 0, Orange: 0, Rouge: 0, Noir: 0 };
    let with911 = 0;
    filtered.forEach(r => { byCode[r.code]++; if (r.appel911) with911++; });
    return { total: filtered.length, byCode, with911 };
  }, [filtered]);

  return (
    <>
      <div className="step-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 24 }}>
        <div>
          <div className="step-eyebrow">Archives</div>
          <h1 className="step-title">Historique des rapports</h1>
          <p className="step-subtitle">Consultez, recherchez et exportez les anciens rapports d'intervention.</p>
        </div>
        <button className="btn btn-primary btn-lg" onClick={onNew}>
          <Icon.Plus /> Nouveau rapport
        </button>
      </div>

      {/* Stats row */}
      <div className="stats-row">
        <StatCard label="Rapports" value={stats.total} sub={periode === 'tous' ? 'tous' : periode === 'saison' ? 'cette saison' : periode === '30j' ? '30 derniers jours' : '7 derniers jours'} />
        <StatCard label="Code Vert" value={stats.byCode.Vert} dot="#3FA66B" />
        <StatCard label="Code Jaune" value={stats.byCode.Jaune} dot="#E8B547" />
        <StatCard label="Code Orange" value={stats.byCode.Orange} dot="#E08A3C" />
        <StatCard label="Code Rouge" value={stats.byCode.Rouge} dot="#C44536" />
        <StatCard label="Appels 911" value={stats.with911} sub="ambulance" />
      </div>

      {/* Filters */}
      <Card>
        <div className="grid">
          <Field label="Rechercher" span={6}>
            <TextInput
              value={q}
              onChange={setQ}
              placeholder="N° rapport, patient, sentier, type d'événement…"
              icon={<Icon.Search />}
            />
          </Field>
          <Field label="Période" span={3}>
            <ChipGroup value={periode} onChange={(v) => setPeriode(v || '30j')} options={[
              { value: '7j', label: '7j' },
              { value: '30j', label: '30j' },
              { value: 'saison', label: 'Saison' },
              { value: 'tous', label: 'Tous' },
            ]} />
          </Field>
          <Field label="Code" span={3}>
            <ChipGroup value={codeFilter} onChange={setCodeFilter} options={[
              { value: 'Vert', label: 'Vert' },
              { value: 'Jaune', label: 'Jaune' },
              { value: 'Orange', label: 'Orange' },
              { value: 'Rouge', label: 'Rouge' },
            ]} />
          </Field>
        </div>
      </Card>

      {/* Table */}
      <div className="report-table">
        <div className="report-table-header">
          <div>N° rapport</div>
          <div>Date</div>
          <div>Code</div>
          <div>Patient</div>
          <div>Endroit</div>
          <div>Type</div>
          <div>Statut</div>
        </div>
        {filtered.length === 0 ? (
          <div className="report-empty">
            <Icon.Search style={{ width: 24, height: 24, opacity: 0.4 }} />
            <div>Aucun rapport ne correspond à ces critères.</div>
          </div>
        ) : filtered.map(r => (
          <div className="report-row" key={r.id} onClick={() => onOpen(r)}>
            <div className="mono" style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{r.reportNumber.split('-').slice(1).join('-')}</div>
            <div>
              <div style={{ fontSize: 13.5 }}>{new Date(r._ts).toLocaleDateString('fr-CA', { month: 'short', day: 'numeric' })}</div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)' }} className="mono">{r.heure}</div>
            </div>
            <div>
              <CodeBadge code={r.code} />
            </div>
            <div>
              <div style={{ fontWeight: 500, fontSize: 13.5 }}>{r.patient.prenom} {r.patient.nom}</div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{r.patient.age} ans · {r.patient.activite}</div>
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)' }}>{r.endroit}</div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)' }}>{r.evenement.type}</div>
            <div>
              <span className={`status-pill ${r.statut === 'Refus signé' ? 'warn' : ''}`}>
                {r.statut}
              </span>
              {r.appel911 && <span className="status-pill alert" style={{ marginLeft: 4 }}>911</span>}
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

function StatCard({ label, value, sub, dot }) {
  return (
    <div className="stat-card">
      <div className="stat-label">
        {dot && <span className="stat-dot" style={{ background: dot }}></span>}
        {label}
      </div>
      <div className="stat-value">{value}</div>
      {sub && <div className="stat-sub">{sub}</div>}
    </div>
  );
}

function CodeBadge({ code }) {
  const c = window.RAPPORT_DATA.codes.find(x => x.value === code);
  if (!c) return null;
  return (
    <span className="code-badge">
      <span className="code-badge-dot" style={{ background: c.color }}></span>
      {code}
    </span>
  );
}

// =====================================================
// Report detail (read-only)
// =====================================================
function ReportDetail({ report, onBack }) {
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
        <button className="btn btn-ghost" onClick={onBack}>
          <Icon.ChevronLeft /> Retour à l'historique
        </button>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
          <button className="btn"><Icon.FileText /> Imprimer / PDF</button>
          <button className="btn">Exporter</button>
        </div>
      </div>

      <div className="step-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 20, flexWrap: 'wrap' }}>
        <div>
          <div className="step-eyebrow mono">{report.reportNumber}</div>
          <h1 className="step-title">{report.patient.prenom} {report.patient.nom}</h1>
          <p className="step-subtitle">
            {new Date(report._ts).toLocaleDateString('fr-CA', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}
            {' · '}
            <span className="mono">{report.heure}</span>
            {' · '}
            {report.endroit}
          </p>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
          <CodeBadge code={report.code} />
          <span className={`status-pill ${report.statut === 'Refus signé' ? 'warn' : ''}`}>{report.statut}</span>
          {report.appel911 && <span className="status-pill alert">911 → {report.amb911Dest}</span>}
        </div>
      </div>

      <Card title="Patient" icon={<Icon.User />}>
        <div className="recap-grid">
          <div className="recap-key">Nom</div>
          <div className="recap-val">{report.patient.prenom} {report.patient.nom}</div>
          <div className="recap-key">Âge / Genre</div>
          <div className="recap-val">{report.patient.age} ans · {report.patient.genre}</div>
          <div className="recap-key">Téléphone</div>
          <div className="recap-val mono">{report.patient.tel}</div>
          <div className="recap-key">Ville</div>
          <div className="recap-val">{report.patient.ville}</div>
          <div className="recap-key">Activité / Niveau</div>
          <div className="recap-val">{report.patient.activite} — {report.patient.niveau}</div>
        </div>
      </Card>

      <Card title="Lieu & contexte" icon={<Icon.MapPin />}>
        <div className="recap-grid">
          <div className="recap-key">Endroit</div>
          <div className="recap-val">{report.endroit}</div>
          <div className="recap-key">Repère</div>
          <div className="recap-val">{report.repere} · {report.sommet}</div>
          <div className="recap-key">Météo</div>
          <div className="recap-val">{report.meteo}</div>
          <div className="recap-key">Cause</div>
          <div className="recap-val">{report.evenement.cause}</div>
          <div className="recap-key">Type</div>
          <div className="recap-val">{report.evenement.type}</div>
          <div className="recap-key">Collision</div>
          <div className="recap-val">{report.evenement.collision}</div>
        </div>
      </Card>

      <Card title="Équipe" icon={<Icon.Users />}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
          {report.team.filter(Boolean).map((p, i) => {
            const initials = (p.match(/[A-Z]/g) || []).slice(-2).join('');
            return (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--panel-2)', padding: '6px 12px 6px 6px', borderRadius: 999, border: '1px solid var(--border)' }}>
                <div className="patrouiller-pick-avatar" style={{ width: 28, height: 28, fontSize: 11 }}>{initials}</div>
                <span style={{ fontSize: 13 }}>
                  <span style={{ color: 'var(--muted)', fontSize: 11, marginRight: 6 }}>{i === 0 ? 'P1' : `P${i + 1}`}</span>
                  {p.split(' ').slice(1).join(' ')}
                </span>
              </div>
            );
          })}
        </div>
      </Card>

      <Card title="Évaluation primaire" icon={<Icon.Stethoscope />}>
        <div className="recap-grid">
          <div className="recap-key">Conscience</div>
          <div className="recap-val">{report.evaluation.conscience}</div>
          <div className="recap-key">Airway</div>
          <div className="recap-val">{report.evaluation.airway}</div>
          <div className="recap-key">Breathing</div>
          <div className="recap-val">{report.evaluation.breathing}</div>
          <div className="recap-key">Hémorragie grave</div>
          <div className="recap-val">{report.evaluation.hemorragie}</div>
        </div>
      </Card>

      <Card title="Blessures" icon={<Icon.Bandage />}>
        {report.injuries.map((b, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: i < report.injuries.length - 1 ? '1px solid var(--border)' : 'none' }}>
            <span className="injury-num">#{i + 1}</span>
            <strong>{b.partie}</strong>
            <span style={{ color: 'var(--muted)' }}>—</span>
            <span>{b.type}</span>
          </div>
        ))}
      </Card>

      <Card title="SAMPLE & douleur" icon={<Icon.Activity />}>
        <div className="recap-grid">
          <div className="recap-key">Douleur</div>
          <div className="recap-val">{report.sample.douleurNiveau}/10</div>
          <div className="recap-key">Allergies</div>
          <div className="recap-val">{report.sample.allergies}</div>
          <div className="recap-key">Médicaments</div>
          <div className="recap-val">{report.sample.medicaments}</div>
        </div>
      </Card>

      <Card title="Soins prodigués" icon={<Icon.Heart />}>
        <div style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--ink-2)' }}>{report.soinsDetail}</div>
        <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--border)' }}>
          <div className="recap-key" style={{ marginBottom: 4 }}>Matériel utilisé</div>
          <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>{report.materiel}</div>
        </div>
      </Card>

      <Card title="Transport" icon={<Icon.Truck />}>
        <div className="recap-grid">
          <div className="recap-key">Méthode</div>
          <div className="recap-val">{report.transport.methode}</div>
          <div className="recap-key">Sommet départ</div>
          <div className="recap-val">{report.transport.sommet}</div>
          <div className="recap-key">Heure départ</div>
          <div className="recap-val mono">{report.transport.heureDepart}</div>
          {report.appel911 && <>
            <div className="recap-key">Ambulance</div>
            <div className="recap-val">Oui → {report.amb911Dest}</div>
          </>}
        </div>
      </Card>
    </>
  );
}

Object.assign(window, { HistoriquePage, ReportDetail, CodeBadge, StatCard });
