import { useState, useEffect, useCallback } from 'react';
import notificationService, { type Notification } from '../services/notificationService';

export function useNotifications() {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchNotifications = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await notificationService.getNotifications();
      const filtered = data
        .filter(Boolean)
        .filter((n) => !n.subject?.startsWith('Failed to send email'));
      setNotifications(filtered);
      setUnreadCount(filtered.filter((n) => !n.read).length);
      // setNotifications(data);
      // setUnreadCount(data.filter(n => !n.read).length);
    } catch (err: any) {
      // Silently handle 417 errors (API not available)
      if (err?.message?.includes('417') || err?.message?.includes('EXPECTATION FAILED')) {
        setNotifications([]);
        setUnreadCount(0);
        setError(null);
      } else {
        const errorMessage = err instanceof Error ? err.message : 'Failed to fetch notifications';
        setError(errorMessage);
        console.warn('Error fetching notifications:', err);
      }
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchNotifications();
    
    // Poll for new notifications every 30 seconds
    const interval = setInterval(fetchNotifications, 30000);
    
    return () => clearInterval(interval);
  }, [fetchNotifications]);

  const markAsRead = useCallback(async (notificationName: string) => {
    // Optimistic update
    const previousNotifications = notifications;
    const previousCount = unreadCount;

    setNotifications(prev =>
      prev.map(n => n.name === notificationName ? { ...n, read: 1 } : n)
    );
    setUnreadCount(prev => Math.max(0, prev - 1));

    try {
      await notificationService.markAsRead(notificationName);
    } catch (error) {
      // Rollback on failure
      console.error('Error marking notification as read:', error);
      setNotifications(previousNotifications);
      setUnreadCount(previousCount);
      throw error;
    }
  }, [notifications, unreadCount]);

  const markAllAsRead = useCallback(async () => {
    // Optimistic update — clear red badges immediately
    const previousNotifications = notifications;
    const previousCount = unreadCount;

    setNotifications(prev =>
      prev.map(n => ({ ...n, read: 1 }))
    );
    setUnreadCount(0);

    try {
      await notificationService.markAllAsRead();
    } catch (error) {
      // Rollback on failure
      console.error('Error marking all notifications as read:', error);
      setNotifications(previousNotifications);
      setUnreadCount(previousCount);
      throw error;
    }
  }, [notifications, unreadCount]);

  return { 
    notifications, 
    unreadCount, 
    loading, 
    error,
    markAsRead,
    markAllAsRead,
    refetch: fetchNotifications
  };
}