import { useEffect } from "react";

export interface McpConfirmSpec {
  tool: string;
  args: unknown;
  reason: string | null;
  /** Human-readable summary of what's about to happen, computed by the
   *  per-tool handler (e.g. "rename pane 'shell' to 'build'"). */
  summary: string;
}

interface McpConfirmProps {
  spec: McpConfirmSpec;
  onAccept: () => void;
  onReject: () => void;
  /** Approve this call AND add the bare tool name to the policy allow list
   *  so future calls of this tool skip the prompt. */
  onAlwaysAllow: () => void | Promise<void>;
}

export default function McpConfirm({ spec, onAccept, onReject, onAlwaysAllow }: McpConfirmProps) {
  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") {
        e.preventDefault();
        onReject();
      } else if (e.key === "Enter") {
        e.preventDefault();
        onAccept();
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onAccept, onReject]);

  const argsJson = JSON.stringify(spec.args, null, 2);

  return (
    <>
      <button
        className="backdrop"
        onClick={onReject}
        aria-label="Reject MCP action"
      />
      <div className="mcp-confirm" role="dialog" aria-label="MCP action confirm">
        <header className="mcp-confirm-header">
          <span className="mcp-confirm-title">
            MCP wants to run <code>{spec.tool}</code>
          </span>
        </header>
        <div className="mcp-confirm-body">
          <p className="mcp-confirm-summary">{spec.summary}</p>
          {spec.reason && (
            <p className="mcp-confirm-reason">
              Policy decision: <em>{spec.reason}</em>
            </p>
          )}
          <details className="mcp-confirm-args">
            <summary>Raw arguments</summary>
            <pre>{argsJson}</pre>
          </details>
        </div>
        <footer className="mcp-confirm-actions">
          <button className="mcp-confirm-reject" onClick={onReject}>
            Reject (Esc)
          </button>
          <button
            className="mcp-confirm-always"
            onClick={() => { void onAlwaysAllow(); }}
            title={`Add "${spec.tool}" to the policy allow list — future calls of this tool won't prompt`}
          >
            Always allow {spec.tool}
          </button>
          <button className="mcp-confirm-accept" onClick={onAccept} autoFocus>
            Approve (Enter)
          </button>
        </footer>
      </div>
    </>
  );
}
