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

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

import { acknowledgementsKeys } from '../queries';
import { getAcknowledgements } from '../services';

export const useGetAcknowledgements = (categoryId: number | null = null) => {
  const showGeneralError = useGeneralError();
  const { t } = useLokaliseTranslation('acknowledgements');

  const { data, hasNextPage, isLoading, fetchNextPage, isFetchingNextPage } =
    useInfiniteQuery({
      queryKey: acknowledgementsKeys.list(categoryId),
      queryFn: ({ pageParam = '' }) =>
        getAcknowledgements(pageParam, undefined, categoryId),
      getNextPageParam: lastPage =>
        lastPage.data?.length > 0
          ? lastPage.data[lastPage.data.length - 1].createdAt
          : undefined,
      onError: err => showGeneralError(err, t('error_get_acknowledgements')),
    });

  const acknowledgements = useMemo(
    () => data?.pages.flatMap(page => page.data) ?? [],
    [data?.pages],
  );

  const isEmpty = !isLoading && !acknowledgements.length;

  return {
    acknowledgements,
    isEmpty,
    hasNextPage,
    isLoading,
    fetchNextPage,
    isFetchingNextPage,
  };
};
