'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useMutation } from 'convex/react';
import { Trash2 } from 'lucide-react';
import { toast } from 'sonner';

import type { Id } 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 DeleteThreadButton = ({
  threadId,
  disabled,
  redirectTo,
  onDeleted,
  label = 'Delete',
  size = 'sm',
  variant = 'destructive',
}: {
  threadId: Id<'threads'>;
  disabled?: boolean;
  redirectTo?: string;
  onDeleted?: () => void;
  label?: string;
  size?: 'sm' | 'default';
  variant?: 'destructive' | 'outline';
}) => {
  const router = useRouter();
  const deleteThread = useMutation(api.threads.deleteThread);
  const [deleting, setDeleting] = useState(false);

  const remove = async () => {
    setDeleting(true);
    try {
      await deleteThread({ threadId });
      toast.success('Thread deleted.');
      onDeleted?.();
      if (redirectTo) router.push(redirectTo);
    } catch (error) {
      console.error(error);
      toast.error(
        error instanceof Error ? error.message : 'Could not delete thread.',
      );
    } finally {
      setDeleting(false);
    }
  };

  return (
    <AlertDialog>
      <AlertDialogTrigger asChild>
        <Button
          type='button'
          size={size}
          variant={variant}
          disabled={(disabled ?? false) || deleting}
          onClick={(event) => event.stopPropagation()}
        >
          <Trash2 className='size-4' />
          {deleting ? 'Deleting...' : label}
        </Button>
      </AlertDialogTrigger>
      <AlertDialogContent onClick={(event) => event.stopPropagation()}>
        <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'
            disabled={deleting}
            onClick={() => void remove()}
          >
            Delete thread
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
};
