// ============================================================
// customizing-sub-rda.jsx — Customizing "Modulo RdA" (s140)
// Liste configurabili white-label del modulo RdA: bando, categorie SOA,
// classificazione budget, priorità (con lead-time). CRUD su rda_option.
// Stile coerente con le altre pagine config: tbl dense + modale crea/modifica.
// ============================================================

const RDA_OPTION_KIND_TABS = [
  { kind: 'bando', label: 'Bando', icon: 'flow', hint: 'Bando / lotto / commessa (es. Bando 2, Bando 3…)' },
  { kind: 'work_category', label: 'Categorie SOA', icon: 'package', hint: 'Tipologie lavoro/fornitura (Servizi, Progettazione, Fornitura…)' },
  { kind: 'budget_class', label: 'Budget', icon: 'coins', hint: 'Classificazione importo a budget (Budget, Contingencies, Extra Budget…)' },
  { kind: 'priority', label: 'Priorità', icon: 'bell', hint: 'Livelli di priorità con lead-time in giorni (alimenta lo SLA)' },
];

// Modale crea/modifica di una singola opzione.
window.RdaOptionModal = function RdaOptionModal({ kind, sel, onClose, onSaved }) {
  const { user, pushToast, addRdaOption, removeRdaOption } = useStore();
  const isEdit = !!sel;
  const isPriority = kind === 'priority';
  const headers = { 'Content-Type': 'application/json', 'X-Actor-Persona-Id': (user && user.id) || '' };
  const [form, setForm] = React.useState({ code: '', label: '', sortOrder: 0, leadDays: '', active: true });
  const [saving, setSaving] = React.useState(false);
  const [err, setErr] = React.useState(null);

  React.useEffect(() => {
    setForm({
      code: sel ? sel.code : '',
      label: sel ? sel.label : '',
      sortOrder: sel ? (sel.sortOrder || 0) : 0,
      leadDays: sel && sel.meta && sel.meta.leadDays != null ? sel.meta.leadDays : '',
      active: sel ? sel.active !== false : true,
    });
    setErr(null);
  }, [sel]);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const codeValid = /^[A-Za-z0-9_-]{1,64}$/.test(form.code);
  const valid = form.label.trim() && codeValid;

  const submit = async () => {
    if (!valid || saving) return;
    setSaving(true); setErr(null);
    try {
      const meta = isPriority && form.leadDays !== '' ? { leadDays: Number(form.leadDays) } : {};
      let res;
      if (isEdit) {
        res = await fetch(`/api/config/rda-options/${encodeURIComponent(sel.id)}`, {
          method: 'PATCH', headers,
          body: JSON.stringify({ label: form.label.trim(), sortOrder: Number(form.sortOrder) || 0, meta, active: !!form.active, code: form.code }),
        });
      } else {
        res = await fetch('/api/config/rda-options', {
          method: 'POST', headers,
          body: JSON.stringify({ kind, code: form.code, label: form.label.trim(), sortOrder: Number(form.sortOrder) || 0, meta, active: !!form.active }),
        });
      }
      const j = await res.json().catch(() => ({}));
      if (!res.ok) { setErr(j.detail || j.error || `HTTP ${res.status}`); return; }
      addRdaOption(j.data);
      pushToast({ title: isEdit ? 'Opzione aggiornata' : 'Opzione aggiunta', desc: `${j.data.code} · ${j.data.label}`, tone: 'ok' });
      onSaved && onSaved();
      onClose();
    } catch (e) { setErr(String(e && e.message || e)); }
    finally { setSaving(false); }
  };

  const doDelete = async () => {
    if (!isEdit || saving) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/config/rda-options/${encodeURIComponent(sel.id)}`, { method: 'DELETE', headers });
      if (!res.ok) { const j = await res.json().catch(() => ({})); setErr(j.error || `HTTP ${res.status}`); return; }
      removeRdaOption(sel.id);
      pushToast({ title: 'Opzione eliminata', tone: 'warn' });
      onSaved && onSaved();
      onClose();
    } catch (e) { setErr(String(e && e.message || e)); }
    finally { setSaving(false); }
  };

  const tab = RDA_OPTION_KIND_TABS.find((t) => t.kind === kind);
  return (
    <Modal open onClose={onClose} size="sm" title={`${isEdit ? 'Modifica' : 'Nuova'} opzione · ${tab ? tab.label : kind}`}
      footer={<>
        {isEdit && <Btn variant="ghost" size="sm" onClick={doDelete} disabled={saving} style={{ marginRight: 'auto', color: 'var(--err, #c0392b)' }}><Icon name="trash" size={11} /> Elimina</Btn>}
        <Btn variant="ghost" size="sm" onClick={onClose} disabled={saving}>Annulla</Btn>
        <Btn variant="primary" size="sm" onClick={submit} disabled={!valid || saving}>{saving ? 'Salvataggio…' : 'Salva'}</Btn>
      </>}>
      <div className="col" style={{ gap: 12 }}>
        <div className="grid grid-2" style={{ gap: 10 }}>
          <div className="field"><label>Code <span style={{ color: 'var(--err)' }}>*</span></label>
            <input value={form.code} onChange={(e) => set('code', e.target.value.toUpperCase().replace(/[^A-Z0-9_-]/g, ''))} placeholder="ES_CODE" style={{ fontFamily: 'var(--font-mono)' }} />
          </div>
          <div className="field"><label>Ordine</label>
            <input type="number" value={form.sortOrder} onChange={(e) => set('sortOrder', e.target.value)} />
          </div>
        </div>
        <div className="field"><label>Etichetta <span style={{ color: 'var(--err)' }}>*</span></label>
          <input value={form.label} onChange={(e) => set('label', e.target.value)} placeholder="es. Bando 2" />
        </div>
        {isPriority && (
          <div className="field"><label>Lead-time (giorni)</label>
            <input type="number" min="0" value={form.leadDays} onChange={(e) => set('leadDays', e.target.value)} placeholder="es. 30" />
            <div style={{ fontSize: 10.5, color: 'var(--text-3)', marginTop: 4 }}>Giorni target per lo SLA della RdA con questa priorità.</div>
          </div>
        )}
        <label className="row" style={{ gap: 6, fontSize: 11.5 }}>
          <input type="checkbox" checked={!!form.active} onChange={(e) => set('active', e.target.checked)} /> Attiva
        </label>
        {form.code && !codeValid && <div style={{ fontSize: 10.5, color: 'var(--err)' }}><Icon name="warning_tri" size={10} /> Code: A-Z/0-9/_/- (max 64)</div>}
        {err && <div style={{ fontSize: 11, color: 'var(--err)', padding: '8px 10px', background: 'rgba(239,68,68,0.06)', border: '1px solid var(--err)', borderRadius: 4 }}><Icon name="warning_tri" size={10} /> {err}</div>}
      </div>
    </Modal>
  );
};

window.CustRdaOptions = function CustRdaOptions() {
  const { seedCustom, extras, user } = useStore();
  const canWrite = typeof window !== 'undefined' && window.can ? window.can('config.update', user, seedCustom) : true;
  const [activeKind, setActiveKind] = React.useState('bando');
  const [sel, setSel] = React.useState(null);   // opzione in modifica
  const [showNew, setShowNew] = React.useState(false);

  // Lista per kind (merge seed+extras, incl. inattive, escluse cancellate). Pattern dedup-extras-seed.
  const list = React.useMemo(() => {
    const seed = (seedCustom && seedCustom.RDA_OPTIONS) || [];
    const ext = (extras && extras.rdaOptionsExt) || [];
    const deleted = new Set((extras && extras.rdaOptionsDeleted) || []);
    const seen = new Set();
    const out = [];
    for (const o of [...ext, ...seed]) {
      if (!o || !o.id || seen.has(o.id) || deleted.has(o.id)) continue;
      seen.add(o.id);
      if (o.kind === activeKind) out.push(o);
    }
    out.sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0) || String(a.label).localeCompare(String(b.label)));
    return out;
  }, [seedCustom, extras, activeKind]);

  const tab = RDA_OPTION_KIND_TABS.find((t) => t.kind === activeKind);
  const isPriority = activeKind === 'priority';

  return (
    <div className="card">
      <div className="card-header">
        <div className="title"><Icon name="receipt" size={13} /> Modulo RdA — opzioni configurabili</div>
        <div className="desc">Liste del modulo Richiesta di Acquisto. White-label: valgono solo per questo tenant.</div>
      </div>

      {/* segmented sub-tabs per kind */}
      <div style={{ display: 'flex', gap: 6, padding: '12px 14px 0', flexWrap: 'wrap' }}>
        {RDA_OPTION_KIND_TABS.map((t) => {
          const on = activeKind === t.kind;
          return (
            <button key={t.kind} onClick={() => setActiveKind(t.kind)}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: on ? 600 : 500,
                padding: '7px 14px', borderRadius: 8, cursor: 'pointer',
                border: '1px solid ' + (on ? 'var(--accent)' : 'var(--line)'),
                background: on ? 'var(--accent-soft, rgba(59,130,246,0.10))' : 'var(--bg-2)',
                color: on ? 'var(--accent)' : 'var(--text-2)',
              }}>
              <Icon name={t.icon} size={12} /> {t.label}
            </button>
          );
        })}
      </div>

      <div className="card-body" style={{ paddingTop: 12 }}>
        <div className="row" style={{ gap: 8, marginBottom: 10, alignItems: 'center' }}>
          <Chip>{list.length} {tab ? tab.label.toLowerCase() : ''}</Chip>
          <span style={{ fontSize: 11, color: 'var(--text-3)', flex: 1 }}>{tab && tab.hint}</span>
          {canWrite && <Btn variant="primary" size="sm" onClick={() => setShowNew(true)}><Icon name="plus" size={11} /> Nuova opzione</Btn>}
        </div>

        {list.length === 0 ? (
          <div style={{ padding: '24px 12px', textAlign: 'center', color: 'var(--text-3)', fontSize: 12, border: '1px dashed var(--line)', borderRadius: 8 }}>
            Nessuna opzione per «{tab && tab.label}». {canWrite ? 'Clicca "Nuova opzione" per aggiungerne.' : ''}
          </div>
        ) : (
          <table className="tbl dense">
            <thead><tr>
              <th style={{ width: 60, textAlign: 'right' }}>Ord.</th>
              <th style={{ width: 170 }}>Code</th>
              <th>Etichetta</th>
              {isPriority && <th style={{ width: 110, textAlign: 'right' }}>Lead-time</th>}
              <th style={{ width: 70, textAlign: 'center' }}>Stato</th>
            </tr></thead>
            <tbody>
              {list.map((o) => (
                <tr key={o.id} className={canWrite ? 'clickable' : ''} onClick={() => { if (canWrite) setSel(o); }} style={{ opacity: o.active === false ? 0.5 : 1 }}>
                  <td className="num mono" style={{ textAlign: 'right', color: 'var(--text-3)' }}>{o.sortOrder || 0}</td>
                  <td className="mono" style={{ fontSize: 10.5 }}>{o.code}</td>
                  <td style={{ fontWeight: 500 }}>{o.label}</td>
                  {isPriority && <td className="num mono" style={{ textAlign: 'right' }}>{o.meta && o.meta.leadDays != null ? `${o.meta.leadDays} gg` : '—'}</td>}
                  <td style={{ textAlign: 'center' }}><Chip kind={o.active === false ? '' : 'ok'} dot>{o.active === false ? 'off' : 'on'}</Chip></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}

        <div style={{ fontSize: 10.5, color: 'var(--text-3)', marginTop: 12, lineHeight: 1.5 }}>
          <Icon name="info" size={10} /> <code>/api/config/rda-options</code> · audit log automatico · scoped al tenant. Il <strong>code</strong> è referenziato dalle RdA.
        </div>
      </div>

      {showNew && <window.RdaOptionModal kind={activeKind} sel={null} onClose={() => setShowNew(false)} />}
      {sel && <window.RdaOptionModal kind={activeKind} sel={sel} onClose={() => setSel(null)} />}
    </div>
  );
};
