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

import useGeneralError from 'src/hooks/useGeneralError';
import { getShiftCalendar, ShiftCalendarParams } from 'src/services/shifts';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

const PAGE_SIZE = 20;

export const useGetShiftsCalendar = (
  queryParams: Omit<ShiftCalendarParams, 'page' | 'limit'>,
  options?: { enabled?: boolean },
) => {
  const showGeneralError = useGeneralError();
  const { t } = useLokaliseTranslation('shifts');

  const {
    data: infiniteRegisters,
    isLoading: isLoadingCollaborators,
    isFetchingNextPage,
    hasNextPage,
    fetchNextPage,
  } = useInfiniteQuery(
    shiftsKeys.calendar({ ...queryParams }),
    ({ pageParam = 1, signal }) =>
      getShiftCalendar(
        {
          ...queryParams,
          page: pageParam,
          limit: PAGE_SIZE,
        },
        signal,
      ),
    {
      enabled: options?.enabled ?? true,
      getNextPageParam: (_, pages) => {
        const { page, totalPages } = pages[pages.length - 1]?.data || {};
        return page < totalPages ? pages.length + 1 : undefined;
      },
      onError: err => {
        showGeneralError({
          errorData: err,
          errorMessage: t('error_shift_calendar'),
        });
      },
    },
  );

  const registers = useMemo(
    () =>
      infiniteRegisters?.pages
        .flatMap(page => page.data.items)
        .filter(register => register.fullName !== ''),
    [infiniteRegisters],
  );
  const totalRegisters = infiniteRegisters?.pages[0].data.total || 0;
  const currentRegisters = infiniteRegisters?.pages[0].data.count || 0;

  return {
    registers,
    currentUserCount: currentRegisters,
    totalUserCount: totalRegisters,
    totalPages: infiniteRegisters?.pages[0].data.totalPages || undefined,
    isLoadingCollaborators,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  };
};
