import { useQuery } from 'react-query';

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

import {
  type PaginatedQueryStates,
  usePaginatedQueryState,
} from 'src/hooks/usePaginatedQueryState';
import { getPaths } from 'src/pages/dashboard/learning/paths/services';
import { type RequestError, type RequestSuccess } from 'src/types/services';

import { pathsKeys } from '../queries';
import { type PathStatus } from '../types';

export type PathsPaginatedQueryStates = PaginatedQueryStates;

export type TSuccess = RequestSuccess<typeof getPaths>;
export type TError = RequestError;
export type TData = TSuccess['data']['learningPaths'];
export type TParams = PaginationParams & {
  status: PathStatus;
};

export const useGetPaths = ({ search, pagination, ...rest }: TParams) => {
  const debouncedSearch = useDebounce(search);

  const debouncedParams = {
    ...pagination,
    ...rest,
    search: debouncedSearch,
  };

  const pathsQuery = useQuery<TSuccess, TError, TData>(
    pathsKeys.list.paginated(debouncedParams),
    () => getPaths(debouncedParams),
    {
      select: response => response.data.learningPaths,
      keepPreviousData: true,
    },
  );

  const isFiltered = search?.length > 0;

  const queryState = usePaginatedQueryState(
    pathsQuery.data,
    pathsQuery.status,
    isFiltered,
  );

  return {
    ...pathsQuery,
    ...queryState,
    isFiltered,
  };
};
