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

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

  const fetchMeeting = useCallback(async (associationId) => {
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from('calendar_events')
        .select('*')
        .eq('association_id', associationId)
        .eq('event_type', 'budget_meeting')
        .maybeSingle();
      if (error) throw error;
      return data;
    } catch (error) {
      console.error('Error fetching budget meeting:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to fetch meeting details.' });
      return null;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const saveMeeting = useCallback(async (associationId, meetingData) => {
    try {
      setLoading(true);
      const { data: userData } = await supabase.auth.getUser();
      
      const payload = {
        ...meetingData,
        association_id: associationId,
        event_type: 'budget_meeting',
        updated_at: new Date().toISOString(),
      };

      const { data: existing } = await supabase
        .from('calendar_events')
        .select('id')
        .eq('association_id', associationId)
        .eq('event_type', 'budget_meeting')
        .maybeSingle();

      let error, result;

      if (existing) {
        const { data, error: updateError } = await supabase
          .from('calendar_events')
          .update(payload)
          .eq('id', existing.id)
          .select()
          .single();
        error = updateError;
        result = data;
      } else {
        const { data, error: insertError } = await supabase
          .from('calendar_events')
          .insert([{ ...payload, created_by: userData?.user?.id }])
          .select()
          .single();
        error = insertError;
        result = data;
      }

      if (error) throw error;
      toast({ title: 'Success', description: 'Budget meeting saved successfully.' });
      return result;
    } catch (error) {
      console.error('Error saving budget meeting:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to save meeting.' });
      return null;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const deleteMeeting = useCallback(async (associationId) => {
    try {
      setLoading(true);
      const { error } = await supabase
        .from('calendar_events')
        .delete()
        .eq('association_id', associationId)
        .eq('event_type', 'budget_meeting');
      if (error) throw error;
      toast({ title: 'Success', description: 'Budget meeting deleted.' });
      return true;
    } catch (error) {
      console.error('Error deleting budget meeting:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to delete meeting.' });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  return {
    loading,
    fetchMeeting,
    saveMeeting,
    deleteMeeting
  };
}
