import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';

export function useBlockedDates() {
  const [blockedDates, setBlockedDates] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchBlockedDates = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      const { data, error: fetchError } = await supabase
        .from('blocked_dates')
        .select('*')
        .order('start_date', { ascending: false });

      if (fetchError) throw fetchError;
      
      const mappedData = (data || []).map(event => ({
        id: event.id,
        date: event.start_date,
        reason: event.title || event.reason || "Blocked",
        source: 'admin',
        created_by: event.created_by,
        start_date: event.start_date,
        end_date: event.end_date,
        title: event.title,
        ...event
      }));

      setBlockedDates(mappedData);
    } catch (err) {
      console.error('[useBlockedDates] Error fetching blocked dates:', err);
      setError(err);
      setBlockedDates([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchBlockedDates();

    const channel = supabase
      .channel('blocked-dates-realtime')
      .on('postgres_changes', { event: '*', schema: 'public', table: 'blocked_dates' }, () => fetchBlockedDates())
      .subscribe();

    return () => { supabase.removeChannel(channel); };
  }, [fetchBlockedDates]);

  const isDateBlocked = useCallback((date) => {
    if (!date) return false;
    const dateString = date instanceof Date ? date.toISOString().split('T')[0] : date;
    return blockedDates.some(bd => bd.start_date <= dateString && bd.end_date >= dateString);
  }, [blockedDates]);

  return { blockedDates, loading, error, refetch: fetchBlockedDates, isDateBlocked };
}
