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

export function useStaffCalendarEvents() {
  const [events, setEvents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { toast } = useToast();

  const fetchEvents = useCallback(async (startRange, endRange) => {
    setLoading(true);
    try {
      let query = supabase
        .from('staff_calendar_events')
        .select('*')
        .neq('category', 'client')
        .order('start_time', { ascending: true });
        
      if (startRange) {
        query = query.gte('end_time', startRange.toISOString());
      }
      if (endRange) {
        query = query.lte('start_time', endRange.toISOString());
      }

      const { data, error } = await query;

      if (error) throw error;
      
      const staffEvents = (data || []).filter(evt => evt.type !== 'client' && evt.category !== 'client');
      setEvents(staffEvents);
    } catch (err) {
      console.error('Error fetching calendar events:', err);
      setError(err);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to load calendar events."
      });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const createEvent = async (eventData) => {
    if (eventData.category === 'client' || eventData.type === 'client') {
      const err = new Error("Cannot create client events in staff calendar.");
      toast({ variant: "destructive", title: "Restricted", description: err.message });
      throw err;
    }

    try {
      const { data, error } = await supabase
        .from('staff_calendar_events')
        .insert([{
            ...eventData,
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString()
        }])
        .select()
        .single();

      if (error) throw error;
      
      setEvents(prev => [...prev, data]);
      toast({ title: "Event Created", description: "Successfully added to calendar." });
      return data;
    } catch (err) {
      console.error('Error creating event:', err);
      toast({ variant: "destructive", title: "Error", description: err.message });
      throw err;
    }
  };

  const updateEvent = async (id, updates) => {
    if (updates.category === 'client' || updates.type === 'client') {
      const err = new Error("Cannot convert event to client type.");
      toast({ variant: "destructive", title: "Restricted", description: err.message });
      throw err;
    }

    try {
      const { data, error } = await supabase
        .from('staff_calendar_events')
        .update({
            ...updates,
            updated_at: new Date().toISOString()
        })
        .eq('id', id)
        .select()
        .single();

      if (error) throw error;

      setEvents(prev => prev.map(ev => ev.id === id ? data : ev));
      toast({ title: "Event Updated", description: "Changes saved successfully." });
      return data;
    } catch (err) {
      console.error('Error updating event:', err);
      toast({ variant: "destructive", title: "Error", description: err.message });
      throw err;
    }
  };

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

      if (error) throw error;

      setEvents(prev => prev.filter(ev => ev.id !== id));
      toast({ title: "Event Deleted", description: "Removed from calendar." });
    } catch (err) {
      console.error('Error deleting event:', err);
      toast({ variant: "destructive", title: "Error", description: err.message });
      throw err;
    }
  };

  const refreshEvents = () => {
    const start = new Date();
    start.setMonth(start.getMonth() - 1);
    const end = new Date();
    end.setMonth(end.getMonth() + 3);
    fetchEvents(start, end);
  };

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

  return {
    events,
    loading,
    error,
    createEvent,
    updateEvent,
    deleteEvent,
    fetchEvents,
    refreshEvents
  };
}
