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

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

  const fetchChecklists = useCallback(async (filters = {}) => {
    try {
      setLoading(true);
      let query = supabase
        .from('checklists')
        .select('*')
        .order('updated_at', { ascending: false });

      if (filters.status) query = query.eq('status', filters.status);
      if (filters.associationId) query = query.eq('association_id', filters.associationId);

      const { data, error } = await query;
      if (error) throw error;
      return data || [];
    } catch (error) {
      console.error('Error fetching checklists:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to load checklists.' });
      return [];
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const updateChecklist = async (id, updates) => {
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from('checklists')
        .update({ ...updates, updated_at: new Date().toISOString() })
        .eq('id', id)
        .select()
        .single();
      if (error) throw error;
      return data;
    } catch (err) {
      console.error('Save failed:', err);
      toast({ variant: 'destructive', title: 'Save Failed', description: 'Could not save changes.' });
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const createChecklist = async (payload) => {
    try {
      setLoading(true);
      const { data, error } = await supabase.from('checklists').insert(payload).select().single();
      if (error) throw error;
      return data;
    } catch (error) {
      console.error('Creation failed:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Could not create checklist.' });
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const deleteChecklist = async (id) => {
    try {
      setLoading(true);
      const { error } = await supabase.from('checklists').delete().eq('id', id);
      if (error) throw error;
    } catch (error) {
      console.error('Delete failed:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Could not delete checklist.' });
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return { loading, fetchChecklists, updateChecklist, createChecklist, deleteChecklist };
}
