'use client';

import { useRouter } from 'next/navigation';
import { useMutation } from 'convex/react';
import {
  ExternalLink,
  GitPullRequestDraft,
  Square,
  Trash2,
} from 'lucide-react';
import { toast } from 'sonner';

import type { Doc } from '@spoon/backend/convex/_generated/dataModel.js';
import { api } from '@spoon/backend/convex/_generated/api.js';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
  Button,
} from '@spoon/ui';

export const WorkspaceActions = ({
  job,
  disabled,
}: {
  job: Doc<'agentJobs'>;
  disabled: boolean;
}) => {
  const router = useRouter();
  const deleteWorkspace = useMutation(api.agentJobs.deleteWorkspace);
  const deleteThread = useMutation(api.threads.deleteThread);
  const canDelete =
    ['failed', 'cancelled', 'timed_out'].includes(job.status) ||
    ['stopped', 'expired', 'failed'].includes(job.workspaceStatus ?? '');

  const openPr = async () => {
    try {
      const response = await fetch(`/api/agent-jobs/${job._id}/open-pr`, {
        method: 'POST',
      });
      if (!response.ok) throw new Error(await response.text());
      toast.success('Draft PR opened.');
    } catch (error) {
      console.error(error);
      toast.error('Could not open draft PR.');
    }
  };

  const remove = async () => {
    try {
      await deleteWorkspace({ jobId: job._id });
      toast.success('Workspace deleted.');
      router.push(`/spoons/${job.spoonId}`);
    } catch (error) {
      console.error(error);
      toast.error('Could not delete workspace.');
    }
  };

  const removeThread = async () => {
    if (!job.threadId) return;
    try {
      await deleteThread({ threadId: job.threadId });
      toast.success('Thread deleted.');
      router.push('/threads');
    } catch (error) {
      console.error(error);
      toast.error(
        error instanceof Error ? error.message : 'Could not delete thread.',
      );
    }
  };

  const stop = async () => {
    try {
      const response = await fetch(`/api/agent-jobs/${job._id}/stop`, {
        method: 'POST',
      });
      if (!response.ok) throw new Error(await response.text());
      toast.success('Workspace stopped.');
    } catch (error) {
      console.error(error);
      toast.error('Could not stop workspace.');
    }
  };

  return (
    <div className='flex flex-wrap items-center gap-2'>
      {job.pullRequestUrl ? (
        <Button asChild variant='outline' size='sm'>
          <a href={job.pullRequestUrl} target='_blank' rel='noreferrer'>
            <ExternalLink className='size-4' />
            Open PR
          </a>
        </Button>
      ) : null}
      <Button type='button' size='sm' disabled={disabled} onClick={openPr}>
        <GitPullRequestDraft className='size-4' />
        Open draft PR
      </Button>
      <Button
        type='button'
        variant='outline'
        size='sm'
        disabled={disabled}
        onClick={stop}
      >
        <Square className='size-4' />
        Stop
      </Button>
      {canDelete ? (
        <>
          {job.threadId ? (
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button type='button' variant='destructive' size='sm'>
                  <Trash2 className='size-4' />
                  Delete thread
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Delete this thread?</AlertDialogTitle>
                  <AlertDialogDescription>
                    This removes the thread and any terminal workspace records,
                    messages, events, artifacts, diffs, and UI state attached to
                    it. This cannot be undone.
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Keep thread</AlertDialogCancel>
                  <AlertDialogAction
                    variant='destructive'
                    onClick={() => void removeThread()}
                  >
                    Delete thread
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          ) : null}
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button type='button' variant='outline' size='sm'>
                <Trash2 className='size-4' />
                Delete workspace
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>Delete this workspace?</AlertDialogTitle>
                <AlertDialogDescription>
                  This removes the workspace record, messages, events,
                  artifacts, diffs, and UI state. The thread is kept unless you
                  delete it separately.
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>Keep workspace</AlertDialogCancel>
                <AlertDialogAction
                  variant='destructive'
                  onClick={() => void remove()}
                >
                  Delete workspace
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </>
      ) : null}
    </div>
  );
};
