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 { type RequestError, type RequestSuccess } from 'src/types/services';
import {
  getNextPageParam,
  infiniteQueryDataParser,
} from 'src/utils/pagination';
import { sToMs } from 'src/utils/timeUtils';

import { TABLE_PAGE_SIZE } from '../constants';
import { learningCertificatesKeys } from '../queries';
import { listLearningCertificates } from '../services';
import { type ListLearningCertificatesParams } from '../types';
import { toBackendOrderBy } from '../utils';

export type TSuccess = RequestSuccess<typeof listLearningCertificates>;
export type TError = RequestError;

export const useGetLearningCertificates = (params: PaginationParams) => {
  const debouncedSearch = useDebounce(params.search);

  const baseParams: ListLearningCertificatesParams = {
    page: 1,
    limit: TABLE_PAGE_SIZE,
    q: debouncedSearch || null,
    orderBy: toBackendOrderBy({
      orderBy: params.orderBy,
      order: params.order,
    }),
  };

  const { data, hasNextPage, isFetchingNextPage, fetchNextPage, ...query } =
    useInfiniteQuery({
      queryKey: learningCertificatesKeys.list.paginated(baseParams),
      queryFn: ({ pageParam = 1 }) =>
        listLearningCertificates({ ...baseParams, page: pageParam }),
      getNextPageParam,
      keepPreviousData: true,
      staleTime: sToMs(60),
    });

  const certificates = infiniteQueryDataParser(data);
  const firstPage = data?.pages[0]?.data;

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

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

  return {
    certificates,
    handleFetchNextPage,
    isFetchingNextPage,
    totalCount: firstPage?.count ?? 0,
    queryState,
    ...query,
  };
};
