import { useInfiniteQuery } from 'react-query';

import useGeneralError from 'src/hooks/useGeneralError';
import { getGroupScheduledPosts } from 'src/services/groups';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import { groupsKeys } from '../../../groups/queries';

const useGroupScheduledPostsQuery = (
  groupId: string,
  enabled: boolean = true,
) => {
  const { t } = useTranslation();
  const showGeneralError = useGeneralError();

  return useInfiniteQuery(
    groupsKeys.scheduledPostList(groupId),
    ({ pageParam = 1 }) => getGroupScheduledPosts(groupId, pageParam),
    {
      getNextPageParam: (_, pages) => {
        const { page, totalPages } = pages[pages.length - 1]?.data || {};
        return page < totalPages ? pages.length + 1 : undefined;
      },
      onError: err => {
        showGeneralError(err, t('group:error_loading_scheduled_posts'));
      },
      enabled: enabled && !!groupId,
      keepPreviousData: true,
      staleTime: 5 * 1000,
    },
  );
};

export default useGroupScheduledPostsQuery;
