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

/**
 * Inline approval card shown in the chat when the agent is paused waiting for a
 * user to approve/deny a Python package it requested (RequestPackage). Approving
 * installs the wheel into this workspace's overlay and resumes the paused job,
 * so the chat continues on its own. Mirrors ToolRequestApproval.
 */
export function PackageRequestApproval({ taskId, poll }: { taskId: number; poll: boolean }) {
  const { t } = useTranslation('chat');
  const qc = useQueryClient();

  const { data: requests = [] } = useQuery({
    queryKey: ['package-requests', taskId],
    queryFn: () => fetchPackageRequests(taskId),
    refetchInterval: poll ? 3000 : false,
  });

  const decide = useMutation({
    mutationFn: ({ reqId, decision }: { reqId: string; decision: 'approve' | 'deny' }) =>
      decidePackageRequest(taskId, reqId, decision),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['package-requests', taskId] });
      qc.invalidateQueries({ queryKey: ['localTask', taskId] });
      qc.invalidateQueries({ queryKey: ['localTasks'] });
    },
  });

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

  return (
    <div className="mb-3 space-y-2" data-testid="package-request-approval">
      {pending.map((r) => (
        <div
          key={r.id}
          data-testid={`package-request-${r.normalizedName}`}
          className="rounded-lg border border-sky-300 bg-sky-50 p-3 text-sm dark:border-sky-700/60 dark:bg-sky-900/20"
        >
          <div className="font-medium text-sky-900 dark:text-sky-200">
            {t('packageRequest.title', { spec: r.spec })}
          </div>
          {r.reason && (
            <div className="mt-1 text-sky-800/90 dark:text-sky-200/80">
              {t('packageRequest.reason')}: {r.reason}
            </div>
          )}
          <div className="mt-1 text-xs text-sky-700/70 dark:text-sky-300/60">{t('packageRequest.note')}</div>
          {decide.isError && (
            <div className="mt-1 text-xs text-red-700 dark:text-red-300" data-testid="package-request-error">
              {t('packageRequest.failed')}: {(decide.error as Error)?.message ?? ''}
            </div>
          )}
          <div className="mt-2 flex gap-2">
            <button
              type="button"
              data-testid={`package-request-approve-${r.normalizedName}`}
              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('packageRequest.approve')}
            </button>
            <button
              type="button"
              data-testid={`package-request-deny-${r.normalizedName}`}
              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('packageRequest.deny')}
            </button>
          </div>
        </div>
      ))}
    </div>
  );
}
