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

export function useSubtaskCompletion() {
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const markSubtaskComplete = useCallback(async (taskId, isComplete) => {
    try {
      setLoading(true);
      const updates = {
        status: isComplete ? 'completed' : 'pending',
        completed_at: isComplete ? new Date().toISOString() : null
      };

      const { error } = await supabase
        .from('tasks')
        .update(updates)
        .eq('id', taskId);

      if (error) throw error;
      
      return true;
    } catch (error) {
      console.error('[useSubtaskCompletion] Error updating subtask:', error);
      toast({ variant: "destructive", title: "Error", description: error.message });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const markAllSubtasksComplete = useCallback(async (parentTaskId) => {
    try {
        setLoading(true);
        const { error } = await supabase
            .from('tasks')
            .update({ 
                status: 'completed', 
                completed_at: new Date().toISOString() 
            })
            .eq('parent_task_id', parentTaskId);

        if (error) throw error;
        
        toast({ title: "Success", description: "All tasks marked as complete." });
        return true;
    } catch (error) {
        console.error('[useSubtaskCompletion] Error completing all tasks:', error);
        toast({ variant: "destructive", title: "Error", description: error.message });
        return false;
    } finally {
        setLoading(false);
    }
  }, [toast]);

  return {
    loading,
    markSubtaskComplete,
    markAllSubtasksComplete
  };
}
