import { useQuery } from 'react-query';

import useGeneralError from 'src/hooks/useGeneralError';
import { useTranslation } from 'src/pages/dashboard/tickets/i18n';
import { ticketKeys } from 'src/pages/dashboard/tickets/queries';
import { getTopicList, getTicketAgentStats } from 'src/services/tickets';
import { UserPermissions } from 'src/utils/permissions';

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

import usePermissions from '../usePermissions';

export const useTicket = () => {
  const showGeneralError = useGeneralError();
  const { hasAll: canViewTickets } = usePermissions([
    UserPermissions.VIEW_TICKETS,
  ]);

  const { t } = useTranslation();

  const ticketTopicData = () =>
    useQuery(ticketKeys.topic.list(), getTopicList, {
      onError: err => {
        showGeneralError(err, t('ERROR_LOADING_TOPICS'));
      },
      enabled: canViewTickets,
    });

  const ticketAgentStats = userId =>
    useQuery(
      chatKeys.ticketAgentStats.detail(Number(userId)),
      () => getTicketAgentStats(userId),
      {
        onError: err =>
          showGeneralError(err, t('CHAT:ERROR_LOADING_AGENT_STATS')),
        enabled: canViewTickets,
      },
    );

  return {
    ticketTopicData,
    ticketAgentStats,
  };
};

export default useTicket;
