import { router } from '@inertiajs/react';
import { useState } from 'react';
import { toast } from 'sonner';

import { ConfirmDeleteDialog } from '@/components/ConfirmDeleteDialog';
import { destroy as destroyRecurringTask } from '@/routes/recurring-tasks';

interface RecurringTask {
    id: number;
    title: string;
}

interface DeleteRecurringTaskDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    task: RecurringTask | null;
}

export function DeleteRecurringTaskDialog({
    open,
    onOpenChange,
    task,
}: DeleteRecurringTaskDialogProps) {
    const [processing, setProcessing] = useState(false);

    const handleDelete = () => {
        if (!task) {
            return;
        }

        setProcessing(true);
        router.delete(destroyRecurringTask(task.id).url, {
            onSuccess: () => {
                setProcessing(false);
                toast.success('Automation deleted successfully');
                onOpenChange(false);
            },
            onError: () => {
                setProcessing(false);
                toast.error('Failed to delete automation');
            },
        });
    };

    return (
        <ConfirmDeleteDialog
            open={open}
            onOpenChange={onOpenChange}
            onConfirm={handleDelete}
            processing={processing}
            title="Delete Automation?"
            description={
                <>
                    Are you sure you want to delete{' '}
                    <span className="font-bold text-foreground">
                        "{task?.title}"
                    </span>
                    ? This action will stop all future task generation for this
                    schedule.
                </>
            }
            confirmLabel="Delete Automation"
            cancelLabel="Keep Automation"
        />
    );
}
