import { useQuery } from 'react-query';

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

import { RequestError, RequestSuccess } from 'src/types/services';

import { EMPLOYEE_LIFECYCLE_STALE_TIME } from '../constants';
import { employeeLifecycleKeys } from '../queries';
import { getJourneys } from '../services';
import { JourneysParams } from '../types';

import { useFilterParams } from './useFilterParams';

export type TSuccess = RequestSuccess<typeof getJourneys>;
export type TError = RequestError;
export type TData = TSuccess['data'];

export const useGetJourneys = () => {
  const { filterParams } = useFilterParams();
  const debouncedSearchQuery = useDebounce(filterParams.search);

  const debouncedParams: JourneysParams = {
    search: debouncedSearchQuery,
    progressStatus: filterParams.progressStatus,
  };

  const { data, ...query } = useQuery<TSuccess, TError, TData>({
    queryKey: employeeLifecycleKeys.journeys.list(debouncedParams),
    queryFn: () => getJourneys(debouncedParams),
    select: response => response.data,
    staleTime: EMPLOYEE_LIFECYCLE_STALE_TIME,
  });

  const isDebouncingSearch = filterParams.search !== debouncedSearchQuery;

  return {
    ...query,
    journeys: data || [],
    isLoading: query.isLoading || isDebouncingSearch,
  };
};
