import { useInfiniteQuery } from 'react-query';

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

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

const PAGE_SIZE = 5;

type UseGetShiftRotationsParams = {
  search: string;
};

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

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

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

  const totalCount = infiniteRegisters?.pages?.[0]?.data?.count ?? 0;

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