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

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

  const fetchAgendas = useCallback(async (associationId) => {
    if (!associationId) return [];
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('calendar_events')
        .select('*')
        .eq('association_id', associationId)
        .eq('event_type', 'meeting')
        .order('updated_at', { ascending: false });

      if (error) throw error;
      return data;
    } catch (error) {
      console.error('Error fetching agendas:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to load saved agendas." });
      return [];
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const loadAgenda = useCallback(async (id) => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('calendar_events')
        .select('*')
        .eq('id', id)
        .single();

      if (error) throw error;
      return data;
    } catch (error) {
      console.error('Error loading agenda:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to load the selected agenda." });
      return null;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const deleteAgenda = useCallback(async (id) => {
    setLoading(true);
    try {
      const { error } = await supabase
        .from('calendar_events')
        .delete()
        .eq('id', id);

      if (error) throw error;
      toast({ title: "Deleted", description: "Agenda deleted successfully." });
      return true;
    } catch (error) {
      console.error('Error deleting agenda:', error);
      toast({ variant: "destructive", title: "Delete Failed", description: error.message });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  return { loading, fetchAgendas, loadAgenda, deleteAgenda };
}
