import { useInfiniteQuery } from 'react-query';

import useGeneralError from 'src/hooks/useGeneralError';
import { getShiftsRepository } from 'src/services/shifts';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { shiftsKeys } from '../queries';

type UseGetShiftsRepositoryParams = {
  search: string;
};

export const useGetShiftsRepository = ({
  search,
}: UseGetShiftsRepositoryParams) => {
  const showGeneralError = useGeneralError();
  const { t } = useLokaliseTranslation('shifts');

  const {
    data: infiniteRegisters,
    isLoading,
    isFetchingNextPage,
    hasNextPage,
    fetchNextPage,
  } = useInfiniteQuery({
    queryKey: shiftsKeys.shiftsRepository({ search }),
    queryFn: ({ pageParam = 1 }) =>
      getShiftsRepository({ page: pageParam, search }),
    getNextPageParam: (_, pages) => {
      const { page, totalPages } = pages[pages.length - 1]?.data || {};
      return page < totalPages ? pages.length + 1 : undefined;
    },
    onError: () => {
      showGeneralError(t('error_load_shifts_repository'));
    },
    staleTime: 1000 * 60 * 2,
  });

  const registers =
    infiniteRegisters?.pages?.flatMap(page => page.data.items) || [];

  return {
    registers,
    isLoading,
    isFetchingNextPage,
    hasNextPage,
    fetchNextPage,
  };
};
