import { useQuery } from 'react-query';

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

import { useAuth } from 'src/contexts/JWTContext';
import { getQueryParamsAutocompleteUser } from 'src/utils/userUtils';

export const useGetUserList = (
  search: string,
  needSubordinates: boolean,
  needAcknowledgeds: boolean,
) => {
  const debouncedQuery = useDebounce(search);
  const { user } = useAuth();

  const { queryKey, queryFn } = getQueryParamsAutocompleteUser(
    debouncedQuery,
    needSubordinates,
    needAcknowledgeds,
  );

  const { data: dataUser, isLoading: isLoadingDataUser } = useQuery(
    queryKey,
    queryFn,
    {
      staleTime: 60000,
    },
  );

  let data;
  if (needSubordinates) {
    // This is to add the self user because the backend does not return it.
    // Also, the data havent the items array.
    data = dataUser?.data?.concat(user);
  } else {
    data = dataUser?.data?.items;
  }

  const isLoading = isLoadingDataUser;

  return { data, isLoading };
};
