import {useCallback, useEffect, useState} from 'react';
import {useRoute} from '@react-navigation/native';
import {EventsSocketsType} from '@config/constants';
import {SocketConnection} from '@config/socket/socket';
import {UserPermissions} from '@interfaces/user';
import {usePermission} from '@redux/selectors';
import {Screens} from '@shared/constants';
import {
  ModulesNotifications,
  clearModuleNotifications,
  getModuleNotifications,
} from '@shared/notifications';
import {ERROR} from '@shared/strings';

import {File} from '../../interfaces';

const socket = new SocketConnection();

export const useFolderListeners = (folderId: number) => {
  const VIEW_DOCUMENT = usePermission(UserPermissions.VIEW_DOCUMENT);
  const route = useRoute();
  const [unreadDocuments, setUnreadDocuments] = useState(0);
  const isInDocuments = route.name === Screens.DOCUMENTS && VIEW_DOCUMENT;

  const getFolderNotifications = useCallback(
    async (data?: File) => {
      if (!data || data.folderId === folderId) {
        const response = await getModuleNotifications<{
          documentNotifications: number;
        }>(ModulesNotifications.DOCUMENT, folderId);
        response !== ERROR &&
          setUnreadDocuments(response.documentNotifications);
      }
    },
    [folderId],
  );

  const refreshFolderNotifications = useCallback(() => {
    if (isInDocuments && unreadDocuments) {
      clearModuleNotifications(ModulesNotifications.DOCUMENT, folderId);
      setUnreadDocuments(0);
    }
  }, [unreadDocuments, folderId, isInDocuments]);

  useEffect(() => {
    if (isInDocuments) {
      socket.listenEvent(
        EventsSocketsType.DOCUMENT_CREATED,
        getFolderNotifications,
      );
      socket.listenEvent(
        EventsSocketsType.DOCUMENT_DELETED,
        getFolderNotifications,
      );

      getFolderNotifications();

      return () => {
        socket.unListenEvent(
          EventsSocketsType.DOCUMENT_CREATED,
          getFolderNotifications,
        );
        socket.unListenEvent(
          EventsSocketsType.DOCUMENT_DELETED,
          getFolderNotifications,
        );
      };
    }
  }, [isInDocuments, getFolderNotifications]);

  return {unreadDocuments, refreshFolderNotifications};
};
