import { useInfiniteQuery } from 'react-query';

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

import useGeneralError from 'src/hooks/useGeneralError';
import { getGroupMembers } from 'src/services/groups';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { groupsKeys } from '../queries';

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

const useInfiniteMembersSearch = (
  {
    groupId,
    search = undefined,
    limit = 20,
    notIncludingIds = [],
    orderBy = undefined,
    order = undefined,
    ids = [],
  }: UseInfiniteMembersSearchParams,
  extraUseQueryParams?: Record<string, any>,
) => {
  const params = {
    groupId,
    search,
    limit,
    notIncludingIds,
    orderBy,
    order,
    ids,
  };
  const debouncedParams = useDebounce(params);
  const showGeneralError = useGeneralError();
  const { t } = useLokaliseTranslation();

  const finalParams = search ? debouncedParams : params; // debounce only when searching
  const query = useInfiniteQuery(
    groupsKeys.searchMember(groupId, finalParams.search || ''),
    ({ pageParam = '' }) =>
      getGroupMembers(groupId, pageParam, finalParams.search),
    {
      getNextPageParam: lastPage => lastPage?.data?.cursor,
      onError: err => {
        showGeneralError(err, t('general:error_loading_members'));
      },
      ...extraUseQueryParams,
    },
  );
  return query;
};

export default useInfiniteMembersSearch;
