/* =========================================================
   Actions — human approval inbox (Phase G)
   =========================================================
   The queue of actions awaiting a human: customer-facing / money /
   regulated items the agent filed but must NOT auto-fire. Uses the
   EXISTING endpoints:
     GET  /calls/actions/pending            (the "TENANT ACTIONS INBOX")
     POST /calls/actions/{id}/approve       body { approved: bool }

   Each card shows the decision + the cost/recipients on the button, and
   only acts on one tap. Reversible internal actions never appear here.

   VERIFICATION STATUS: matches tenant.jsx/admin-ops.jsx conventions
   (apiRequest, card/CSS-var styling, hooks) but NOT browser-verified.
   Confirm the ActionApproval body shape ({approved}) against
   models/schemas.py before relying on the approve call. Needs jsx-loader
   + root.jsx route registration to go live.
   ========================================================= */

const _payloadSummary = (a) => {
  const p = (a && a.request_payload) || {};
  if (p.subject) return p.subject;
  if (p.to) return `To ${Array.isArray(p.to) ? p.to.join(", ") : p.to}`;
  return a.action_type || "Action";
};

const ApprovalCard = ({ action, onApprove, onReject, busy }) => {
  const p = (action && action.request_payload) || {};
  const cost = p.est_cost_kes != null ? ` · KES ${p.est_cost_kes}` : "";
  return (
    <div className="card card-pad" style={{ borderLeft: "3px solid var(--mk-info, #185FA5)", marginBottom: 12 }}>
      <div className="row between" style={{ marginBottom: 6 }}>
        <div style={{ fontSize: 12, color: "var(--fg-muted)", textTransform: "uppercase", letterSpacing: ".06em" }}>
          {action.action_type || "action"}{action.urgency_tier ? ` · ${action.urgency_tier}` : ""}
        </div>
        <div style={{ fontSize: 12, color: "var(--fg-faint)" }}>{action.created_at ? new Date(action.created_at).toLocaleString() : ""}</div>
      </div>
      <div style={{ fontSize: 15, fontWeight: 500, marginBottom: 6 }}>{_payloadSummary(action)}</div>
      {p.body && <div style={{ fontSize: 13, color: "var(--fg-muted)", marginBottom: 10, whiteSpace: "pre-wrap" }}>{String(p.body).slice(0, 280)}</div>}
      <div className="row" style={{ gap: 8 }}>
        <button className="btn btn-primary" disabled={busy} onClick={() => onApprove(action)}>
          Approve{cost}
        </button>
        <button className="btn" disabled={busy} onClick={() => onReject(action)}>Dismiss</button>
      </div>
    </div>
  );
};

const ApprovalInbox = ({ onGo }) => {
  const [rows, setRows] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [busyId, setBusyId] = React.useState(null);
  const [err, setErr] = React.useState(null);

  const load = React.useCallback(async () => {
    try {
      const a = await apiRequest("/calls/actions/pending");
      setRows(Array.isArray(a) ? a : []);
    } catch (e) {
      setErr(String((e && e.message) || e));
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => { load(); }, [load]);

  const decide = async (action, approved) => {
    setBusyId(action.id);
    try {
      await apiRequest(`/calls/actions/${action.id}/approve`, {
        method: "POST",
        body: JSON.stringify({ approved }),
      });
      setRows((rs) => rs.filter((r) => r.id !== action.id));
    } catch (e) {
      setErr(String((e && e.message) || e));
    } finally {
      setBusyId(null);
    }
  };

  if (loading) return <div className="card card-pad">Loading approvals…</div>;

  return (
    <div className="stack" style={{ gap: 16 }}>
      <div className="row between">
        <h2 style={{ margin: 0 }}>Actions</h2>
        <div style={{ fontSize: 13, color: "var(--fg-muted)" }}>{rows.length} waiting for you</div>
      </div>
      {err && <div className="card card-pad" style={{ color: "var(--mk-danger)" }}>{err}</div>}
      {rows.length === 0 ? (
        <div className="card card-pad" style={{ color: "var(--fg-muted)" }}>
          Nothing needs you right now. Routine internal actions are handled automatically and shown in Operations.
        </div>
      ) : (
        rows.map((a) => (
          <ApprovalCard
            key={a.id}
            action={a}
            busy={busyId === a.id}
            onApprove={(x) => decide(x, true)}
            onReject={(x) => decide(x, false)}
          />
        ))
      )}
    </div>
  );
};
