/* Maschera 4 — Strumenti di Intelligenza Artificiale
   Fattori di influenza su: costo totale, costo DM, gg di degenza, margine vs DRG */
const { useState: r4us, useMemo: r4um } = React;

const AI_TARGETS = [
  { id: "costoTotale", label: "Costo totale", unit: "€", color: "#008A3D" },
  { id: "costoDM", label: "Costo dispositivi medici", unit: "€", color: "#0E7C8C" },
  { id: "ggDegenza", label: "Giornate di degenza", unit: "gg", color: "#7C3AED" },
  { id: "margine", label: "Margine vs DRG", unit: "€", color: "#C8102E" }
];

// Pre-computed feature importance per target (plausibile, ordinato)
const FEATURE_IMPORTANCE = {
  costoTotale: [
    { feat: "Peso DRG", imp: 0.28, dir: "pos" },
    { feat: "Durata intervento", imp: 0.22, dir: "pos" },
    { feat: "Giornate di degenza", imp: 0.17, dir: "pos" },
    { feat: "Dipartimento (CardC/NeurC)", imp: 0.11, dir: "pos" },
    { feat: "Età paziente", imp: 0.07, dir: "pos" },
    { feat: "Tipo intervento (Urgenza)", imp: 0.06, dir: "pos" },
    { feat: "N° DM utilizzati", imp: 0.05, dir: "pos" },
    { feat: "Regime ordinario", imp: 0.03, dir: "pos" },
    { feat: "Comorbidità", imp: 0.01, dir: "pos" }
  ],
  costoDM: [
    { feat: "Categoria DRG (protesico)", imp: 0.41, dir: "pos" },
    { feat: "Durata intervento", imp: 0.16, dir: "pos" },
    { feat: "Tipo protesi/dispositivo", imp: 0.14, dir: "pos" },
    { feat: "Chirurgo (variabilità individuale)", imp: 0.10, dir: "neutral" },
    { feat: "Dipartimento", imp: 0.08, dir: "pos" },
    { feat: "Età paziente", imp: 0.05, dir: "pos" },
    { feat: "Peso DRG", imp: 0.04, dir: "pos" },
    { feat: "Urgenza vs elettivo", imp: 0.02, dir: "pos" }
  ],
  ggDegenza: [
    { feat: "Età paziente", imp: 0.24, dir: "pos" },
    { feat: "Peso DRG", imp: 0.21, dir: "pos" },
    { feat: "Regime di ricovero", imp: 0.18, dir: "neg" },
    { feat: "Diagnosi (complicanze)", imp: 0.13, dir: "pos" },
    { feat: "Provenienza (PS)", imp: 0.09, dir: "pos" },
    { feat: "Comorbidità", imp: 0.07, dir: "pos" },
    { feat: "Giorno settimana ingresso", imp: 0.04, dir: "neutral" },
    { feat: "Genere", imp: 0.02, dir: "neutral" },
    { feat: "Dipartimento", imp: 0.02, dir: "pos" }
  ],
  margine: [
    { feat: "Costo DM", imp: 0.31, dir: "neg" },
    { feat: "Giornate di degenza", imp: 0.24, dir: "neg" },
    { feat: "Tariffa DRG", imp: 0.18, dir: "pos" },
    { feat: "Durata intervento", imp: 0.12, dir: "neg" },
    { feat: "Regime (DS/DH)", imp: 0.07, dir: "pos" },
    { feat: "Dipartimento", imp: 0.04, dir: "neutral" },
    { feat: "Età paziente", imp: 0.03, dir: "neg" },
    { feat: "Urgenza vs elettivo", imp: 0.01, dir: "neg" }
  ]
};

