'use client';

import React, { useEffect, useRef, useState } from 'react';
import { notification } from 'antd';
import { getAutoLeadNotifications, markAutoLeadNotificationRead } from '../service';
import type { AutoLeadNotification } from '../interface';

const POLL_INTERVAL_MS = 60000;

/*
  Mounted globally (see client-provider.tsx), same polling pattern as
  FollowUpNotifier — no push/socket delivery. Every 60s, fetches unread
  Auto Lead Assignment notifications for the logged-in sales person (raised
  when a duplicate, non-dead lead comes in again via the same source) and
  shows one toast per notification, marking it read so it isn't shown again.
 */
const DuplicateLeadNotifier: React.FC = () => {
  const [notifications, setNotifications] = useState<AutoLeadNotification[]>([]);
  const shownRef = useRef<Set<number>>(new Set());

  const fetchNotifications = (): void => {
    getAutoLeadNotifications()
      .then(setNotifications)
      .catch(() => {});
  };

  useEffect(() => {
    fetchNotifications();
    const interval = setInterval(fetchNotifications, POLL_INTERVAL_MS);
    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    notifications.forEach((item) => {
      if (shownRef.current.has(item.id)) return;
      shownRef.current.add(item.id);

      notification.info({
        message: `New lead via ${item.source}`,
        description: item.message,
        duration: 0,
      });

      markAutoLeadNotificationRead(item.id).catch(() => {});
    });
  }, [notifications]);

  return null;
};

export default DuplicateLeadNotifier;
