import { useState, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';

export function useWorkflowDeletion() {
  const [deleting, setDeleting] = useState(false);
  const { toast } = useToast();

  const deleteWorkflow = useCallback(async (workflowId, onSuccess) => {
    if (!workflowId) return;
    
    setDeleting(true);
    try {
      console.log('Deleting workflow instance:', workflowId);

      const { error: subtasksError } = await supabase
        .from('tasks')
        .delete()
        .eq('parent_task_id', workflowId);

      if (subtasksError) {
        console.error('Error deleting subtasks:', subtasksError);
        throw subtasksError;
      }

      const { error: parentError } = await supabase
        .from('tasks')
        .delete()
        .eq('id', workflowId);

      if (parentError) {
        console.error('Error deleting parent workflow task:', parentError);
        throw parentError;
      }

      toast({
        title: "Workflow Deleted",
        description: "The workflow and its tasks have been removed."
      });

      if (onSuccess) {
        onSuccess();
      }

    } catch (error) {
      console.error('Workflow deletion failed:', error);
      toast({
        variant: "destructive",
        title: "Deletion Failed",
        description: error.message || "Could not delete workflow."
      });
    } finally {
      setDeleting(false);
    }
  }, [toast]);

  return {
    deleteWorkflow,
    deleting
  };
}
