/* Maschera Reportistica — generazione report via agente AI (OpenAI tool-use su SQL) */
const { useState: rpus, useEffect: rpuef, useRef: rpuref } = React;

const RP_PALETTE = ["#008A3D", "#0E7C8C", "#7C3AED", "#C8102E", "#C2410C", "#B45309", "#1E5BA8", "#6D28D9"];

function rpMd(text) {
  if (!text) return "";
  const esc = String(text).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  return esc
    .replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
    .replace(/(^|[\s(])\*([^*]+)\*/g, "$1<em>$2</em>")
    .replace(/`([^`]+)`/g, "<code>$1</code>")
    .replace(/\n\s*[-•]\s+(.+)/g, "<li>$1</li>")
    .replace(/(<li>.*<\/li>\s*)+/gs, m => "<ul>" + m + "</ul>")
    .replace(/\n{2,}/g, "<br/><br/>")
    .replace(/\n/g, "<br/>");
}

function MaskReports({ filters, onEditFilters, onCount }) {
  const D = window.DATA;
  const [view, setView] = rpus("list");        // list | new | viewer
  const [list, setList] = rpus(null);
  const [templates, setTemplates] = rpus([]);
  const [aiAttivo, setAiAttivo] = rpus(true);
  const [current, setCurrent] = rpus(null);     // report aperto
  const [err, setErr] = rpus(null);

  function loadList() {
    return D.api.reports.list().then(d => { setList(d.reports); setAiAttivo(d.aiAttivo); if (onCount) onCount(d.count); });
  }
  rpuef(() => { loadList().catch(e => setErr(e.message)); D.api.reports.templates().then(d => { setTemplates(d.templates); setAiAttivo(d.aiAttivo); }).catch(() => {}); }, []);

  function openReport(id) {
    setErr(null); setCurrent(null); setView("viewer");
    D.api.reports.get(id).then(d => setCurrent(d.report)).catch(e => setErr(e.message));
  }
  async function removeReport(id) {
    await D.api.reports.remove(id);
    await loadList();
  }

  return (
    <div>
      <div className="content__header">
        <div>
          <h1 className="page-title">Reportistica</h1>
          <div className="page-sub">Report generati da un agente AI che interroga i dati reali del database.</div>
        </div>
        <div className="row">
          {view !== "list" && <button className="btn" onClick={() => { setView("list"); loadList(); }}><Icon name="chevron-right" size={12} /> Elenco</button>}
          {view === "list" && <button className="btn btn--primary" onClick={() => setView("new")}><Icon name="plus" size={12} color="white" /> Nuovo report</button>}
        </div>
      </div>

      {err && <div className="anag-error"><Icon name="alerts" size={13} color="#C8102E" /> {err}</div>}

      {view === "list" && <ReportList list={list} onOpen={openReport} onRemove={removeReport} onNew={() => setView("new")} />}
      {view === "new" && <ReportNew templates={templates} aiAttivo={aiAttivo} filters={filters} onEditFilters={onEditFilters}
        onCreated={(id) => { loadList(); openReport(id); }} onCancel={() => setView("list")} />}
      {view === "viewer" && <ReportViewer report={current} onReload={(id) => openReport(id)} />}
    </div>
  );
}

function ReportList({ list, onOpen, onRemove, onNew }) {
  const D = window.DATA;
  if (!list) return <div style={{ display: "flex", justifyContent: "center", padding: 60 }}><div className="spinner" /></div>;
  if (!list.length) return (
    <Card>
      <div style={{ textAlign: "center", padding: "30px 0", color: "var(--c-text-3)" }}>
        <div style={{ fontSize: 13, marginBottom: 12 }}>Nessun report ancora generato.</div>
        <button className="btn btn--primary" onClick={onNew}><Icon name="plus" size={12} color="white" /> Crea il primo report</button>
      </div>
    </Card>
  );
  const statoPill = s => s === "completed" ? <Pill tone="primary">Completato</Pill> : s === "generating" ? <Pill tone="warn">In corso…</Pill> : <Pill tone="danger">Errore</Pill>;
  return (
    <Card title="Report salvati" sub={list.length + " report"} flush>
      <table className="table">
        <thead><tr><th>Titolo</th><th>Tipo</th><th>Data</th><th>Stato</th><th style={{ width: 130 }}></th></tr></thead>
        <tbody>
          {list.map(r => (
            <tr key={r.id} className="is-clickable" onClick={() => onOpen(r.id)}>
              <td><strong style={{ color: "var(--c-text)" }}>{r.titolo}</strong></td>
              <td style={{ fontSize: 12 }}>{r.tipo}</td>
              <td className="tnum" style={{ fontSize: 12 }}>{new Date(r.created_at).toLocaleString("it-IT", { day: "2-digit", month: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit" })}</td>
              <td>{statoPill(r.stato)}</td>
              <td>
                <div className="row" style={{ gap: 4, justifyContent: "flex-end" }}>
                  <button className="btn btn--sm" onClick={e => { e.stopPropagation(); onOpen(r.id); }}>Apri</button>
                  <button className="btn btn--sm btn--ghost-danger" onClick={e => { e.stopPropagation(); if (confirm("Eliminare il report?")) onRemove(r.id); }}><Icon name="close" size={12} /></button>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

function ReportNew({ templates, aiAttivo, filters, onEditFilters, onCreated, onCancel }) {
  const D = window.DATA;
  const [tipo, setTipo] = rpus("libero");
  const [richiesta, setRichiesta] = rpus("");
  const [busy, setBusy] = rpus(false);
  const [err, setErr] = rpus(null);

  function pickTemplate(t) { setTipo(t.key); setRichiesta(t.prompt); }
  async function genera() {
    if (!richiesta.trim()) { setErr("Descrivi il report da generare."); return; }
    setBusy(true); setErr(null);
    try { const r = await D.api.reports.create(richiesta.trim(), tipo, filters); onCreated(r.id); }
    catch (e) { setErr(e.message); setBusy(false); }
  }

  return (
    <div className="grid" style={{ gridTemplateColumns: "1fr 300px", gap: 12 }}>
      <Card title="Nuovo report" sub="Descrivi cosa vuoi analizzare: l'agente interrogherà il database e comporrà il report con dati reali.">
        <div className="report-templates">
          {templates.map(t => (
            <button key={t.key} className={"report-tpl " + (tipo === t.key ? "is-active" : "")} onClick={() => pickTemplate(t)}>
              <span className="report-tpl__t">{t.label}</span>
              <span className="report-tpl__d">{t.descr}</span>
            </button>
          ))}
        </div>
        <textarea
          className="report-textarea"
          rows={6}
          placeholder="Es. «Analizza i margini economici per dipartimento, evidenzia i 5 DRG più in perdita e il trend mensile dei costi sala operatoria»…"
          value={richiesta}
          onChange={e => { setRichiesta(e.target.value); setTipo("libero"); }}
          disabled={busy}
        />
        {err && <div className="anag-error" style={{ marginTop: 10 }}><Icon name="alerts" size={13} color="#C8102E" /> {err}</div>}
        <div className="row" style={{ gap: 8, marginTop: 12 }}>
          <button className="btn btn--primary" onClick={genera} disabled={busy || !aiAttivo}>
            {busy ? <><span className="spinner spinner--sm" /> Avvio…</> : <><Icon name="reports" size={12} color="white" /> Genera report</>}
          </button>
          <button className="btn" onClick={onCancel} disabled={busy}>Annulla</button>
        </div>
        {!aiAttivo && <div className="muted" style={{ fontSize: 11.5, marginTop: 8 }}>Agente AI non configurato (manca la API key).</div>}
      </Card>

      <div className="col" style={{ gap: 12 }}>
        <Card title="Perimetro dati" sub="Filtri passati all'agente come contesto">
          <FilterBar filters={filters} onEdit={onEditFilters} />
          <div className="muted" style={{ fontSize: 11.5, marginTop: 8 }}>L'agente può usare questo perimetro o considerare l'intero dataset, in base alla richiesta.</div>
        </Card>
        <Card title="Come funziona" tight>
          <div style={{ padding: "4px 10px 10px", fontSize: 12, color: "var(--c-text-2)", lineHeight: 1.5 }}>
            <p style={{ margin: "6px 0" }}>1. L'agente traduce la richiesta in <strong>query SQL</strong> (sola lettura) sul database.</p>
            <p style={{ margin: "6px 0" }}>2. Compone il report con <strong>KPI, tabelle e grafici</strong> sui dati reali ottenuti.</p>
            <p style={{ margin: "6px 0" }}>3. Il report viene <strong>salvato</strong> e resta consultabile nell'elenco.</p>
          </div>
        </Card>
      </div>
    </div>
  );
}

function ReportViewer({ report, onReload }) {
  const D = window.DATA;
  const [showQueries, setShowQueries] = rpus(false);
  const pollRef = rpuref(null);

  // Polling finché in generazione
  rpuef(() => {
    if (report && report.stato === "generating") {
      pollRef.current = setTimeout(() => onReload(report.id), 2500);
      return () => clearTimeout(pollRef.current);
    }
  }, [report]);

  if (!report) return <div style={{ display: "flex", justifyContent: "center", padding: 60 }}><div className="spinner" /></div>;

  if (report.stato === "generating") {
    return (
      <Card>
        <div style={{ textAlign: "center", padding: "40px 0", color: "var(--c-text-2)" }}>
          <div className="spinner" style={{ margin: "0 auto 14px" }} />
          <div style={{ fontWeight: 600, fontSize: 14 }}>L'agente sta analizzando i dati…</div>
          <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>Interrogazione del database e composizione del report in corso.</div>
        </div>
      </Card>
    );
  }
  if (report.stato === "failed") {
    return <Card><div style={{ padding: 20 }} className="anag-error"><Icon name="alerts" size={14} color="#C8102E" /> Generazione fallita: {report.errore || "errore sconosciuto"}</div></Card>;
  }

  const c = report.contenuto || {};
  return (
    <div className="report-doc">
      <Card flush>
        <div className="report-head">
          <div>
            <div className="report-head__title">{c.titolo || report.titolo}</div>
            <div className="report-head__meta">
              Generato il {new Date(report.created_at).toLocaleString("it-IT")} · modello {report.modello} · {(report.query_log || []).length} query sui dati reali
            </div>
          </div>
          <button className="btn btn--sm" onClick={() => window.print()}><Icon name="download" size={12} /> Stampa / PDF</button>
        </div>
        {c.sintesi && (
          <div className="report-summary">
            <div className="report-summary__label">Sintesi esecutiva</div>
            <div dangerouslySetInnerHTML={{ __html: rpMd(c.sintesi) }} />
          </div>
        )}
      </Card>

      {(c.sezioni || []).map((s, i) => <ReportSection key={i} s={s} />)}

      {(report.query_log || []).length > 0 && (
        <Card title="Trasparenza dati" sub={report.query_log.length + " query SQL eseguite sul database"} flush>
          <div style={{ padding: "0 0 4px" }}>
            <button className="btn btn--sm" style={{ margin: 12 }} onClick={() => setShowQueries(q => !q)}>
              <Icon name={showQueries ? "chevron-up" : "chevron-down"} size={12} /> {showQueries ? "Nascondi query" : "Mostra query eseguite"}
            </button>
            {showQueries && (
              <div style={{ padding: "0 12px 12px" }}>
                {report.query_log.map((q, i) => (
                  <div key={i} className="report-query">
                    <code>{q.query}</code>
                    <span className="report-query__meta">{q.error ? "⚠ " + q.error : (q.rowCount + " righe")}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </Card>
      )}
    </div>
  );
}

function ReportSection({ s }) {
  const D = window.DATA;
  if (s.tipo === "narrativa") {
    return (
      <Card title={s.titolo}>
        <div className="report-narrativa" dangerouslySetInnerHTML={{ __html: rpMd(s.testo) }} />
      </Card>
    );
  }
  if (s.tipo === "kpi") {
    const items = s.kpi || [];
    return (
      <Card title={s.titolo}>
        <div className="kpis" style={{ gridTemplateColumns: "repeat(" + Math.min(4, Math.max(1, items.length)) + ", 1fr)" }}>
          {items.map((k, i) => <KpiCard key={i} label={k.label} value={k.valore} unit={k.unita} deltaLabel={k.nota} />)}
        </div>
      </Card>
    );
  }
  if (s.tipo === "tabella") {
    const cols = s.colonne || [];
    const rows = s.righe || [];
    return (
      <Card title={s.titolo} flush>
        <table className="table">
          <thead><tr>{cols.map((c, i) => <th key={i} className={i > 0 ? "num" : ""}>{c}</th>)}</tr></thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={i}>{(r || []).map((cell, j) => <td key={j} className={j > 0 ? "num tnum" : ""}>{cell}</td>)}</tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }
  if (s.tipo === "grafico") {
    return (
      <Card title={s.titolo}>
        <ReportChart s={s} />
      </Card>
    );
  }
  return null;
}

function ReportChart({ s }) {
  const dati = (s.dati || []).map((d, i) => ({ label: d.label, value: d.valore, color: d.colore || RP_PALETTE[i % RP_PALETTE.length] }));
  if (s.grafico === "torta") {
    return <DonutChart data={dati} colorKey="color" size={200} />;
  }
  if (s.grafico === "linee") {
    const series = (s.serie || []).map((se, i) => ({ label: se.label, data: se.dati || [], color: se.colore || RP_PALETTE[i % RP_PALETTE.length] }));
    return (
      <div>
        <LineChart series={series} xLabels={s.xlabels || []} />
        <div className="legend" style={{ marginTop: 10, justifyContent: "center" }}>
          {series.map((se, i) => <span key={i}><span className="legend__dot" style={{ background: se.color }} />{se.label}</span>)}
        </div>
      </div>
    );
  }
  // barre (default)
  return <BarChartH data={dati} maxBars={20} colorBy={d => d.color} />;
}

Object.assign(window, { MaskReports });
