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

import { RANKING_PAGE_LIMIT } from 'src/pages/dashboard/acknowledgements/constants';
import { acknowledgementsKeys } from 'src/pages/dashboard/acknowledgements/queries';
import { getAcknowledgementsRanking } from 'src/pages/dashboard/acknowledgements/services';
import { type KudosRankingFiltersState } from 'src/pages/dashboard/acknowledgements/types';
import { formatKudosFilters } from 'src/pages/dashboard/acknowledgements/utils';

type UseGetKudosRankingOptions = {
  enabled?: boolean;
  filters: KudosRankingFiltersState;
};

export const useGetKudosRanking = (options: UseGetKudosRankingOptions) => {
  const { enabled = true, filters } = options;

  const params = formatKudosFilters(filters, RANKING_PAGE_LIMIT);

  const { data, hasNextPage, isFetchingNextPage, isLoading, fetchNextPage } =
    useInfiniteQuery({
      queryKey: acknowledgementsKeys.ranking.filtered(params),
      queryFn: ({ pageParam = 1 }) =>
        getAcknowledgementsRanking({ ...params, page: pageParam }),
      enabled,
      getNextPageParam: (lastPage, allPages) =>
        lastPage.data.length < RANKING_PAGE_LIMIT
          ? undefined
          : allPages.length + 1,
    });

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

  const lastPage = data?.pages?.[data.pages.length - 1];
  const lastPageLength = lastPage?.data?.length ?? 0;
  const showRankingEnd =
    lastPage != null && lastPageLength < RANKING_PAGE_LIMIT;

  return {
    users,
    isLoading,
    hasNextPage,
    isFetchingNextPage,
    fetchNextPage,
    showRankingEnd,
  };
};
