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

export function useImportedCalendars() {
  const [calendars, setCalendars] = useState([]);
  const [loading, setLoading] = useState(true);
  const { toast } = useToast();

  const fetchCalendars = useCallback(async () => {
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from('calendar_events')
        .select('*')
        .order('created_at', { ascending: false });

      if (error) throw error;
      setCalendars(data || []);
    } catch (err) {
      console.error('Error fetching imported calendars:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchCalendars();
  }, [fetchCalendars]);

  const addCalendar = async (eventData) => {
    try {
      const { data, error } = await supabase
        .from('calendar_events')
        .insert([eventData])
        .select()
        .single();

      if (error) throw error;
      setCalendars(prev => [data, ...prev]);
      toast({ title: "Calendar Event Added", description: "Event saved successfully." });
      return data;
    } catch (err) {
      console.error('Error adding calendar event:', err);
      toast({ variant: "destructive", title: "Error", description: err.message });
      throw err;
    }
  };

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

      if (error) throw error;
      setCalendars(prev => prev.filter(c => c.id !== id));
      toast({ title: "Event Removed", description: "Calendar event deleted." });
    } catch (err) {
      console.error('Error removing calendar event:', err);
      toast({ variant: "destructive", title: "Error", description: err.message });
    }
  };

  return { calendars, loading, addCalendar, removeCalendar, refreshCalendars: fetchCalendars };
}
