import { useState } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { generateRecurrenceDates, RECURRENCE_TYPES } from '@/lib/recurrenceUtils';
import { validateAndParseDate } from '@/lib/utils';
import { v4 as uuidv4 } from 'uuid';

export function useRecurringEvents() {
  const [loading, setLoading] = useState(false);

  const createRecurringEvents = async (baseEventData, recurrenceConfig) => {
    setLoading(true);
    try {
      const validStart = validateAndParseDate(baseEventData.start_time);
      const validEnd = validateAndParseDate(baseEventData.end_time);

      if (!validStart || !validEnd) {
          throw new Error("Invalid start or end date provided for event creation.");
      }
      
      const safeBaseData = {
          ...baseEventData,
          start_time: validStart.toISOString(),
          end_time: validEnd.toISOString()
      };

      if (!recurrenceConfig || recurrenceConfig.type === RECURRENCE_TYPES.NONE) {
        const { data, error } = await supabase
          .from('calendar_events')
          .insert([{
             ...safeBaseData,
             is_recurring: false,
             recurrence_config: null,
             series_id: null
          }])
          .select();
        if (error) throw error;
        return data;
      }

      const seriesId = uuidv4();
      
      const instances = generateRecurrenceDates(validStart, validEnd, recurrenceConfig);
      
      if (instances.length === 0) {
          throw new Error("Could not generate valid recurrence dates.");
      }

      const payload = instances.map(instance => ({
        ...safeBaseData,
        start_time: instance.start.toISOString(),
        end_time: instance.end.toISOString(),
        is_recurring: true,
        series_id: seriesId,
        recurrence_config: recurrenceConfig,
        original_start_time: validStart.toISOString()
      }));

      const { data, error } = await supabase
        .from('calendar_events')
        .insert(payload)
        .select();

      if (error) throw error;
      return data;
    } catch (err) {
      console.error("Error creating recurring events:", err);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const updateRecurringEvent = async (originalEvent, newEventData, recurrenceConfig, mode = 'single') => {
    setLoading(true);
    try {
      const validStart = validateAndParseDate(newEventData.start_time);
      const validEnd = validateAndParseDate(newEventData.end_time);
      
      if (!validStart || !validEnd) throw new Error("Invalid dates provided for update.");
      
      const safeNewData = {
          ...newEventData,
          start_time: validStart.toISOString(),
          end_time: validEnd.toISOString()
      };

      const isCurrentlyRecurring = originalEvent.is_recurring && originalEvent.series_id;
      
      if (!isCurrentlyRecurring && recurrenceConfig?.type !== RECURRENCE_TYPES.NONE) {
         await deleteEvent(originalEvent.id);
         return await createRecurringEvents(safeNewData, recurrenceConfig);
      }

      if (isCurrentlyRecurring && mode === 'single') {
         const { data, error } = await supabase
            .from('calendar_events')
            .update({
               ...safeNewData,
               series_id: null,
               is_recurring: false,
               recurrence_config: null
            })
            .eq('id', originalEvent.id)
            .select();
            
         if (error) throw error;
         return data;
      }

      if (isCurrentlyRecurring && mode === 'series') {
         const { error: deleteError } = await supabase
            .from('calendar_events')
            .delete()
            .eq('series_id', originalEvent.series_id);
            
         if (deleteError) throw deleteError;

         return await createRecurringEvents(safeNewData, recurrenceConfig);
      }

      const { data, error } = await supabase
        .from('calendar_events')
        .update({
           ...safeNewData,
           is_recurring: false,
           recurrence_config: null,
           series_id: null
        })
        .eq('id', originalEvent.id)
        .select();

      if (error) throw error;
      return data;

    } catch (err) {
      console.error("Error updating recurring event:", err);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const deleteEvent = async (eventId, seriesId = null, mode = 'single') => {
    setLoading(true);
    try {
      if (mode === 'series' && seriesId) {
         const { error } = await supabase
           .from('calendar_events')
           .delete()
           .eq('series_id', seriesId);
         if (error) throw error;
      } else {
         const { error } = await supabase
           .from('calendar_events')
           .delete()
           .eq('id', eventId);
         if (error) throw error;
      }
    } catch (err) {
      console.error("Error deleting event:", err);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  return {
    createRecurringEvents,
    updateRecurringEvent,
    deleteEvent,
    loading
  };
}