function Mask4IA({ filters, onEditFilters }) {
  const D = window.DATA;
  const rows = r4um(() => D.applyFilters(filters), [filters]);
  const [target, setTarget] = r4us("costoTotale");
  const [model, setModel] = r4us("gbm");
  const targetMeta = AI_TARGETS.find(t => t.id === target);

  // Extract values
  function valueFor(r) {
    if (target === "costoTotale") return r.costoTotale;
    if (target === "costoDM") return r.costoDM;
    if (target === "ggDegenza") return r.ggDegenza;
    if (target === "margine") return r.margine;
    return 0;
  }
  function fmtVal(v) {
    if (target === "ggDegenza") return v.toFixed(1) + " gg";
    return D.fmtEuro(Math.round(v));
  }

  const stats = r4um(() => {
    const vals = rows.map(valueFor);
    const n = vals.length;
    if (!n) return { n: 0 };
    const mean = vals.reduce((s, x) => s + x, 0) / n;
    const sorted = [...vals].sort((a, b) => a - b);
    const median = sorted[Math.floor(n / 2)];
    const p10 = sorted[Math.floor(n * 0.1)];
    const p90 = sorted[Math.floor(n * 0.9)];
    return { n, mean, median, p10, p90, min: sorted[0], max: sorted[n - 1] };
  }, [rows, target]);

  const featImp = FEATURE_IMPORTANCE[target];

  // Mock model metrics that vary by target/model
  const metrics = r4um(() => {
    const base = {
      gbm: { name: "Gradient Boosting", r2: 0.847, mae: 0.0, rmse: 0.0 },
      rf: { name: "Random Forest", r2: 0.812, mae: 0.0, rmse: 0.0 },
      lr: { name: "Regressione regolarizzata", r2: 0.683, mae: 0.0, rmse: 0.0 }
    }[model];
    const variance = stats.mean ? Math.abs(stats.p90 - stats.p10) / 4 : 0;
    return {
      ...base,
      mae: Math.round(variance * (1 - base.r2 * 0.85) * 100) / 100,
      rmse: Math.round(variance * (1 - base.r2 * 0.8) * 100) / 100
    };
  }, [target, model, stats]);

  // What-if simulation state
  const [whatIf, setWhatIf] = r4us({
    eta: 65,
    pesoDRG: 1.5,
    durataMin: 90,
    ggDegenza: 5,
    regime: "ORD"
  });

  // Naive prediction formula (just for demo plausibility)
  const prediction = r4um(() => {
    const { eta, pesoDRG, durataMin, ggDegenza, regime } = whatIf;
    const regCoef = regime === "ORD" ? 1.0 : regime === "URG" ? 1.15 : 0.65;
    if (target === "costoTotale") return Math.round((pesoDRG * 1800 + durataMin * 22 + ggDegenza * 480 + eta * 8) * regCoef);
    if (target === "costoDM") return Math.round((pesoDRG * 980 + durataMin * 6) * regCoef);
    if (target === "ggDegenza") return Math.max(0.5, Math.round((pesoDRG * 1.4 + eta * 0.04 + (regime === "ORD" ? 2 : 0)) * 10) / 10);
    if (target === "margine") return Math.round((pesoDRG * 2400 - durataMin * 18 - ggDegenza * 420 - eta * 6) * regCoef);
    return 0;
  }, [whatIf, target]);

  // Anomalie: ricoveri con margine molto negativo (oppure costo > p95)
  const anomalie = r4um(() => {
    if (!rows.length) return [];
    const valSorted = rows.map(r => ({ r, v: valueFor(r) })).sort((a, b) => target === "margine" ? a.v - b.v : b.v - a.v);
    return valSorted.slice(0, 10).map(x => x.r);
  }, [rows, target]);

  // Cluster mock: K=4 segments
  const clusters = r4um(() => {
    // Simple bucketing on DRG peso (proxy)
    const buckets = [
      { id: "C1", nome: "Bassa complessità / DS", filter: r => r.drgPeso < 1 && (r.regime === "DS" || r.regime === "DH"), color: "#008A3D" },
      { id: "C2", nome: "Standard elettivo", filter: r => r.drgPeso < 1.5 && r.tipoIntervento === "EL" && r.regime === "ORD", color: "#0E7C8C" },
      { id: "C3", nome: "Alta complessità ortopedica", filter: r => r.drgPeso >= 1.5 && r.drgPeso < 3 && (r.dipartimento === "ORTOP" || r.dipartimento === "VASCO"), color: "#7C3AED" },
      { id: "C4", nome: "Cardio/Neuro alta intensità", filter: r => r.drgPeso >= 3 || r.dipartimento === "CARDC" || r.dipartimento === "NEURC", color: "#C8102E" }
    ];
    return buckets.map(b => {
      const items = rows.filter(b.filter);
      const vals = items.map(valueFor);
      const mean = vals.length ? vals.reduce((s, x) => s + x, 0) / vals.length : 0;
      return { ...b, count: items.length, mean };
    });
  }, [rows, target]);

  return (
    <div>
      <div className="content__header">
        <div>
          <h1 className="page-title">Strumenti di intelligenza artificiale</h1>
          <div className="page-sub">
            Analisi dei <strong style={{ color: "var(--c-text-2)" }}>fattori di influenza</strong> su costo, costo DM, giornate di degenza e margine rispetto al DRG.
            Modello supervisionato addestrato sul perimetro filtrato.
          </div>
        </div>
        <div className="row">
          <Segmented value={model} onChange={setModel} options={[
            { value: "gbm", label: "Gradient Boosting" },
            { value: "rf", label: "Random Forest" },
            { value: "lr", label: "Reg. lineare" }
          ]} />
          <button className="btn btn--primary"><Icon name="refresh" size={12} color="white" /> Riaddestra</button>
        </div>
      </div>

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

      {/* Target selector */}
      <Card title="Variabile target" sub="Scegli la metrica da spiegare" tight>
        <div style={{ padding: 4, display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
          {AI_TARGETS.map(t => (
            <button
              key={t.id}
              onClick={() => setTarget(t.id)}
              style={{
                textAlign: "left",
                padding: "12px 14px",
                border: "1.5px solid " + (target === t.id ? t.color : "var(--c-border)"),
                background: target === t.id ? t.color + "12" : "var(--c-surface)",
                borderRadius: 8,
                cursor: "pointer",
                fontFamily: "inherit"
              }}
            >
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ width: 8, height: 8, borderRadius: 2, background: t.color }} />
                <span style={{ fontSize: 12.5, color: "var(--c-text-2)", fontWeight: 600 }}>{t.label}</span>
              </div>
              <div style={{ marginTop: 6, fontSize: 18, fontWeight: 700, color: target === t.id ? t.color : "var(--c-text)", fontVariantNumeric: "tabular-nums", letterSpacing: "-0.01em" }}>
                {target === t.id ? (
                  t.id === "ggDegenza" ? stats.mean.toFixed(1) + " gg" : D.fmtEuro(Math.round(stats.mean))
                ) : ""}
              </div>
              <div className="muted text-sm" style={{ marginTop: 2 }}>{target === t.id ? "valore medio nel perimetro" : "Clicca per selezionare"}</div>
            </button>
          ))}
        </div>
      </Card>

      {/* Model metrics row */}
      <div className="kpis" style={{ marginTop: 12, marginBottom: 12, gridTemplateColumns: "repeat(4, 1fr)" }}>
        <KpiCard label="Record di training" value={D.fmtNum(stats.n)} icon="reports" />
        <KpiCard label="R² (validation)" value={metrics.r2.toFixed(3)} deltaLabel={metrics.name} icon="check" tone="accent" />
        <KpiCard label="MAE" value={target === "ggDegenza" ? metrics.mae.toFixed(2) + " gg" : D.fmtEuro(metrics.mae)} deltaLabel="Mean Absolute Error" />
        <KpiCard label="RMSE" value={target === "ggDegenza" ? metrics.rmse.toFixed(2) + " gg" : D.fmtEuro(metrics.rmse)} deltaLabel="Root Mean Squared Error" />
      </div>

      {/* Feature importance + scatter */}
      <div className="grid" style={{ gridTemplateColumns: "3fr 2fr", gap: 12, marginBottom: 12 }}>
        <Card title="Fattori di influenza" sub={"Importanza relativa delle variabili su " + targetMeta.label.toLowerCase()}>
          <FeatureImportanceBars data={featImp} color={targetMeta.color} />
          <div style={{ marginTop: 12, padding: "10px 12px", background: "var(--c-primary-50)", borderRadius: 6, fontSize: 12, color: "var(--c-text-2)", display: "flex", gap: 10 }}>
            <Icon name="info" size={14} color="#008A3D" />
            <div>
              <strong>Insight automatico:</strong>{" "}
              {target === "costoTotale" && <>il <strong>peso DRG</strong> e la <strong>durata intervento</strong> spiegano oltre il 50% della varianza del costo. Interventi {">"}3h hanno costo medio +42% rispetto alla mediana di reparto.</>}
              {target === "costoDM" && <>la <strong>tipologia DRG</strong> (protesica vs non protesica) è il driver principale. Si osserva variabilità del costo DM <strong>±18%</strong> tra chirurghi per stesso DRG.</>}
              {target === "ggDegenza" && <>l'<strong>età</strong> e il <strong>peso DRG</strong> spiegano oltre il 45% della degenza. Ingressi da PS hanno degenza +1.8gg rispetto agli elettivi a parità di DRG.</>}
              {target === "margine" && <>il <strong>costo DM</strong> e le <strong>giornate di degenza</strong> sono i fattori che più erodono il margine. <strong>12% dei ricoveri</strong> hanno margine negativo.</>}
            </div>
          </div>
        </Card>

        <Card title="Predetto vs reale" sub="Validazione modello — campione 200 record">
          <ScatterPredVsReal rows={rows} valueFor={valueFor} r2={metrics.r2} color={targetMeta.color} />
        </Card>
      </div>

      {/* What-if simulator + cluster */}
      <div className="grid grid-2" style={{ marginBottom: 12 }}>
        <Card title="Simulatore what-if" sub="Stima il valore atteso al variare delle features">
          <WhatIfPanel whatIf={whatIf} setWhatIf={setWhatIf} prediction={prediction} fmtVal={fmtVal} color={targetMeta.color} targetLabel={targetMeta.label} />
        </Card>

        <Card title="Segmentazione clienti (clustering)" sub="K=4 cluster identificati su pattern multi-feature" flush>
          <table className="table">
            <thead>
              <tr>
                <th>Cluster</th>
                <th className="num">Ricoveri</th>
                <th className="num">{targetMeta.label} medio</th>
                <th style={{ width: 100 }}></th>
              </tr>
            </thead>
            <tbody>
              {clusters.map(c => {
                const max = Math.max(...clusters.map(x => x.mean));
                return (
                  <tr key={c.id}>
                    <td>
                      <div className="row">
                        <span style={{ width: 10, height: 10, borderRadius: 2, background: c.color }} />
                        <div>
                          <div style={{ fontWeight: 600, color: "var(--c-text)", fontSize: 12.5 }}>{c.nome}</div>
                          <div className="muted text-sm">{c.id}</div>
                        </div>
                      </div>
                    </td>
                    <td className="num tnum"><strong>{D.fmtNum(c.count)}</strong></td>
                    <td className="num tnum">{fmtVal(c.mean)}</td>
                    <td>
                      <div style={{ height: 6, background: "#F1F5F9", borderRadius: 2, overflow: "hidden" }}>
                        <div style={{ height: "100%", width: (Math.abs(c.mean) / Math.max(1, Math.abs(max))) * 100 + "%", background: c.color }} />
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>
      </div>

      {/* Anomalie */}
      <Card title="Ricoveri anomali rilevati" sub={target === "margine" ? "Margine più negativo nel perimetro" : "Valori fuori dal pattern atteso (top 10 outlier)"} action={
        <Pill tone="warn">{anomalie.length} casi</Pill>
      } flush>
        <table className="table">
          <thead>
            <tr>
              <th style={{ width: 28 }}></th>
              <th>Ricovero</th>
              <th>Dipartimento</th>
              <th>DRG</th>
              <th>Chirurgo</th>
              <th className="num">{targetMeta.label}</th>
              <th className="num">vs medio</th>
              <th>Driver principale</th>
            </tr>
          </thead>
          <tbody>
            {anomalie.map(r => {
              const v = valueFor(r);
              const delta = stats.mean ? ((v - stats.mean) / stats.mean) * 100 : 0;
              const driver = target === "costoDM" ? "Alto consumo dispositivi"
                          : target === "ggDegenza" ? "Età + comorbidità"
                          : target === "margine" ? "Costo DM > ricavo DRG"
                          : "Durata intervento";
              return (
                <tr key={r.id}>
                  <td><Icon name="alerts" size={14} color="#C8102E" /></td>
                  <td><span className="mono" style={{ color: "var(--c-primary)" }}>{r.id}</span></td>
                  <td style={{ fontSize: 12 }}>{D.dipNome(r.dipartimento)}</td>
                  <td><span className="mono" style={{ color: "var(--c-primary)", fontWeight: 600 }}>{r.drg}</span> <span className="muted" style={{ fontSize: 11 }}>{r.drgDesc.slice(0, 30)}…</span></td>
                  <td style={{ fontSize: 12 }}>{r.chirurgoNome || "—"}</td>
                  <td className="num tnum"><strong>{fmtVal(v)}</strong></td>
                  <td className="num tnum"><Pill tone={delta > 0 ? "warn" : "accent"}>{delta > 0 ? "+" : ""}{delta.toFixed(0)}%</Pill></td>
                  <td style={{ fontSize: 12 }}>{driver}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

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

function FeatureImportanceBars({ data, color }) {
  const max = Math.max(...data.map(d => d.imp));
  return (
    <div className="col" style={{ gap: 8 }}>
      {data.map(d => (
        <div key={d.feat} style={{ display: "grid", gridTemplateColumns: "200px 1fr 50px", alignItems: "center", gap: 12 }}>
          <span style={{ fontSize: 12.5, color: "var(--c-text-2)", fontWeight: 500 }}>{d.feat}</span>
          <div style={{ height: 14, background: "#F1F5F9", borderRadius: 2, overflow: "hidden", position: "relative" }}>
            <div style={{ height: "100%", width: (d.imp / max) * 100 + "%", background: color, borderRadius: 2 }} />
          </div>
          <span className="tnum" style={{ fontSize: 12, color: "var(--c-text)", fontWeight: 600, textAlign: "right" }}>{(d.imp * 100).toFixed(1)}%</span>
        </div>
      ))}
    </div>
  );
}

function ScatterPredVsReal({ rows, valueFor, r2, color }) {
  const sample = rows.slice(0, 200);
  const values = sample.map(valueFor);
  const min = Math.min(...values, 0);
  const max = Math.max(...values, 1);
  const w = 360, h = 280;
  const pad = 30;
  // Synthetic noise around y=x line to simulate predictions
  function predict(actual, idx) {
    const noise = ((idx * 7.13) % 10 - 5) / 5 * (max - min) * (1 - r2) * 0.6;
    return actual + noise;
  }
  function sx(v) { return pad + ((v - min) / (max - min || 1)) * (w - pad * 2); }
  function sy(v) { return h - pad - ((v - min) / (max - min || 1)) * (h - pad * 2); }

  return (
    <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="xMidYMid meet" style={{ display: "block" }}>
      {/* axes */}
      <line x1={pad} y1={h - pad} x2={w - pad} y2={h - pad} stroke="#CBD5E1" strokeWidth="1" />
      <line x1={pad} y1={pad} x2={pad} y2={h - pad} stroke="#CBD5E1" strokeWidth="1" />
      {/* y=x reference */}
      <line x1={sx(min)} y1={sy(min)} x2={sx(max)} y2={sy(max)} stroke="#94A3B8" strokeWidth="1" strokeDasharray="4,4" />
      {/* points */}
      {sample.map((r, i) => {
        const real = values[i];
        const pred = predict(real, i);
        return <circle key={i} cx={sx(real)} cy={sy(pred)} r="2.5" fill={color} fillOpacity="0.45" />;
      })}
      {/* labels */}
      <text x={w / 2} y={h - 8} fontSize="10.5" fill="#64748B" textAnchor="middle">Reale</text>
      <text x={12} y={h / 2} fontSize="10.5" fill="#64748B" textAnchor="middle" transform={`rotate(-90, 12, ${h / 2})`}>Predetto</text>
      <text x={w - pad} y={pad - 8} fontSize="11" fill={color} textAnchor="end" fontWeight="700">R² = {r2.toFixed(3)}</text>
    </svg>
  );
}

function WhatIfPanel({ whatIf, setWhatIf, prediction, fmtVal, color, targetLabel }) {
  function s(k, v) { setWhatIf({ ...whatIf, [k]: v }); }
  return (
    <div>
      <div className="col" style={{ gap: 14 }}>
        <WhatIfSlider label="Età paziente" min={0} max={100} step={1} value={whatIf.eta} unit="anni" onChange={v => s("eta", v)} />
        <WhatIfSlider label="Peso DRG" min={0.3} max={8} step={0.05} value={whatIf.pesoDRG} unit="" onChange={v => s("pesoDRG", v)} />
        <WhatIfSlider label="Durata intervento" min={15} max={400} step={5} value={whatIf.durataMin} unit="min" onChange={v => s("durataMin", v)} />
        <WhatIfSlider label="Giornate di degenza" min={0} max={30} step={1} value={whatIf.ggDegenza} unit="gg" onChange={v => s("ggDegenza", v)} />
        <div className="field">
          <label className="field__label">Regime di ricovero</label>
          <Segmented
            value={whatIf.regime}
            onChange={v => s("regime", v)}
            options={[
              { value: "ORD", label: "Ordinario" },
              { value: "DS", label: "Day Surgery" },
              { value: "URG", label: "Urgenza" }
            ]}
          />
        </div>
      </div>
      <div style={{ marginTop: 18, padding: "14px 16px", background: color + "0E", border: "1.5px solid " + color + "40", borderRadius: 8 }}>
        <div style={{ fontSize: 11, color: "var(--c-text-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em" }}>Predizione: {targetLabel}</div>
        <div style={{ fontSize: 28, fontWeight: 700, color: color, marginTop: 2, fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em" }}>
          {fmtVal(prediction)}
        </div>
        <div className="muted text-sm" style={{ marginTop: 2 }}>Intervallo di confidenza 95%: ± {fmtVal(Math.abs(prediction) * 0.18)}</div>
      </div>
    </div>
  );
}

function WhatIfSlider({ label, min, max, step, value, unit, onChange }) {
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 4 }}>
        <label className="field__label">{label}</label>
        <span className="tnum" style={{ fontSize: 13, fontWeight: 700, color: "var(--c-text)" }}>{value}{unit ? " " + unit : ""}</span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value} onChange={e => onChange(Number(e.target.value))} style={{ width: "100%", accentColor: "var(--c-primary)" }} />
    </div>
  );
}

Object.assign(window, { Mask4IA });
