import { useInfiniteQuery } from 'react-query';

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

import { profileKeys } from 'src/pages/dashboard/profile/queries';
import { getUserList } from 'src/services/users';

type UseInfiniteUsersPublicSearchParams = {
  search?: string;
  limit?: number;
  notIncludingIds?: number[];
  orderBy?: string;
  order?: string;
  ids?: string[];
  status?: string;
};

const useInfiniteUsersPublicSearch = (
  {
    search = undefined,
    limit = 20,
    notIncludingIds = [],
    orderBy = undefined,
    order = undefined,
    ids = [],
    status = undefined,
  }: UseInfiniteUsersPublicSearchParams,
  extraUseQueryParams?: Record<string, any>,
) => {
  const params = {
    search,
    limit,
    notIncludingIds,
    orderBy,
    order,
    ids,
    status,
  };
  const debouncedParams = useDebounce(params);
  const finalParams = search ? debouncedParams : params; // debounce only when searching
  const query = useInfiniteQuery(
    profileKeys.userList(finalParams.search ?? '', finalParams.status),
    ({ pageParam = 1 }) =>
      getUserList(
        finalParams.search ?? '',
        pageParam,
        30,
        true,
        notIncludingIds,
        orderBy,
        order,
        status,
      ),
    {
      getNextPageParam: lastPage =>
        lastPage.data.page < lastPage.data.totalPages
          ? lastPage.data.page + 1
          : undefined,
      keepPreviousData: true,
      ...extraUseQueryParams,
    },
  );
  return query;
};

export default useInfiniteUsersPublicSearch;
