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

export function useNotifications(userId) {
  const { toast } = useToast();
  const [unreadCount, setUnreadCount] = useState(0);
  const [notifications, setNotifications] = useState([]);
  const [loading, setLoading] = useState(true);
  const channelRef = useRef(null);

  const fetchUnreadCount = useCallback(async () => {
    if (!userId) return;
    try {
      const { count, error } = await supabase
        .from('reminders')
        .select('*', { count: 'exact', head: true })
        .eq('created_by', userId)
        .eq('status', 'pending');

      if (error) throw error;
      setUnreadCount(count || 0);
    } catch (error) {
      console.error('fetchUnreadCount error:', error);
    }
  }, [userId]);

  const fetchNotifications = useCallback(async (limit = 10, offset = 0) => {
    if (!userId) return;
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('reminders')
        .select('*')
        .eq('created_by', userId)
        .order('created_at', { ascending: false })
        .range(offset, offset + limit - 1);

      if (error) throw error;

      if (offset === 0) {
        setNotifications(data || []);
      } else {
        setNotifications(prev => [...prev, ...(data || [])]);
      }
    } catch (error) {
      console.error('fetchNotifications error:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to load notifications." });
    } finally {
      setLoading(false);
    }
  }, [userId, toast]);

  const markAsRead = useCallback(async (id) => {
    try {
      const { error } = await supabase
        .from('reminders')
        .update({ status: 'completed', updated_at: new Date().toISOString() })
        .eq('id', id);

      if (error) throw error;
      setNotifications(prev => prev.map(n => n.id === id ? { ...n, status: 'completed' } : n));
      setUnreadCount(prev => Math.max(0, prev - 1));
    } catch (error) {
      console.error('markAsRead error:', error);
    }
  }, []);

  const deleteNotification = useCallback(async (id) => {
    try {
      const wasUnread = notifications.find(n => n.id === id)?.status === 'pending';
      const { error } = await supabase.from('reminders').delete().eq('id', id);
      if (error) throw error;

      setNotifications(prev => prev.filter(n => n.id !== id));
      if (wasUnread) setUnreadCount(prev => Math.max(0, prev - 1));
      toast({ description: "Notification removed." });
    } catch (error) {
      console.error('deleteNotification error:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to delete notification." });
    }
  }, [notifications, toast]);

  useEffect(() => {
    if (!userId) return;
    fetchUnreadCount();

    const channel = supabase
      .channel(`reminders:${userId}`)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'reminders', filter: `created_by=eq.${userId}` }, () => {
        fetchUnreadCount();
        fetchNotifications();
      })
      .subscribe();

    channelRef.current = channel;

    return () => {
      supabase.removeChannel(channel);
      channelRef.current = null;
    };
  }, [userId, fetchUnreadCount, fetchNotifications]);

  return { unreadCount, notifications, loading, fetchNotifications, markAsRead, deleteNotification };
}
