/* Maschera 2 — Impostazione filtri per selezione di interesse */
const { useState: r2us, useMemo: r2um } = React;

function Mask2Filtri({ filters, onChange, onApply }) {
  const D = window.DATA;
  const [local, setLocal] = r2us(filters);

  function update(patch) {
    setLocal(l => ({ ...l, ...patch }));
  }
  function toggleArr(key, val) {
    setLocal(l => {
      const arr = l[key] || [];
      return { ...l, [key]: arr.includes(val) ? arr.filter(x => x !== val) : [...arr, val] };
    });
  }
  function reset() {
    setLocal(D.defaultFilters());
  }
  function apply() {
    onChange(local);
    onApply();
  }

  const anteprima = r2um(() => D.applyFilters(local), [local]);
  const previewKpis = r2um(() => {
    const tot = anteprima.length;
    const pazienti = new Set(anteprima.map(r => r.pazId)).size;
    const ricoveri = tot;
    const interventi = anteprima.filter(r => r.interventoEseguito).length;
    return { pazienti, ricoveri, interventi };
  }, [anteprima]);

  const periodoFromStr = local.periodoFrom.toISOString().slice(0, 10);
  const periodoToStr = local.periodoTo.toISOString().slice(0, 10);

  const presetPeriodi = [
    { label: "Ultimo mese", days: 30 },
    { label: "Ultimo trimestre", days: 90 },
    { label: "Ultimo semestre", days: 180 },
    { label: "Ultimo anno", days: 365 },
    { label: "Anno corrente (YTD)", custom: "ytd" },
    { label: "Anno precedente", custom: "yp" }
  ];
  function setPreset(p) {
    const to = new Date(2026, 4, 25);
    let from;
    if (p.custom === "ytd") from = new Date(2026, 0, 1);
    else if (p.custom === "yp") { from = new Date(2025, 0, 1); }
    else { from = new Date(to); from.setDate(to.getDate() - p.days); }
    const toFinal = p.custom === "yp" ? new Date(2025, 11, 31) : to;
    update({ periodoFrom: from, periodoTo: toFinal });
  }

  return (
    <div>
      <div className="content__header">
        <div>
          <h1 className="page-title">Impostazione filtri per selezione di interesse</h1>
          <div className="page-sub">Definisci i criteri di selezione per le maschere di riepilogo e dettaglio. Anteprima risultati in tempo reale.</div>
        </div>
        <div className="row">
          <button className="btn" onClick={reset}><Icon name="refresh" size={12} /> Reset</button>
          <button className="btn"><Icon name="save" size={12} /> Salva ricerca</button>
          <button className="btn btn--primary" onClick={apply}>
            <Icon name="check" size={12} color="white" /> Applica filtri ({D.fmtNum(anteprima.length)} record)
          </button>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1fr 320px", gap: 12 }}>
        <div className="col" style={{ gap: 12 }}>
          {/* Periodo */}
          <Card title="Periodo temporale" sub="Intervallo di osservazione">
            <div className="row" style={{ gap: 16, alignItems: "flex-end" }}>
              <div className="field" style={{ flex: 1 }}>
                <label className="field__label">Data inizio</label>
                <div className="field__wrap">
                  <span className="field__icon"><Icon name="calendar" size={13} /></span>
                  <input
                    type="date"
                    className="input input--with-icon"
                    value={periodoFromStr}
                    onChange={e => update({ periodoFrom: new Date(e.target.value) })}
                  />
                </div>
              </div>
              <div className="field" style={{ flex: 1 }}>
                <label className="field__label">Data fine</label>
                <div className="field__wrap">
                  <span className="field__icon"><Icon name="calendar" size={13} /></span>
                  <input
                    type="date"
                    className="input input--with-icon"
                    value={periodoToStr}
                    onChange={e => update({ periodoTo: new Date(e.target.value) })}
                  />
                </div>
              </div>
            </div>
            <hr className="sep" />
            <div className="row row--wrap" style={{ gap: 6 }}>
              <span className="filter-bar__label">Preset</span>
              {presetPeriodi.map(p => (
                <button key={p.label} className="chip" onClick={() => setPreset(p)}>{p.label}</button>
              ))}
            </div>
          </Card>

          {/* Dipartimento + Regime */}
          <div className="grid grid-2">
            <Card title="Dipartimento" sub="Selezione multipla">
              <div style={{ maxHeight: 240, overflow: "auto", display: "flex", flexDirection: "column", gap: 6 }}>
                {D.dipartimenti.map(d => (
                  <label key={d.id} className="checkbox">
                    <input type="checkbox" checked={local.dipartimenti.includes(d.id)} onChange={() => toggleArr("dipartimenti", d.id)} />
                    <span style={{ flex: 1 }}>{d.nome}</span>
                  </label>
                ))}
              </div>
            </Card>
            <Card title="Regime di ricovero" sub="Selezione multipla">
              <div className="col" style={{ gap: 6 }}>
                {D.regimi.map(r => (
                  <label key={r.id} className="checkbox">
                    <input type="checkbox" checked={local.regimi.includes(r.id)} onChange={() => toggleArr("regimi", r.id)} />
                    <span style={{ flex: 1 }}>{r.nome}</span>
                    <span className="pill" style={{ background: r.colore + "1A", color: r.colore, borderColor: r.colore + "33" }}>{r.id}</span>
                  </label>
                ))}
              </div>
              <hr className="sep" />
              <div className="field__label" style={{ marginBottom: 6 }}>Tipo intervento</div>
              <div className="row">
                <label className="radio">
                  <input type="radio" name="ti" checked={local.tipoIntervento.length === 0} onChange={() => update({ tipoIntervento: [] })} />
                  <span>Tutti</span>
                </label>
                <label className="radio">
                  <input type="radio" name="ti" checked={local.tipoIntervento.length === 1 && local.tipoIntervento[0] === "EL"} onChange={() => update({ tipoIntervento: ["EL"] })} />
                  <span>Solo elettivi</span>
                </label>
                <label className="radio">
                  <input type="radio" name="ti" checked={local.tipoIntervento.length === 1 && local.tipoIntervento[0] === "PS"} onChange={() => update({ tipoIntervento: ["PS"] })} />
                  <span>Solo PS/Urgenze</span>
                </label>
              </div>
            </Card>
          </div>

          {/* Pazienti */}
          <Card title="Caratteristiche paziente">
            <div className="grid grid-3">
              <div>
                <div className="field__label" style={{ marginBottom: 8 }}>Genere</div>
                <div className="col" style={{ gap: 6 }}>
                  {D.generi.map(g => (
                    <label key={g.id} className="checkbox">
                      <input type="checkbox" checked={local.generi.includes(g.id)} onChange={() => toggleArr("generi", g.id)} />
                      <span>{g.nome}</span>
                    </label>
                  ))}
                </div>
              </div>
              <div>
                <div className="field__label" style={{ marginBottom: 8 }}>Fasce di età</div>
                <div className="col" style={{ gap: 6 }}>
                  {D.fasceEta.map(f => (
                    <label key={f.id} className="checkbox">
                      <input type="checkbox" checked={local.fasceEta.includes(f.id)} onChange={() => toggleArr("fasceEta", f.id)} />
                      <span>{f.nome}</span>
                    </label>
                  ))}
                </div>
              </div>
              <div>
                <div className="field__label" style={{ marginBottom: 8 }}>Provenienza</div>
                <div className="col" style={{ gap: 6 }}>
                  {D.provenienze.map(p => (
                    <label key={p} className="checkbox">
                      <input type="checkbox" checked={local.provenienze.includes(p)} onChange={() => toggleArr("provenienze", p)} />
                      <span style={{ fontSize: 12 }}>{p}</span>
                    </label>
                  ))}
                </div>
              </div>
            </div>
          </Card>

          {/* DRG */}
          <Card title="DRG (medico/chirurgico)" sub="Cerca per codice o descrizione, selezione multipla" action={
            <span className="muted text-sm">{local.drg.length} selezionati</span>
          }>
            <DrgSelector selected={local.drg} onToggle={(c) => toggleArr("drg", c)} />
          </Card>

          {/* Procedure */}
          <Card title="Procedure (ICD-9-CM)" sub="Codice e descrizione procedura principale" action={
            <span className="muted text-sm">{local.procedure.length} selezionate</span>
          }>
            <ProcedureSelector selected={local.procedure} onToggle={(c) => toggleArr("procedure", c)} />
          </Card>

          {/* Diagnosi */}
          <Card title="Diagnosi principale (ICD-9-CM)" action={
            <span className="muted text-sm">{local.diagnosi.length} selezionate</span>
          }>
            <DiagnosiSelector selected={local.diagnosi} onToggle={(c) => toggleArr("diagnosi", c)} />
          </Card>

          {/* PNE */}
          <Card title="Indicatori PNE" sub="Programma Nazionale Esiti — selezione multipla" action={
            <span className="muted text-sm">{local.pne.length} selezionati</span>
          }>
            <PneSelector selected={local.pne} onToggle={(c) => toggleArr("pne", c)} />
          </Card>
        </div>

        {/* Right column: preview + saved */}
        <div className="col" style={{ gap: 12 }}>
          <Card title="Anteprima selezione" sub="Aggiornata in tempo reale">
            <div style={{ textAlign: "center", padding: "8px 0 12px" }}>
              <div style={{ fontSize: 36, fontWeight: 700, color: "var(--c-primary)", letterSpacing: "-0.02em", fontVariantNumeric: "tabular-nums" }}>
                {D.fmtNum(previewKpis.ricoveri)}
              </div>
              <div style={{ fontSize: 11.5, color: "var(--c-text-3)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>
                Ricoveri selezionati
              </div>
            </div>
            <hr className="sep" />
            <div className="col" style={{ gap: 10 }}>
              <PreviewRow label="Pazienti distinti" value={D.fmtNum(previewKpis.pazienti)} />
              <PreviewRow label="Ricoveri" value={D.fmtNum(previewKpis.ricoveri)} />
              <PreviewRow label="Interventi eseguiti" value={D.fmtNum(previewKpis.interventi)} />
              <PreviewRow label="DRG selezionati" value={local.drg.length || "Tutti"} />
              <PreviewRow label="Procedure selezionate" value={local.procedure.length || "Tutte"} />
              <PreviewRow label="Diagnosi selezionate" value={local.diagnosi.length || "Tutte"} />
              <PreviewRow label="Dipartimenti" value={local.dipartimenti.length || "Tutti"} />
              <PreviewRow label="Indicatori PNE" value={local.pne.length || "—"} />
            </div>
            <hr className="sep" />
            <button className="btn btn--primary btn--lg" style={{ width: "100%", justifyContent: "center" }} onClick={apply}>
              Applica e visualizza riepilogo
            </button>
          </Card>

          <Card title="Ricerche salvate" sub="Recenti" flush>
            {D.ricercheSalvate.map((rc, i) => (
              <div key={i} style={{ padding: "10px 14px", borderBottom: i < D.ricercheSalvate.length - 1 ? "1px solid var(--c-border)" : "none", cursor: "pointer" }} className="saved-row">
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 6 }}>
                  <span style={{ fontSize: 12.5, fontWeight: 500, color: "var(--c-text)" }}>{rc.nome}</span>
                  <Icon name="chevron-right" size={12} color="#94A3B8" />
                </div>
                <div className="muted text-sm" style={{ marginTop: 2 }}>{D.fmtNum(rc.count)} record</div>
              </div>
            ))}
          </Card>

          <Card title="Esportazione" tight>
            <div className="col" style={{ gap: 6, padding: 8 }}>
              <button className="btn" style={{ justifyContent: "flex-start", width: "100%" }}><Icon name="download" size={12} /> Esporta CSV</button>
              <button className="btn" style={{ justifyContent: "flex-start", width: "100%" }}><Icon name="download" size={12} /> Esporta XLSX</button>
              <button className="btn" style={{ justifyContent: "flex-start", width: "100%" }}><Icon name="download" size={12} /> Esporta PDF report</button>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

function PreviewRow({ label, value }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 12.5 }}>
      <span style={{ color: "var(--c-text-3)" }}>{label}</span>
      <span style={{ fontWeight: 600, color: "var(--c-text)", fontVariantNumeric: "tabular-nums" }}>{value}</span>
    </div>
  );
}

