/**
 * @ai-summary Hook to show login notifications toast based on notification summary
 * @ai-context Shows once per session on successful authentication
 */

import { useEffect, useRef } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useAuth0 } from '@auth0/auth0-react';
import toast from 'react-hot-toast';
import { notificationsApi } from '../api/notifications.api';

export function useLoginNotifications() {
  const { isAuthenticated } = useAuth0();
  const hasShownToast = useRef(false);

  const { data: summary } = useQuery({
    queryKey: ['notificationSummary'],
    queryFn: notificationsApi.getSummary,
    enabled: isAuthenticated && !hasShownToast.current,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });

  useEffect(() => {
    if (summary && !hasShownToast.current) {
      const maintenanceCount = summary.maintenanceDueSoon + summary.maintenanceOverdue;
      const documentCount = summary.documentsExpiringSoon + summary.documentsExpired;
      const total = maintenanceCount + documentCount;

      if (total > 0) {
        const parts: string[] = [];
        if (maintenanceCount > 0) {
          parts.push(`${maintenanceCount} maintenance item${maintenanceCount > 1 ? 's' : ''}`);
        }
        if (documentCount > 0) {
          parts.push(`${documentCount} document${documentCount > 1 ? 's' : ''}`);
        }

        toast(`You have ${parts.join(' and ')} requiring attention`, {
          duration: 6000,
          icon: '🔔',
        });
      }
      hasShownToast.current = true;
    }
  }, [summary]);

  return summary;
}
