/* Maschera 5 — Dettaglio consumi DM in attività chirurgica ed interventistica */
const { useState: r5us, useMemo: r5um } = React;

function Mask5DM({ filters, onEditFilters }) {
  const D = window.DATA;
  const allRows = r5um(() => D.applyFilters(filters), [filters]);
  // Solo interventi eseguiti
  const rows = r5um(() => allRows.filter(r => r.interventoEseguito), [allRows]);

  // Filtri locali aggiuntivi (extra)
  const [filtroProcedura, setFiltroProcedura] = r5us(""); // procedura.codice
  const [filtroChirurgo, setFiltroChirurgo] = r5us("");
  const [filtroCategoria, setFiltroCategoria] = r5us(""); // categoria DM

  // Auto-seleziona la procedura più frequente all'avvio
  React.useEffect(() => {
    if (!filtroProcedura && rows.length) {
      const m = {};
      rows.forEach(r => { m[r.proceduraCod] = (m[r.proceduraCod] || 0) + 1; });
      const top = Object.entries(m).sort((a, b) => b[1] - a[1])[0];
      if (top) setFiltroProcedura(top[0]);
    }
  }, [rows.length]);

  // Filtro applicato
  const filtered = r5um(() => {
    return rows.filter(r => {
      if (filtroProcedura && r.proceduraCod !== filtroProcedura) return false;
      if (filtroChirurgo && r.chirurgoId !== filtroChirurgo) return false;
      return true;
    });
  }, [rows, filtroProcedura, filtroChirurgo]);

  // Ricovero selezionato per il dettaglio DM
  const [selectedRicovero, setSelectedRicovero] = r5us(null);
  React.useEffect(() => {
    if (filtered.length && (!selectedRicovero || !filtered.find(r => r.id === selectedRicovero.id))) {
      setSelectedRicovero(filtered[0]);
    }
  }, [filtered]);

  // KPI complessivi
  const kpis = r5um(() => {
    const n = filtered.length;
    if (!n) return { n: 0 };
    const costoTotale = filtered.reduce((s, r) => s + r.costoDM, 0);
    const costoMedio = costoTotale / n;
    const costoMediano = [...filtered.map(r => r.costoDM)].sort((a, b) => a - b)[Math.floor(n / 2)];
    const dmMedi = filtered.reduce((s, r) => s + r.dmUsati.length, 0) / n;
    const durataMedia = filtered.reduce((s, r) => s + r.durataMin, 0) / n;
    return { n, costoTotale, costoMedio, costoMediano, dmMedi, durataMedia };
  }, [filtered]);

  // Procedure disponibili nel perimetro
  const procedureDisp = r5um(() => {
    const m = {};
    rows.forEach(r => { m[r.proceduraCod] = (m[r.proceduraCod] || 0) + 1; });
    return Object.entries(m)
      .map(([cod, count]) => {
        const p = D.procedure.find(x => x.codice === cod);
        return { codice: cod, nome: p ? p.nome : cod, count };
      })
      .sort((a, b) => b.count - a.count);
  }, [rows]);

  // Chirurghi disponibili per la procedura selezionata
  const chirurghiDisp = r5um(() => {
    const filt = filtroProcedura ? rows.filter(r => r.proceduraCod === filtroProcedura) : rows;
    const m = {};
    filt.forEach(r => { if (r.chirurgoId) m[r.chirurgoId] = (m[r.chirurgoId] || 0) + 1; });
    return Object.entries(m).map(([id, count]) => ({
      id, nome: D.chirurgoNome(id), count
    })).sort((a, b) => b.count - a.count);
  }, [rows, filtroProcedura]);

  // Confronto per chirurgo (per la procedura selezionata)
  const perChirurgo = r5um(() => {
    if (!filtroProcedura) return [];
    const proc = rows.filter(r => r.proceduraCod === filtroProcedura);
    const m = {};
    proc.forEach(r => {
      const k = r.chirurgoId || "—";
      if (!m[k]) m[k] = { id: k, nome: r.chirurgoNome || "—", count: 0, totale: 0, durata: 0 };
      m[k].count++;
      m[k].totale += r.costoDM;
      m[k].durata += r.durataMin;
    });
    return Object.values(m)
      .filter(x => x.count >= 2)
      .map(x => ({ ...x, medio: x.totale / x.count, durataMedia: x.durata / x.count }))
      .sort((a, b) => b.medio - a.medio);
  }, [rows, filtroProcedura]);

  // Confronto con altre procedure simili (dipartimento o DRG simile)
  const confrontoProcedure = r5um(() => {
    if (!selectedRicovero) return [];
    // Stesso dipartimento
    const m = {};
    rows.filter(r => r.dipartimento === selectedRicovero.dipartimento).forEach(r => {
      const k = r.proceduraCod;
      if (!m[k]) m[k] = { codice: k, nome: r.procedura, count: 0, totale: 0 };
      m[k].count++;
      m[k].totale += r.costoDM;
    });
    return Object.values(m)
      .filter(x => x.count >= 3)
      .map(x => ({ ...x, medio: x.totale / x.count }))
      .sort((a, b) => b.medio - a.medio)
      .slice(0, 8);
  }, [rows, selectedRicovero]);

  // Distribuzione costo DM (boxplot semplificato a barre)
  const distribuzioneCosti = r5um(() => {
    if (!filtered.length) return null;
    const vals = filtered.map(r => r.costoDM).sort((a, b) => a - b);
    const n = vals.length;
    return {
      min: vals[0],
      p10: vals[Math.floor(n * 0.1)],
      p25: vals[Math.floor(n * 0.25)],
      median: vals[Math.floor(n * 0.5)],
      p75: vals[Math.floor(n * 0.75)],
      p90: vals[Math.floor(n * 0.9)],
      max: vals[n - 1]
    };
  }, [filtered]);

  // Top DM utilizzati nel perimetro
  const topDM = r5um(() => {
    const m = {};
    filtered.forEach(r => {
      r.dmUsati.forEach(dm => {
        if (!m[dm.codice]) m[dm.codice] = { codice: dm.codice, nome: dm.nome, categoria: dm.categoria, qty: 0, costo: 0 };
        m[dm.codice].qty += dm.qty;
        m[dm.codice].costo += dm.costoTotale;
      });
    });
    return Object.values(m).sort((a, b) => b.costo - a.costo).slice(0, 8);
  }, [filtered]);

  return (
    <div>
      <div className="content__header">
        <div>
          <h1 className="page-title">Consumi dispositivi medici in attività chirurgica</h1>
          <div className="page-sub">
            Dettaglio DM utilizzati per intervento, costi e confronti per <strong style={{ color: "var(--c-text-2)" }}>procedura</strong> e <strong style={{ color: "var(--c-text-2)" }}>primo chirurgo</strong>.
          </div>
        </div>
        <div className="row">
          <button className="btn"><Icon name="download" size={12} /> Esporta dettaglio DM</button>
        </div>
      </div>

      <FilterBar filters={filters} onEdit={onEditFilters} />

      {/* Local filters bar */}
      <Card title="Filtri di analisi" sub="In aggiunta ai filtri principali del perimetro">
        <div className="grid grid-3" style={{ gap: 12 }}>
          <div className="field">
            <label className="field__label">Procedura chirurgica</label>
            <select className="select" value={filtroProcedura} onChange={e => setFiltroProcedura(e.target.value)}>
              <option value="">Tutte le procedure</option>
              {procedureDisp.map(p => (
                <option key={p.codice} value={p.codice}>{p.nome} ({p.count})</option>
              ))}
            </select>
          </div>
          <div className="field">
            <label className="field__label">Primo chirurgo</label>
            <select className="select" value={filtroChirurgo} onChange={e => setFiltroChirurgo(e.target.value)}>
              <option value="">Tutti i chirurghi</option>
              {chirurghiDisp.map(c => (
                <option key={c.id} value={c.id}>{c.nome} ({c.count})</option>
              ))}
            </select>
          </div>
          <div className="field">
            <label className="field__label">Categoria DM</label>
            <select className="select" value={filtroCategoria} onChange={e => setFiltroCategoria(e.target.value)}>
              <option value="">Tutte le categorie</option>
              {[...new Set(D.dispositiviMedici.map(d => d.categoria))].map(c => (
                <option key={c} value={c}>{c}</option>
              ))}
            </select>
          </div>
        </div>
      </Card>

      {/* KPI strip */}
      <div className="kpis" style={{ marginTop: 12, marginBottom: 12, gridTemplateColumns: "repeat(5, 1fr)" }}>
        <KpiCard label="Interventi" value={D.fmtNum(kpis.n || 0)} icon="drill" />
        <KpiCard label="Costo DM totale" value={D.fmtEuro(Math.round(kpis.costoTotale || 0))} icon="reports" />
        <KpiCard label="Costo DM medio" value={D.fmtEuro(Math.round(kpis.costoMedio || 0))} deltaLabel="per intervento" tone="accent" icon="reports" />
        <KpiCard label="Costo DM mediano" value={D.fmtEuro(Math.round(kpis.costoMediano || 0))} deltaLabel="50° percentile" />
        <KpiCard label="DM medi / intervento" value={(kpis.dmMedi || 0).toFixed(1)} deltaLabel="numero medio" />
      </div>

      {/* Dettaglio intervento selezionato + lista interventi */}
      <div className="grid" style={{ gridTemplateColumns: "1fr 1.4fr", gap: 12, marginBottom: 12 }}>
        {/* Lista interventi a sinistra */}
        <Card title={"Interventi selezionati (" + D.fmtNum(filtered.length) + ")"} sub="Click per visualizzare il dettaglio DM" flush>
          <div style={{ maxHeight: 480, overflow: "auto" }}>
            <table className="table" style={{ fontSize: 12 }}>
              <thead>
                <tr>
                  <th>Ricovero</th>
                  <th>Data</th>
                  <th>Chirurgo</th>
                  <th className="num">Durata</th>
                  <th className="num">Costo DM</th>
                </tr>
              </thead>
              <tbody>
                {filtered.slice(0, 50).map(r => (
                  <tr
                    key={r.id}
                    className="is-clickable"
                    onClick={() => setSelectedRicovero(r)}
                    style={selectedRicovero && selectedRicovero.id === r.id ? { background: "var(--c-primary-50)" } : {}}
                  >
                    <td><span className="mono" style={{ color: "var(--c-primary)", fontWeight: 600 }}>{r.id}</span></td>
                    <td className="tnum">{D.fmtDate(r.dataRicovero)}</td>
                    <td style={{ fontSize: 11.5 }}>{r.chirurgoNome ? r.chirurgoNome.replace(/^Dott\.?(ssa)?\s/, "Dr.") : "—"}</td>
                    <td className="num tnum">{r.durataMin}'</td>
                    <td className="num tnum"><strong>{D.fmtEuro(Math.round(r.costoDM))}</strong></td>
                  </tr>
                ))}
              </tbody>
            </table>
            {filtered.length > 50 && <div className="empty">Visualizzati i primi 50 di {filtered.length}</div>}
          </div>
        </Card>

        {/* Dettaglio a destra */}
        {selectedRicovero ? <RicoveroDMDetail r={selectedRicovero} /> : <Card title="Dettaglio DM"><div className="empty">Seleziona un intervento dalla lista</div></Card>}
      </div>

      {/* Confronto per chirurgo */}
      <div className="grid grid-2" style={{ marginBottom: 12 }}>
        <Card title="Confronto costo DM per chirurgo" sub={
          filtroProcedura
            ? "Procedura: " + (D.procedure.find(p => p.codice === filtroProcedura) || {}).nome
            : "Seleziona una procedura per il confronto puntuale"
        }>
          {perChirurgo.length > 0 ? (
            <ChirurgoComparison data={perChirurgo} mediaPerimetro={kpis.costoMedio || 0} />
          ) : (
            <div className="empty">Servono almeno 2 interventi per chirurgo. Seleziona una procedura più frequente.</div>
          )}
        </Card>

        <Card title="Confronto con altri interventi" sub={selectedRicovero ? "Stesso dipartimento — " + D.dipNome(selectedRicovero.dipartimento) : "—"}>
          {confrontoProcedure.length > 0 ? (
            <BarChartH
              data={confrontoProcedure.map(p => ({
                label: p.nome,
                value: Math.round(p.medio),
                count: p.count,
                isSelected: selectedRicovero && p.codice === selectedRicovero.proceduraCod
              }))}
              valueKey="value"
              labelKey="label"
              maxBars={8}
              formatValue={v => D.fmtEuro(v)}
              colorBy={(d) => d.isSelected ? "#C8102E" : "#008A3D"}
            />
          ) : <div className="empty">Dati insufficienti per il confronto</div>}
        </Card>
      </div>

      {/* Top DM + distribuzione */}
      <div className="grid grid-2" style={{ marginBottom: 12 }}>
        <Card title="Top DM per impatto economico" sub="Sul perimetro analizzato" flush>
          <table className="table" style={{ fontSize: 12 }}>
            <thead>
              <tr>
                <th>Codice</th>
                <th>Descrizione</th>
                <th>Categoria</th>
                <th className="num">Qty</th>
                <th className="num">Costo tot.</th>
              </tr>
            </thead>
            <tbody>
              {topDM.map(d => (
                <tr key={d.codice}>
                  <td><span className="mono" style={{ color: "var(--c-primary)", fontWeight: 600, fontSize: 11 }}>{d.codice}</span></td>
                  <td>{d.nome}</td>
                  <td><span className="pill pill--neutral">{d.categoria}</span></td>
                  <td className="num tnum">{D.fmtNum(d.qty)}</td>
                  <td className="num tnum"><strong>{D.fmtEuro(Math.round(d.costo))}</strong></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        <Card title="Distribuzione costo DM" sub="Box-plot percentili sul perimetro filtrato">
          {distribuzioneCosti && <BoxPlot d={distribuzioneCosti} color="#008A3D" />}
        </Card>
      </div>
    </div>
  );
}

/* ---------- Sub-components ---------- */

function RicoveroDMDetail({ r }) {
  const D = window.DATA;
  // Group DM by category
  const byCat = {};
  r.dmUsati.forEach(dm => {
    if (!byCat[dm.categoria]) byCat[dm.categoria] = { categoria: dm.categoria, totale: 0, items: [] };
    byCat[dm.categoria].items.push(dm);
    byCat[dm.categoria].totale += dm.costoTotale;
  });
  const categorie = Object.values(byCat).sort((a, b) => b.totale - a.totale);

  return (
    <Card title={"Dettaglio DM — Ricovero " + r.id} sub={r.procedura + " · " + r.chirurgoNome} flush>
      <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--c-border)", background: "var(--c-surface-2)" }}>
        <div className="grid grid-4" style={{ gap: 12 }}>
          <DetailMini label="Costo DM" value={D.fmtEuro(Math.round(r.costoDM))} highlight />
          <DetailMini label="DM utilizzati" value={r.dmUsati.length} />
          <DetailMini label="Durata intervento" value={r.durataMin + " min"} />
          <DetailMini label="DRG" value={r.drg + " · " + r.drgPeso.toFixed(2)} />
        </div>
      </div>
      <div style={{ maxHeight: 380, overflow: "auto" }}>
        {categorie.map(c => (
          <div key={c.categoria}>
            <div style={{ padding: "8px 16px", background: "var(--c-surface-2)", borderBottom: "1px solid var(--c-border)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <span style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--c-text-3)" }}>{c.categoria}</span>
              <span className="tnum" style={{ fontSize: 12, fontWeight: 600, color: "var(--c-text)" }}>{D.fmtEuro(Math.round(c.totale))}</span>
            </div>
            <table className="table" style={{ fontSize: 12 }}>
              <tbody>
                {c.items.map((dm, i) => (
                  <tr key={dm.codice + i}>
                    <td style={{ width: 110 }}><span className="mono" style={{ color: "var(--c-primary)", fontWeight: 600, fontSize: 11 }}>{dm.codice}</span></td>
                    <td>{dm.nome}</td>
                    <td className="num tnum" style={{ width: 50 }}>×{dm.qty}</td>
                    <td className="num tnum" style={{ width: 80 }}>{D.fmtEuro(dm.costoUnit)}</td>
                    <td className="num tnum" style={{ width: 90 }}><strong>{D.fmtEuro(Math.round(dm.costoTotale))}</strong></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ))}
      </div>
    </Card>
  );
}

function DetailMini({ label, value, highlight }) {
  return (
    <div>
      <div style={{ fontSize: 10.5, color: "var(--c-text-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em" }}>{label}</div>
      <div style={{ fontSize: 15, fontWeight: 700, color: highlight ? "var(--c-primary)" : "var(--c-text)", marginTop: 2, fontVariantNumeric: "tabular-nums", letterSpacing: "-0.01em" }}>{value}</div>
    </div>
  );
}

function ChirurgoComparison({ data, mediaPerimetro }) {
  const D = window.DATA;
  const max = Math.max(...data.map(d => d.medio));
  return (
    <div className="col" style={{ gap: 10 }}>
      <div style={{ fontSize: 11.5, color: "var(--c-text-3)" }}>Costo DM medio per intervento, con confronto vs media perimetro <strong>({D.fmtEuro(Math.round(mediaPerimetro))})</strong></div>
      {data.map(c => {
        const delta = mediaPerimetro ? ((c.medio - mediaPerimetro) / mediaPerimetro) * 100 : 0;
        return (
          <div key={c.id} style={{ display: "grid", gridTemplateColumns: "190px 1fr 90px 70px", alignItems: "center", gap: 10 }}>
            <div>
              <div style={{ fontSize: 12, color: "var(--c-text)", fontWeight: 500 }}>{c.nome}</div>
              <div className="muted text-sm">{c.count} interventi · {c.durataMedia.toFixed(0)}' media</div>
            </div>
            <div style={{ height: 14, background: "#F1F5F9", borderRadius: 2, overflow: "hidden", position: "relative" }}>
              <div style={{ height: "100%", width: (c.medio / max) * 100 + "%", background: delta > 10 ? "#C8102E" : delta < -10 ? "#0E7C8C" : "#008A3D" }} />
              {mediaPerimetro && (
                <div style={{ position: "absolute", top: -2, bottom: -2, left: (mediaPerimetro / max) * 100 + "%", width: 1.5, background: "#0F172A", opacity: 0.55 }} />
              )}
            </div>
            <span className="tnum" style={{ fontSize: 12, color: "var(--c-text)", fontWeight: 700, textAlign: "right" }}>{D.fmtEuro(Math.round(c.medio))}</span>
            <span className="tnum text-right" style={{ fontSize: 11 }}>
              <Pill tone={delta > 10 ? "warn" : delta < -10 ? "accent" : "neutral"}>{delta > 0 ? "+" : ""}{delta.toFixed(0)}%</Pill>
            </span>
          </div>
        );
      })}
    </div>
  );
}

function BoxPlot({ d, color }) {
  const D = window.DATA;
  const w = 360, h = 140;
  const pad = 30;
  const innerW = w - pad * 2;
  const range = d.max - d.min || 1;
  const x = (v) => pad + ((v - d.min) / range) * innerW;
  const yMid = h / 2;
  return (
    <div>
      <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="xMidYMid meet" style={{ display: "block" }}>
        {/* whisker */}
        <line x1={x(d.p10)} y1={yMid} x2={x(d.p90)} y2={yMid} stroke="#94A3B8" strokeWidth="1.5" />
        <line x1={x(d.p10)} y1={yMid - 16} x2={x(d.p10)} y2={yMid + 16} stroke="#94A3B8" strokeWidth="1.5" />
        <line x1={x(d.p90)} y1={yMid - 16} x2={x(d.p90)} y2={yMid + 16} stroke="#94A3B8" strokeWidth="1.5" />
        {/* box */}
        <rect x={x(d.p25)} y={yMid - 22} width={x(d.p75) - x(d.p25)} height={44} fill={color} fillOpacity="0.18" stroke={color} strokeWidth="1.5" rx="2" />
        {/* median */}
        <line x1={x(d.median)} y1={yMid - 22} x2={x(d.median)} y2={yMid + 22} stroke={color} strokeWidth="2.5" />
        {/* axis */}
        <line x1={pad} y1={h - 18} x2={w - pad} y2={h - 18} stroke="#CBD5E1" strokeWidth="1" />
        <text x={x(d.min)} y={h - 4} fontSize="10" fill="#64748B" textAnchor="middle">{D.fmtEuro(Math.round(d.min))}</text>
        <text x={x(d.median)} y={h - 4} fontSize="10" fill="#0F172A" textAnchor="middle" fontWeight="600">{D.fmtEuro(Math.round(d.median))}</text>
        <text x={x(d.max)} y={h - 4} fontSize="10" fill="#64748B" textAnchor="middle">{D.fmtEuro(Math.round(d.max))}</text>
      </svg>
      <div className="grid grid-3" style={{ gap: 8, marginTop: 8, fontSize: 11.5 }}>
        <PercRow label="10° perc." value={D.fmtEuro(Math.round(d.p10))} />
        <PercRow label="25° perc." value={D.fmtEuro(Math.round(d.p25))} />
        <PercRow label="Mediana" value={D.fmtEuro(Math.round(d.median))} bold />
        <PercRow label="75° perc." value={D.fmtEuro(Math.round(d.p75))} />
        <PercRow label="90° perc." value={D.fmtEuro(Math.round(d.p90))} />
        <PercRow label="Max" value={D.fmtEuro(Math.round(d.max))} />
      </div>
    </div>
  );
}
function PercRow({ label, value, bold }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 8px", background: "var(--c-surface-2)", borderRadius: 4 }}>
      <span className="muted">{label}</span>
      <span className="tnum" style={{ color: "var(--c-text)", fontWeight: bold ? 700 : 500 }}>{value}</span>
    </div>
  );
}

Object.assign(window, { Mask5DM });
