import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useQueryClient, useInfiniteQuery } from 'react-query';

import { useDebounce } from '@material-hu/hooks/useDebounce';

import { useAuth } from 'src/contexts/JWTContext';
import useTicket from 'src/hooks/queryHooks/ticket';
import useGeneralError from 'src/hooks/useGeneralError';
import usePermissions from 'src/hooks/usePermissions';
import { getChatList, getArchivedChatList } from 'src/services/chats';
import { buildParamsToGetChatsService } from 'src/utils/chats';
import {
  getNextPage,
  getListLength,
  getListItemsLength,
} from 'src/utils/pagination';
import { UserPermissions } from 'src/utils/permissions';

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

const { VIEW_REGULAR_CHATS, VIEW_TICKETS, VIEW_CHATS_V2 } = UserPermissions;

const useChatThread = () => {
  const { t } = useTranslation(['CHAT', 'TICKETS']);
  const { user } = useAuth();
  const [query, setQuery] = useState<string>('');
  const [showArchived, setShowArchived] = useState<boolean>(false);
  const showGeneralError = useGeneralError();
  const debouncedQuery = useDebounce(query);
  const queryClient = useQueryClient();
  const { ticketAgentStats } = useTicket();

  const { hasAll: canViewChats } = usePermissions([VIEW_REGULAR_CHATS]);
  const { hasAll: canViewTickets } = usePermissions([VIEW_TICKETS]);
  const { hasAll: canViewConversations } = usePermissions([VIEW_CHATS_V2]);

  useEffect(() => {
    queryClient.invalidateQueries(chatKeys.list(debouncedQuery));
  }, [canViewChats, canViewTickets]);

  const dataChatList = useInfiniteQuery(
    chatKeys.list(debouncedQuery),
    ({ pageParam = 1 }) => {
      const { page, q, types } = buildParamsToGetChatsService(pageParam, query);
      return getChatList(page, types, q);
    },
    {
      getNextPageParam: (_, pages) =>
        getNextPage(getListLength(pages), 20, pages),
      onError: err => showGeneralError(err, t('ERROR_GET_PARTICIPANTS')),
    },
  );

  const dataArchivedChats = useInfiniteQuery(
    chatKeys.archivedChats.list(debouncedQuery),
    ({ pageParam = 1 }) => {
      const { page, q, types } = buildParamsToGetChatsService(pageParam, query);
      return getArchivedChatList(page, types, q);
    },
    {
      getNextPageParam: (_, pages) =>
        getNextPage(getListItemsLength(pages), 20, pages),
      onError: err => showGeneralError(err, t('ERROR_GET_PARTICIPANTS')),
    },
  );

  const { data: agentStats } = ticketAgentStats(user.id);

  const dataArchivedCount = dataArchivedChats?.data?.pages[0]?.data.count;

  const chatsToShow = showArchived ? dataArchivedChats : dataChatList;

  const emptyInbox = !!dataChatList?.data?.pages.length;

  return {
    chatsToShow,
    emptyInbox,
    dataArchivedCount,
    setQuery,
    agentStats,
    query,
    queryClient,
    canViewChats,
    canViewConversations,
    canViewTickets,
    showArchived,
    setShowArchived,
    t,
  };
};

export default useChatThread;
