'use client';

import React, { useEffect, useRef, useState } from 'react';
import { notification } from 'antd';
import { useRouter } from 'next/navigation';
import { CheckCircleFilled, CloseCircleFilled, ExclamationCircleFilled, InfoCircleFilled } from '@ant-design/icons';
import { getAutoLeadNotifications, markAutoLeadNotificationRead } from '../service';
import type { AutoLeadNotification, AutoLeadNotificationType } from '../interface';

const POLL_INTERVAL_MS = 60000;

interface NotificationStyle {
  title: string;
  color: string;
  background: string;
  icon: React.ReactNode;
}

/* One look per notification type: duplicate = yellow, new lead = green,
 reassigned = gray, overdue (10+ days) = red. */
const NOTIFICATION_STYLES: Record<AutoLeadNotificationType, NotificationStyle> = {
  duplicate: { title: 'Duplicate lead', color: '#faad14', background: '#fffbe6', icon: <ExclamationCircleFilled style={{ color: '#faad14' }} /> },
  new_lead: { title: 'New lead', color: '#52c41a', background: '#f6ffed', icon: <CheckCircleFilled style={{ color: '#52c41a' }} /> },
  reassigned: { title: 'Lead reassigned', color: '#8c8c8c', background: '#f5f5f5', icon: <InfoCircleFilled style={{ color: '#8c8c8c' }} /> },
  overdue: { title: 'Lead overdue 10+ days', color: '#ff4d4f', background: '#fff1f0', icon: <CloseCircleFilled style={{ color: '#ff4d4f' }} /> },
};

/*
  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 and shows
  one toast per notification, colored by its type, marking it read so it isn't
  shown again. A notification with no type (created before the type column
  existed) keeps the plain default toast. Clicking a toast closes it and opens
  that lead's detail drawer (/enquiries?id=<lead id>).
 */
const DuplicateLeadNotifier: React.FC = () => {
  const [notifications, setNotifications] = useState<AutoLeadNotification[]>([]);
  const shownRef = useRef<Set<number>>(new Set());
  const router = useRouter();

  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);

      const key = String(item.id);
      const common = {
        key,
        duration: 0,
        className: 'cursor-pointer',
        onClick: (): void => {
          notification.destroy(key);
          router.push(`/enquiries?id=${item.lead_id}`);
        },
      };

      const style = item.type ? NOTIFICATION_STYLES[item.type] : undefined;
      if (style) {
        notification.open({
          ...common,
          message: `${style.title} · ${item.source}`,
          description: item.message,
          icon: style.icon,
          style: { background: style.background, border: `1px solid ${style.color}`, borderRadius: 8 },
        });
      } else {
        notification.info({
          ...common,
          message: `New lead via ${item.source}`,
          description: item.message,
        });
      }

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

  return null;
};

export default DuplicateLeadNotifier;
