import { useQuery } from 'react-query';
import { useInfiniteQuery } from 'react-query';

import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import { getChatById } from 'src/services/chats';
import { getParticipantsOfGroup } from 'src/services/chats';
import { ChatType } from 'src/types/chats';

import { useTranslation } from 'src/components/dashboard/chat/i18n';
import { chatKeys } from 'src/components/dashboard/chat/queries';

export const useChat = (key, id) => {
  const { user } = useAuth();
  const showGeneralError = useGeneralError();
  const { t } = useTranslation();

  const userId = user?.id;

  const chatResult = useQuery(key, () => getChatById(id), {
    onError: err => {
      showGeneralError(err, t('CHAT:ERROR_LOADING_THREAD'));
    },
  });

  const isGroup = chatResult?.data?.data?.chatType === ChatType.REGULAR_GROUP;

  const { data } = useInfiniteQuery(
    chatKeys.participants(id),
    ({ pageParam = 1 }) =>
      getParticipantsOfGroup(id, pageParam, isGroup ? 20 : 2, false, !isGroup),
    {
      onError: err => showGeneralError(err, t('ERROR_GET_PARTICIPANTS')),
      enabled: !!chatResult?.data,
    },
  );

  let otherUser = null;
  let participants = null;
  if (isGroup) {
    participants = data?.pages[0]?.data?.items;
  } else {
    otherUser = data?.pages[0]?.data?.items.find(elem => elem.id !== userId);
  }

  return { ...chatResult, otherUser, participants };
};

export default useChat;
