import { useState, useCallback } from 'react';
import { api } from '@/lib/api';
import { ENDPOINTS } from '@/constants/endpoints';
import type { NotificationDTO, ApiResponse } from '@/types';

export function useNotifications() {
  const [notifications, setNotifications] = useState<NotificationDTO[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchNotifications = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const response: ApiResponse<NotificationDTO[]> = await api.get(ENDPOINTS.NOTIFICATIONS.LIST);
      if (response.success && response.data) {
        setNotifications(Array.isArray(response.data) ? response.data : []);
      } else {
        setNotifications([]);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to fetch notifications');
      setNotifications([]);
    } finally {
      setIsLoading(false);
    }
  }, []);

  const markAsRead = useCallback(async (id: string): Promise<boolean> => {
    try {
      const response: ApiResponse<void> = await api.patch(ENDPOINTS.NOTIFICATIONS.MARK_READ(id), {});
      if (response.success) {
        setNotifications(prev =>
          prev.map(n => n.id === id ? { ...n, status: 'read', read_at: new Date().toISOString() } : n)
        );
        return true;
      }
      return false;
    } catch {
      return false;
    }
  }, []);

  const unreadCount = notifications.filter(n => n.status !== 'read' && !n.read_at).length;

  return { notifications, isLoading, error, fetchNotifications, markAsRead, unreadCount };
}
