import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { fetchToolRequests, decideToolRequest } from '../../api';

/**
 * Inline approval card shown in the chat when the agent is paused waiting for
 * the user to approve/deny a tool it requested (RequestTool). Polls the task's
 * tool requests while enabled and renders an approve/deny pair per pending row.
 * Deciding re-queues the paused job, so the chat resumes on its own.
 */
export function ToolRequestApproval({ taskId, poll }: { taskId: number; poll: boolean }) {
  const { t } = useTranslation('chat');
  const qc = useQueryClient();

  // Always fetch once when a task is open (so a pending approval card shows
  // immediately on load); poll only while the job is active/paused.
  const { data: requests = [] } = useQuery({
    queryKey: ['tool-requests', taskId],
    queryFn: () => fetchToolRequests(taskId),
    refetchInterval: poll ? 3000 : false,
  });

  const decide = useMutation({
    mutationFn: ({ reqId, decision }: { reqId: string; decision: 'approve' | 'deny' }) =>
      decideToolRequest(taskId, reqId, decision),
    onSuccess: () => {
      // Refresh the request list (card disappears) and the task/job state so
      // ChatPane's jobStatus flips off waiting_human immediately — otherwise the
      // resume + stream reconnect lag until the next poll. Keys must match the
      // app's actual query keys (see useTaskDetail / useTaskOperations).
      qc.invalidateQueries({ queryKey: ['tool-requests', taskId] });
      qc.invalidateQueries({ queryKey: ['localTask', taskId] });
      qc.invalidateQueries({ queryKey: ['localTasks'] });
    },
  });

  const pending = requests.filter((r) => r.status === 'pending' && r.category === 'requested');
  if (pending.length === 0) return null;

  return (
    <div className="mb-3 space-y-2" data-testid="tool-request-approval">
      {pending.map((r) => (
        <div
          key={r.id}
          data-testid={`tool-request-${r.toolName}`}
          className="rounded-lg border border-amber-300 bg-amber-50 p-3 text-sm dark:border-amber-700/60 dark:bg-amber-900/20"
        >
          <div className="font-medium text-amber-900 dark:text-amber-200">
            {t('toolRequest.title', { tool: r.toolName })}
          </div>
          {r.reason && (
            <div className="mt-1 text-amber-800/90 dark:text-amber-200/80">
              {t('toolRequest.reason')}: {r.reason}
            </div>
          )}
          <div className="mt-0.5 text-xs text-amber-700/70 dark:text-amber-300/60">movement: {r.movementName}</div>
          {decide.isError && (
            <div className="mt-1 text-xs text-red-700 dark:text-red-300" data-testid="tool-request-error">
              {t('toolRequest.failed')}: {(decide.error as Error)?.message ?? ''}
            </div>
          )}
          <div className="mt-2 flex gap-2">
            <button
              type="button"
              data-testid={`tool-request-approve-${r.toolName}`}
              disabled={decide.isPending}
              onClick={() => decide.mutate({ reqId: r.id, decision: 'approve' })}
              className="rounded-md bg-emerald-600 px-3 py-1 text-xs font-medium text-white hover:bg-emerald-700 disabled:opacity-50"
            >
              {t('toolRequest.approve')}
            </button>
            <button
              type="button"
              data-testid={`tool-request-deny-${r.toolName}`}
              disabled={decide.isPending}
              onClick={() => decide.mutate({ reqId: r.id, decision: 'deny' })}
              className="rounded-md border border-stone-300 bg-white px-3 py-1 text-xs font-medium text-stone-700 hover:bg-stone-50 disabled:opacity-50 dark:border-stone-600 dark:bg-stone-800 dark:text-stone-200 dark:hover:bg-stone-700"
            >
              {t('toolRequest.deny')}
            </button>
          </div>
        </div>
      ))}
    </div>
  );
}
