import { useInfiniteQuery } from 'react-query';

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

import usePaginatedQueryState from 'src/hooks/usePaginatedQueryState';
import { getPaths } from 'src/pages/dashboard/Learning/Paths/services';
import { type RequestError, type RequestSuccess } from 'src/types/services';

import {
  type SortingOrderType,
  type TableColumnsType,
} from '../../common/types';
import { pathsKeys } from '../queries';
import { type PathsPagination } from '../types';

export type TSuccess = RequestSuccess<typeof getPaths>;
export type TError = RequestError;
export type TData = TSuccess;

const getNextPageParam = (lastPage: TSuccess) => {
  const data = lastPage.data.learningPaths;
  if (data.page === data.totalPages) return undefined;
  return data.page;
};

const useGetLearningPaths = (params: PaginationParams) => {
  const debouncedQuery = useDebounce(params.search);

  const pathPagination: PathsPagination = {
    status: undefined,
    limit: params.pagination.limit,
    search: debouncedQuery,
    order: params.order as SortingOrderType,
    orderBy: params.orderBy as TableColumnsType,
  };

  const infiniteQuery = useInfiniteQuery<TSuccess, TError, TData>({
    queryKey: pathsKeys.paths.list(pathPagination),
    queryFn: ({ pageParam = 0 }) =>
      getPaths({ ...pathPagination, page: pageParam }),
    getNextPageParam,
    keepPreviousData: true,
  });

  const paths =
    infiniteQuery.data?.pages.flatMap(
      page => page?.data?.learningPaths?.items,
    ) || [];

  const firstLearningPathsPage =
    infiniteQuery.data?.pages[0].data.learningPaths;

  const totalCount = firstLearningPathsPage?.count || 0;

  const queryState = usePaginatedQueryState(
    firstLearningPathsPage,
    infiniteQuery.status,
    params.search !== '',
  );

  return {
    ...infiniteQuery,
    totalCount,
    paths,
    queryState,
  };
};

export default useGetLearningPaths;
