import { useState, useEffect, useRef, useCallback } from 'react';
import { IAlert } from '../types';
import { dataService } from '../services/dataService';

const POLLING_INTERVAL = 30000; // 30 seconds

export const useNotifications = () => {
  const [isNotificationsOpen, setIsNotificationsOpen] = useState(false);
  const [isAllNotificationsModalOpen, setIsAllNotificationsModalOpen] = useState(false);
  const [alerts, setAlerts] = useState<IAlert[]>([]);
  const notificationRef = useRef<HTMLDivElement>(null);

  const fetchAlerts = useCallback(async () => {
    const data = await dataService.getAlerts();
    // Sort by newest
    setAlerts(data.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()));
  }, []);

  const handleMarkAsRead = useCallback(async () => {
    // Mark all visible as read
    for (const alert of alerts) {
      if (!alert.isRead) await dataService.markAlertAsRead(alert._id);
    }
    await fetchAlerts();
  }, [alerts, fetchAlerts]);

  const handleMarkAllAsRead = useCallback(async () => {
    // Mark ALL alerts as read (not just visible ones)
    const unreadAlerts = alerts.filter(alert => !alert.isRead);
    for (const alert of unreadAlerts) {
      await dataService.markAlertAsRead(alert._id);
    }
    await fetchAlerts();
  }, [alerts, fetchAlerts]);

  const handleDeleteAlert = useCallback(async (alertId: string) => {
    try {
      await dataService.deleteAlert(alertId);
      await fetchAlerts();
    } catch (error) {
      console.error('Failed to delete alert:', error);
    }
  }, [fetchAlerts]);

  useEffect(() => {
    fetchAlerts();

    // Polling for alerts every 30s
    const interval = setInterval(fetchAlerts, POLLING_INTERVAL);

    const handleClickOutside = (event: MouseEvent) => {
      if (notificationRef.current && !notificationRef.current.contains(event.target as Node)) {
        setIsNotificationsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      clearInterval(interval);
    };
  }, [fetchAlerts]);

  const unreadCount = alerts.filter(n => !n.isRead).length;

  return {
    isNotificationsOpen,
    setIsNotificationsOpen,
    isAllNotificationsModalOpen,
    setIsAllNotificationsModalOpen,
    alerts,
    unreadCount,
    handleMarkAsRead,
    handleMarkAllAsRead,
    handleDeleteAlert,
    notificationRef,
    refreshAlerts: fetchAlerts
  };
};
