import { useState } from 'react';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Codex';
import type { DirectorAction } from '@/lib/assistant/director';
import { actionSummary } from './actionSummary';
import type { ApplyResult } from './useDirectorAction';

/**
 * A proposed state change. Approve-each: it only mutates the game when the human
 * clicks Apply, which routes through the rules kernel. If no `onApply` is given it
 * renders as a passive preview.
 */
export function ActionCard({
  action,
  onApply,
}: {
  action: DirectorAction;
  onApply?: (a: DirectorAction) => Promise<ApplyResult>;
}) {
  const [busy, setBusy] = useState(false);
  const [result, setResult] = useState<ApplyResult | null>(null);

  const apply = async () => {
    if (!onApply) return;
    setBusy(true);
    try {
      setResult(await onApply(action));
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="rounded-md border border-line bg-panel/60 p-2 text-sm">
      <div className="flex items-center gap-2">
        <Badge tone={result ? (result.ok ? 'success' : 'ember') : 'arcane'}>
          {result ? (result.ok ? 'applied' : 'skipped') : 'change'}
        </Badge>
        <span className="min-w-0 flex-1 truncate text-muted">{actionSummary(action)}</span>
        {onApply && !result && (
          <Button size="sm" disabled={busy} onClick={apply}>
            {busy ? '…' : 'Apply'}
          </Button>
        )}
      </div>
      {result && !result.ok && <p className="mt-1 pl-1 text-xs text-danger">{result.message}</p>}
    </div>
  );
}
