'use client';

// app/hail/[id]/governance/governance-editor.jsx — inline governance matrix editor.
//
// Edits rows locally; saves the whole matrix via PUT, which re-validates every
// row server-side. The visible rule of thumb: irreversible_external must require
// approval and name a reviewer. Validation errors are surfaced inline.

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import {
  GOVERNANCE_RISK_TIERS,
  AGENT_AUTHORITIES,
  REVIEWER_ROLES,
  SENSITIVITY_CLASSES,
} from '../../../../lib/hail/constants.js';

const BLANK = { action_type: '', risk: 'low', authority: 'draft', role_slug: '', data_class: '', reviewer_role: '', approval_required: false, evidence_required: false };

export default function GovernanceEditor({ engagementId, initialRules }) {
  const router = useRouter();
  const [rules, setRules] = useState(initialRules.length ? initialRules : [{ ...BLANK }]);
  const [busy, setBusy] = useState(false);
  const [errors, setErrors] = useState([]);
  const [saved, setSaved] = useState(false);

  function update(i, patch) {
    setRules((rs) => rs.map((r, j) => (j === i ? { ...r, ...patch } : r)));
    setSaved(false);
  }
  function addRow() { setRules((rs) => [...rs, { ...BLANK }]); }
  function removeRow(i) { setRules((rs) => rs.filter((_, j) => j !== i)); }

  async function save() {
    setBusy(true); setErrors([]); setSaved(false);
    try {
      const payload = rules
        .filter((r) => r.action_type.trim())
        .map((r) => ({
          ...r,
          role_slug: r.role_slug || null,
          data_class: r.data_class || null,
          reviewer_role: r.reviewer_role || null,
        }));
      const res = await fetch(`/api/hail/engagements/${engagementId}/governance`, {
        method: 'PUT',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ rules: payload }),
      });
      const data = await res.json();
      if (!res.ok) { setErrors(data?.errors || [data?.error || 'Save failed.']); return; }
      setRules(data.rules.length ? data.rules : [{ ...BLANK }]);
      setSaved(true);
      router.refresh();
    } catch {
      setErrors(['Network error.']);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="hail-panel">
      <div className="hail-gov-table" role="table">
        <div className="hail-gov-row hail-gov-head" role="row">
          <span>Action</span><span>Risk</span><span>Authority</span><span>Role</span><span>Data class</span><span>Reviewer</span><span>Approval</span><span>Evidence</span><span></span>
        </div>
        {rules.map((r, i) => {
          const irreversible = r.risk === 'irreversible_external';
          const warn = irreversible && (!r.approval_required || !r.reviewer_role || r.authority === 'decide');
          return (
            <div key={i} className={`hail-gov-row ${warn ? 'is-warn' : ''}`} role="row">
              <input value={r.action_type} onChange={(e) => update(i, { action_type: e.target.value })} placeholder="email.send" />
              <select value={r.risk} onChange={(e) => update(i, { risk: e.target.value })}>
                {GOVERNANCE_RISK_TIERS.map((t) => <option key={t} value={t}>{t}</option>)}
              </select>
              <select value={r.authority} onChange={(e) => update(i, { authority: e.target.value })}>
                {AGENT_AUTHORITIES.map((a) => <option key={a} value={a}>{a}</option>)}
              </select>
              <input value={r.role_slug || ''} onChange={(e) => update(i, { role_slug: e.target.value })} placeholder="role" />
              <select value={r.data_class || ''} onChange={(e) => update(i, { data_class: e.target.value })}>
                <option value="">—</option>
                {SENSITIVITY_CLASSES.map((s) => <option key={s} value={s}>{s}</option>)}
              </select>
              <select value={r.reviewer_role || ''} onChange={(e) => update(i, { reviewer_role: e.target.value })}>
                <option value="">—</option>
                {REVIEWER_ROLES.map((rr) => <option key={rr} value={rr}>{rr}</option>)}
              </select>
              <input type="checkbox" checked={!!r.approval_required} onChange={(e) => update(i, { approval_required: e.target.checked })} aria-label="approval required" />
              <input type="checkbox" checked={!!r.evidence_required} onChange={(e) => update(i, { evidence_required: e.target.checked })} aria-label="evidence required" />
              <button type="button" className="hail-btn" onClick={() => removeRow(i)} aria-label="remove">×</button>
            </div>
          );
        })}
      </div>
      <p className="hail-actions">
        <button type="button" className="hail-btn" onClick={addRow}>+ Add rule</button>
        <button type="button" className="hail-btn hail-btn-primary" onClick={save} disabled={busy}>{busy ? 'Saving…' : 'Save matrix'}</button>
        {saved && <span className="hail-badge tone-success">Saved</span>}
      </p>
      <p className="hail-hint">Irreversible-external actions must require approval and name a reviewer, and can never be set to “decide”. Rows that violate this are highlighted and rejected on save.</p>
      {errors.length > 0 && (
        <ul className="hail-error" role="alert">{errors.map((e, i) => <li key={i}>{e}</li>)}</ul>
      )}
    </div>
  );
}
