'use client';

import { useEffect, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { notification } from 'antd';
import { useRouter } from 'next/navigation';
import { fetchAllTodayFollowUpLeads, removeTodayFollowUpLead } from '../followUpSlice';
import type { AppDispatch } from '@/store/store';

const FollowUpNotifier = () => {
  const dispatch = useDispatch<AppDispatch>();
  const tabKey = 'today_follow_up';
 const router = useRouter();
  const allTodayFollowUpLeads = useSelector((state: any) => state.followUpLeads.allTodayFollowUpLeads);
  // Track notified leads (won't reset on re-renders)
  const notifiedLeadsRef = useRef<Set<number>>(new Set());

  // Check if follow-up is due
  const isDueNow = (followUpTime: string): boolean => {
    if (!followUpTime) return false;
    const now = Date.now();
    const followUp = new Date(followUpTime).getTime();
    const diffInMs = now - followUp;
    return diffInMs >= 1 * 60 * 1000; // 1 minutes = 60000 ms
  };

  useEffect(() => {
    dispatch(fetchAllTodayFollowUpLeads(tabKey));
  }, [dispatch]);

  useEffect(() => {
    const interval = setInterval(() => {
      allTodayFollowUpLeads?.forEach((lead: any) => {
        // Only notify if not already notified
        if (
          lead.follow_up_date &&
          isDueNow(lead.follow_up_date) &&
          !notifiedLeadsRef.current.has(lead.id)
        ) {
          const isSuperHot = lead.tag === 'super_hot';
          const notificationConfig: any = {
            message: (
              <div style={{ display: 'flex', flexDirection: 'column' }}>
                {isSuperHot && (
                  <span
                    style={{
                      background: '#fff',
                      color: '#f33066',
                      padding: '4px 8px 2px 8px',
                      letterSpacing: '0.5px',
                      borderRadius: '4px',
                      fontSize: '11px',
                      fontWeight: 'bold',
                      width: 'fit-content',
                      marginBottom: '4px',
                      textTransform: 'uppercase',
                      boxShadow: '0 2px 4px rgba(0,0,0,0.05)',
                    }}
                  >
                    🔥 Super Hot
                  </span>
                )}
                <span style={{
                  color: isSuperHot ? '#000000' : 'inherit',
                  fontWeight: 'bold',
                  fontSize: '16px',
                }}>
                  Follow-up Reminder
                </span>
              </div>
            ),
            description: (
              <span style={{ color: isSuperHot ? '#000000' : 'inherit' }}>
                The follow-up for <strong>{lead.customer_name}</strong> on{' '}
                <strong>{lead.project_name}</strong> is now due.
                {isSuperHot && lead.configuration && (
                  <div style={{ marginTop: '8px', fontWeight: 500 }}>
                    Config: <strong>{lead.configuration}</strong>
                  </div>
                )}
              </span>
            ),
            duration: 0,
            className: 'cursor-pointer',
            style: isSuperHot
              ? {
                  background: '#effab6',
                  border: '1px solid #CEF212',
                  borderRadius: '8px',
                }
              : {},
            onClick: () => {
              dispatch(removeTodayFollowUpLead(lead.id));
              router.push(`/enquiries?tabkey=today_follow_up&id=${lead.id}`);
            },
            onClose: () => {
              console.log(`Removed This Id ${lead.id}`);
              dispatch(removeTodayFollowUpLead(lead.id));
              // router.push(`/enquiries?tabkey=overdue&id=${lead.id}`);
            },
          };
          notification.warning(notificationConfig);

          notifiedLeadsRef.current.add(lead.id);
        }
      });

    }, 60000); // every 60 seconds

    return () => clearInterval(interval); // cleanup on unmount
  }, [allTodayFollowUpLeads]);
  return null;
};

export default FollowUpNotifier;
