import { useEffect, useRef } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import logWebUserEvent from '@/logging/logWebUserEvent';

import { useBreakpointMd } from './useBreakpoint';

const DEFAULT_POLLING_INTERVAL = 5 * 60000; // Five minutes

/**
 * Starts polling for updates to notifications
 *
 * Pass a polling interval of 0 to disable polling, or -1 to disable fetching
 * notifications entirely
 */
export default function useNotifications(
  pollingInterval = DEFAULT_POLLING_INTERVAL
) {
  const isMobile = !useBreakpointMd();
  const { notifications: notificationsStore } = useStores();
  const isBootstrapped = useRef(false);
  const prevUnreadCount = useRef(0);

  useEffect(() => {
    // Disable polling by using a negative interval
    if (pollingInterval < 0) {
      return;
    }

    let pollingTimeout: ReturnType<typeof setTimeout>;

    async function loadNotifications() {
      await notificationsStore.loadNotifications();

      if (pollingInterval) {
        pollingTimeout = setTimeout(loadNotifications, pollingInterval);
      }
    }

    // Only bootstrap notifications once
    if (!isBootstrapped.current) {
      loadNotifications();
      isBootstrapped.current = true;
    }

    return () => {
      clearTimeout(pollingTimeout);
    };
  }, [notificationsStore, pollingInterval]);

  useEffect(() => {
    if (prevUnreadCount.current === 0 && notificationsStore.unreadCount) {
      logWebUserEvent({
        actionName: 'NotificationAlert',
        context: {
          unreadCount: notificationsStore.unreadCount,
          isMobile,
        },
      });
    }
    prevUnreadCount.current = notificationsStore.unreadCount;
  }, [notificationsStore.unreadCount, isMobile]);

  return notificationsStore;
}
