import { useInfiniteQuery, useQuery } from 'react-query';

import { secondsToMilliseconds } from 'date-fns';

import { useDebounce } from '@material-hu/hooks/useDebounce';

import { PAGE_SIZE } from '../constants';
import { employeeLifecycleKeys } from '../queries';
import { getMyTeamJourneys } from '../services';

import { GetMyTeamJourneyParams } from '../types';

import { useFilterParams } from './useFilterParams';

export const useGetMyTeamJourneys = () => {
  const { filterParams } = useFilterParams();

  const debouncedSearch = useDebounce(filterParams.search);

  const params: GetMyTeamJourneyParams = {
    offset: PAGE_SIZE,
    limit: PAGE_SIZE,
    search: debouncedSearch,
    progressStatus: filterParams.progressStatus,
  };

  // Used to get the total number of journeys (no pagination)
  const { data: allItems = [] } = useQuery({
    queryKey: employeeLifecycleKeys.myTeamJourneys.allItems(),
    queryFn: () => getMyTeamJourneys(),
    select: data => data.data,
    staleTime: secondsToMilliseconds(120),
  });

  const { data, hasNextPage, isFetchingNextPage, fetchNextPage, ...query } =
    useInfiniteQuery({
      queryKey: employeeLifecycleKeys.myTeamJourneys.list(params),
      queryFn: ({ pageParam }) =>
        getMyTeamJourneys({ ...params, offset: pageParam }),
      getNextPageParam: lastPage =>
        lastPage.data.length === (lastPage.metadata.limit || PAGE_SIZE)
          ? lastPage.metadata.offset + (lastPage.metadata.limit || PAGE_SIZE)
          : null,
      keepPreviousData: true,
    });

  const journeys = data?.pages.flatMap(page => page.data) || [];

  const handleFetchNextPage = () => {
    hasNextPage && !isFetchingNextPage && fetchNextPage();
  };

  return {
    journeys,
    handleFetchNextPage,
    totalCount: allItems.length,
    isFetchingNextPage,
    ...query,
  };
};
