import { useCallback, useMemo } from 'react';

import { getUnreadTickets } from 'src/pages/dashboard/tickets/queries';

import { getUnreadChats } from 'src/components/dashboard/chat/queries';
import { getUnreadFormChats } from 'src/components/dashboard/form/queries';

const unread: Set<number> = new Set();

const useUnreadChats = () => {
  const addUnread = useCallback(
    (id: number): void => {
      unread.add(id);
    },
    [unread],
  );

  const deleteUnread = useCallback(
    (id: number): void => {
      unread.delete(id);
    },
    [unread],
  );

  const hasUnread = useCallback(
    (id: number): boolean => {
      const newUnread = getUnread();
      return newUnread.has(id);
    },
    [unread],
  );

  const getUnread = useCallback((): Set<number> => {
    const newUnread = new Set(unread);

    getUnreadChats().forEach(id => newUnread.add(id));

    getUnreadTickets().forEach(id => newUnread.add(id));

    getUnreadFormChats().forEach(id => newUnread.add(id));

    return newUnread;
  }, [unread]);

  const unreadObject = useMemo(
    () => ({
      delete: deleteUnread,
      add: addUnread,
      has: hasUnread,
    }),
    [deleteUnread, addUnread, hasUnread],
  );

  return unreadObject;
};

export default useUnreadChats;
