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

// How long after one answer the next call goes out: a minute while the pop-ups
// are switched on, five while the backend says they are switched off (so that
// switching them on reaches every open browser without a reload).
const POLL_INTERVAL_MS = 60000;
const POLL_INTERVAL_WHILE_OFF_MS = 5 * 60000;
// The browser's event for a tab being shown or hidden.
// eslint-disable-next-line spellcheck/spell-checker
const VISIBILITY_EVENT = 'visibilitychange';

// Assigned (new lead), reassigned and duplicate notifications are only worth opening while the lead is still the user's.
const OWNERSHIP_CHECKED_TYPES: Array<AutoLeadNotificationType | null> = ['new_lead', 'reassigned', 'duplicate'];

// How long the "lead expired" notice stays on screen before it dismisses itself.
const EXPIRED_NOTICE_SECONDS = 10;

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

/* One look per notification type: duplicate = yellow, new lead = green,
 reassigned = gray, overdue = 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', color: '#ff4d4f', background: '#fff1f0', icon: <CloseCircleFilled style={{ color: '#ff4d4f' }} /> },
};

/*
  Mounted globally (see client-provider.tsx) — no push/socket delivery. Fetches
  the logged-in sales person's unread Auto Lead Assignment notifications and
  shows one toast per notification, colored by its type, showing client,
  source, launch and project. A toast has no close button and stays until
  clicked; clicking it marks that notification read and opens the lead's
  detail drawer (/enquiries?id=<lead id>). A notification with no type
  (created before the type column existed) gets the same toast without the color.

  How it polls, so it can never pile calls up on a slow server:
   - One call at a time. The next call is timed from the moment the last
     answer arrived (or failed, or timed out after 15s) — never while one is
     still waiting.
   - Only while this tab is on screen. A toast is drawn inside the page, so
     nobody can see it in a hidden tab; when the tab is shown again the call
     goes out as soon as it is due — at once, if it has been hidden for longer
     than the interval.
 */
const DuplicateLeadNotifier: React.FC = () => {
  const [notifications, setNotifications] = useState<AutoLeadNotification[]>([]);
  const shownRef = useRef<Set<number>>(new Set());
  const router = useRouter();

  useEffect(() => {
    let timer: ReturnType<typeof setTimeout> | null = null;
    let inFlight = false;
    let stopped = false;
    let nextCallAt = 0; // the first call is due straight away

    const isOnScreen = (): boolean => document.visibilityState === 'visible';

    const cancelTimer = (): void => {
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
    };

    const poll = (): void => {
      timer = null;
      if (stopped || inFlight || !isOnScreen()) return;

      inFlight = true;
      let interval = POLL_INTERVAL_MS;
      getAutoLeadNotifications()
        .then((result) => {
          if (stopped) return;
          if (!result.enabled) interval = POLL_INTERVAL_WHILE_OFF_MS;
          setNotifications(result.data);
        })
        .catch(() => {})
        .finally(() => {
          inFlight = false;
          nextCallAt = Date.now() + interval;
          scheduleNext();
        });
    };

    // Arms the timer for the next call — unless one is still waiting for its
    // answer, or the tab is hidden (onVisibilityChange arms it again).
    function scheduleNext(): void {
      cancelTimer();
      if (stopped || inFlight || !isOnScreen()) return;
      timer = setTimeout(poll, Math.max(0, nextCallAt - Date.now()));
    }

    const onVisibilityChange = (): void => {
      if (isOnScreen()) scheduleNext();
      else cancelTimer();
    };

    document.addEventListener(VISIBILITY_EVENT, onVisibilityChange);
    scheduleNext();

    return () => {
      stopped = true;
      cancelTimer();
      document.removeEventListener(VISIBILITY_EVENT, onVisibilityChange);
    };
  }, []);

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

      const key = String(item.id);
      const style = item.type ? NOTIFICATION_STYLES[item.type] : undefined;

      // Same four lines for every kind of notification. An overdue one adds its message on top:
      // it says who missed the lead and for how long, which the four lines do not.
      const details = (
        <div style={{ lineHeight: 1.6 }}>
          {item.type === 'overdue' && item.message && <div style={{ marginBottom: 4 }}>{item.message}</div>}
          <div><b>Source:</b> {item.source}</div>
          <div><b>Client Name:</b> {item.client_name || '-'}</div>
          <div><b>Launch:</b> {item.launch_name || '-'}</div>
          <div><b>Project:</b> {item.project_name || '-'}</div>
        </div>
      );

      // The toast stays on screen until the server has answered, so a second click must not start a second call.
      let clicked = false;

      notification.open({
        key,
        duration: 0,
        // No close button: the only way to dismiss it is to open the lead.
        closeIcon: false,
        className: 'cursor-pointer',
        message: style ? style.title : 'New lead',
        description: details,
        icon: style?.icon,
        style: style ? { background: style.background, border: `1px solid ${style.color}`, borderRadius: 8 } : undefined,
        onClick: (): void => {
          if (clicked) return;
          clicked = true;
          const openLead = (): void => {
            notification.destroy(key);
            router.push(`/enquiries?id=${item.lead_id}`);
          };
          // Marked read only now, so a notification nobody has opened yet comes back after a refresh.
          // The same call says whether the user still owns the lead: an assigned / reassigned one
          // may have moved on (e.g. the 30-minute rotation) while this toast sat on screen.
          markAutoLeadNotificationRead(item.id)
            .then(({ is_current_owner: isCurrentOwner }) => {
              if (!isCurrentOwner && OWNERSHIP_CHECKED_TYPES.includes(item.type)) {
                // Same key as the clicked toast, so the notice takes its place in the stack.
                notification.warning({
                  key,
                  message: 'Lead expired',
                  description: 'This lead has expired for you. It is no longer assigned to you.',
                  duration: EXPIRED_NOTICE_SECONDS,
                });
                return;
              }
              openLead();
            })
            .catch(openLead);
        },
      });
    });
  }, [notifications, router]);

  return null;
};

export default DuplicateLeadNotifier;