function DrgSelector({ selected, onToggle }) {
  const [q, setQ] = r2us("");
  const D = window.DATA;
  const filtered = D.drgList.filter(d =>
    !q || d.codice.includes(q) || d.desc.toLowerCase().includes(q.toLowerCase())
  );
  return (
    <div>
      <div className="field__wrap" style={{ marginBottom: 10 }}>
        <span className="field__icon"><Icon name="search" size={13} /></span>
        <input
          className="input input--with-icon"
          placeholder="Cerca DRG per codice o descrizione…"
          value={q}
          onChange={e => setQ(e.target.value)}
        />
      </div>
      <div style={{ maxHeight: 220, overflow: "auto", border: "1px solid var(--c-border)", borderRadius: 6 }}>
        <table className="table" style={{ fontSize: 12 }}>
          <thead>
            <tr>
              <th style={{ width: 30 }}></th>
              <th style={{ width: 60 }}>Cod.</th>
              <th>Descrizione</th>
              <th className="num" style={{ width: 60 }}>Peso</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(d => {
              const isSel = selected.includes(d.codice);
              return (
                <tr key={d.codice} className="is-clickable" onClick={() => onToggle(d.codice)}>
                  <td><label className="checkbox" onClick={e => e.stopPropagation()}><input type="checkbox" checked={isSel} onChange={() => onToggle(d.codice)} /></label></td>
                  <td><span className="mono" style={{ color: "var(--c-primary)", fontWeight: 600 }}>{d.codice}</span></td>
                  <td>{d.desc}</td>
                  <td className="num tnum">{d.peso.toFixed(2)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ProcedureSelector({ selected, onToggle }) {
  const [q, setQ] = r2us("");
  const D = window.DATA;
  const filtered = D.procedure.filter(p =>
    !q || p.codice.includes(q) || p.nome.toLowerCase().includes(q.toLowerCase())
  );
  return (
    <div>
      <div className="field__wrap" style={{ marginBottom: 10 }}>
        <span className="field__icon"><Icon name="search" size={13} /></span>
        <input className="input input--with-icon" placeholder="Cerca procedura per codice ICD o nome…" value={q} onChange={e => setQ(e.target.value)} />
      </div>
      <div style={{ maxHeight: 200, overflow: "auto", border: "1px solid var(--c-border)", borderRadius: 6 }}>
        <table className="table" style={{ fontSize: 12 }}>
          <thead>
            <tr><th style={{ width: 30 }}></th><th style={{ width: 72 }}>ICD-9</th><th>Procedura</th><th style={{ width: 60 }}>DRG</th></tr>
          </thead>
          <tbody>
            {filtered.map(p => {
              const isSel = selected.includes(p.codice);
              return (
                <tr key={p.codice} className="is-clickable" onClick={() => onToggle(p.codice)}>
                  <td><label className="checkbox" onClick={e => e.stopPropagation()}><input type="checkbox" checked={isSel} onChange={() => onToggle(p.codice)} /></label></td>
                  <td><span className="mono" style={{ color: "var(--c-primary)", fontWeight: 600 }}>{p.codice}</span></td>
                  <td>{p.nome}</td>
                  <td><span className="pill pill--neutral">{p.drg}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function DiagnosiSelector({ selected, onToggle }) {
  const [q, setQ] = r2us("");
  const D = window.DATA;
  const filtered = D.diagnosi.filter(p =>
    !q || p.codice.includes(q) || p.nome.toLowerCase().includes(q.toLowerCase())
  );
  return (
    <div>
      <div className="field__wrap" style={{ marginBottom: 10 }}>
        <span className="field__icon"><Icon name="search" size={13} /></span>
        <input className="input input--with-icon" placeholder="Cerca diagnosi per codice ICD o nome…" value={q} onChange={e => setQ(e.target.value)} />
      </div>
      <div style={{ maxHeight: 200, overflow: "auto", border: "1px solid var(--c-border)", borderRadius: 6 }}>
        <table className="table" style={{ fontSize: 12 }}>
          <thead><tr><th style={{ width: 30 }}></th><th style={{ width: 72 }}>ICD-9</th><th>Diagnosi</th><th style={{ width: 60 }}>DRG</th></tr></thead>
          <tbody>
            {filtered.map(p => {
              const isSel = selected.includes(p.codice);
              return (
                <tr key={p.codice} className="is-clickable" onClick={() => onToggle(p.codice)}>
                  <td><label className="checkbox" onClick={e => e.stopPropagation()}><input type="checkbox" checked={isSel} onChange={() => onToggle(p.codice)} /></label></td>
                  <td><span className="mono" style={{ color: "var(--c-primary)", fontWeight: 600 }}>{p.codice}</span></td>
                  <td>{p.nome}</td>
                  <td><span className="pill pill--neutral">{p.drg}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function PneSelector({ selected, onToggle }) {
  const D = window.DATA;
  return (
    <div className="col" style={{ gap: 6 }}>
      {D.pneIndicatori.map(p => (
        <label key={p.id} className="checkbox" style={{ alignItems: "flex-start", padding: "6px 8px", border: "1px solid var(--c-border)", borderRadius: 6, background: selected.includes(p.id) ? "var(--c-primary-50)" : "var(--c-surface)" }}>
          <input type="checkbox" checked={selected.includes(p.id)} onChange={() => onToggle(p.id)} style={{ marginTop: 2 }} />
          <div style={{ flex: 1 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span style={{ fontSize: 12.5, color: "var(--c-text)", fontWeight: 500 }}>{p.nome}</span>
              <span className="pill pill--neutral" style={{ marginLeft: 8 }}>{p.id}</span>
            </div>
            <div className="muted text-sm" style={{ marginTop: 2 }}>Soglia di riferimento: {p.soglia}{p.unit}</div>
          </div>
        </label>
      ))}
    </div>
  );
}

Object.assign(window, { Mask2Filtri });
