import { useInfiniteQuery } from 'react-query';

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

import usePaginatedQueryState from 'src/hooks/usePaginatedQueryState';
import { getSessions } from 'src/pages/dashboard/Learning/Sessions/services';
import { sToMs } from 'src/utils/timeUtils';

import { TABLE_PAGE_SIZE } from '../constants';
import { sessionsKeys } from '../queries';
import { type SessionsPaginationParams } from '../types';

export const useGetSessions = (search: string) => {
  const debouncedSearch = useDebounce(search);

  const params: SessionsPaginationParams = {
    page: 1,
    limit: TABLE_PAGE_SIZE,
    q: debouncedSearch || null,
  };

  const { data, hasNextPage, isFetchingNextPage, fetchNextPage, ...query } =
    useInfiniteQuery({
      queryKey: sessionsKeys.sessions.list(debouncedSearch),
      queryFn: ({ pageParam = 1 }) =>
        getSessions({ ...params, page: pageParam }),
      getNextPageParam: lastPage => {
        const lastPageData = lastPage.data;
        return lastPageData.page === lastPageData.totalPages
          ? undefined
          : lastPageData.page + 1;
      },
      keepPreviousData: true,
      staleTime: sToMs(60),
    });

  const sessions = data?.pages.flatMap(page => page.data.items) || [];
  const firstSessionsPage = data?.pages[0].data;

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

  const queryState = usePaginatedQueryState(
    firstSessionsPage,
    query.status,
    debouncedSearch !== '',
  );

  return {
    sessions,
    handleFetchNextPage,
    isFetchingNextPage,
    totalCount: data?.pages[0].data.count ?? 0,
    queryState,
    ...query,
  };
};
