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

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

  const fetchMeeting = useCallback(async (clientId) => {
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from('annual_meetings')
        .select('*')
        .eq('client_id', clientId)
        .maybeSingle(); 

      if (error) throw error;
      return data;
    } catch (error) {
      console.error('Error fetching annual meeting:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to fetch meeting details.' });
      return null;
    } finally {
      setLoading(false);
    }
  }, [toast]);

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

      const { data: existing } = await supabase
        .from('annual_meetings')
        .select('id')
        .eq('client_id', clientId)
        .maybeSingle();

      let error;
      let result;

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

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

  const deleteMeeting = useCallback(async (clientId) => {
    try {
      setLoading(true);
      const { error } = await supabase
        .from('annual_meetings')
        .delete()
        .eq('client_id', clientId);

      if (error) throw error;
      toast({ title: 'Success', description: 'Annual meeting deleted.' });
      return true;
    } catch (error) {
      console.error('Error deleting annual meeting:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to delete meeting.' });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const fetchChecklists = useCallback(async (meetingId) => {
    try {
      const { data, error } = await supabase
        .from('meeting_checklists')
        .select('*')
        .eq('meeting_id', meetingId)
        .eq('meeting_type', 'annual')
        .order('order_index', { ascending: true });

      if (error) throw error;
      return data || [];
    } catch (error) {
      console.error('Error fetching checklists:', error);
      return [];
    }
  }, []);

  const saveChecklist = useCallback(async (meetingId, clientId, checklistData) => {
    try {
      const payload = {
        ...checklistData,
        meeting_id: meetingId,
        client_id: clientId,
        meeting_type: 'annual',
        updated_at: new Date().toISOString()
      };

      if (checklistData.id) {
         const { data, error } = await supabase
            .from('meeting_checklists')
            .update(payload)
            .eq('id', checklistData.id)
            .select()
            .single();
         if (error) throw error;
         return data;
      } else {
         const { data, error } = await supabase
            .from('meeting_checklists')
            .insert([payload])
            .select()
            .single();
         if (error) throw error;
         return data;
      }
    } catch (error) {
      console.error('Error saving checklist:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to save checklist item.' });
      throw error;
    }
  }, [toast]);

  const deleteChecklist = useCallback(async (id) => {
    try {
      const { error } = await supabase
        .from('meeting_checklists')
        .delete()
        .eq('id', id);
      
      if (error) throw error;
      return true;
    } catch (error) {
      console.error('Error deleting checklist:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to delete checklist item.' });
      return false;
    }
  }, [toast]);

  const updateChecklistOrder = useCallback(async (items) => {
    try {
      const updates = items.map((item, index) => ({
        id: item.id,
        order_index: index,
        updated_at: new Date().toISOString()
      }));

      const { error } = await supabase
        .from('meeting_checklists')
        .upsert(updates);

      if (error) throw error;
    } catch (error) {
      console.error('Error reordering checklists:', error);
    }
  }, []);

  return {
    loading,
    fetchMeeting,
    saveMeeting,
    deleteMeeting,
    fetchChecklists,
    saveChecklist,
    deleteChecklist,
    updateChecklistOrder
  };
}
