import { useState } from 'react';
import { useInfiniteQuery } from 'react-query';

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

import useGeneralError from 'src/hooks/useGeneralError';
import { getFormsAvailable, getFormsCompleted } from 'src/services/forms';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getNextPage, getListItemsLength } from 'src/utils/pagination';

import { formKeys } from 'src/components/dashboard/form/queries';

export const useForm = () => {
  const showGeneralError = useGeneralError();
  const [query, setQuery] = useState<string>('');
  const debouncedQuery = useDebounce(query);

  const { t } = useLokaliseTranslation('forms');

  const formsAvailable = (type, limit) =>
    useInfiniteQuery(
      formKeys.listAvailable(type, debouncedQuery),
      ({ pageParam = 1 }) =>
        getFormsAvailable(type, debouncedQuery, pageParam, limit),
      {
        getNextPageParam: (lastPage, pages) =>
          getNextPage(getListItemsLength(pages), limit, pages),
        onError: err => showGeneralError(err, t('ERROR_GET_FORMS')),
      },
    );

  const formsCompleted = (userId, type, limit) =>
    useInfiniteQuery(
      formKeys.listCompleted(type, debouncedQuery),
      ({ pageParam = 1 }) =>
        getFormsCompleted(userId, type, debouncedQuery, pageParam, limit),
      {
        getNextPageParam: (lastPage, pages) =>
          getNextPage(getListItemsLength(pages), limit, pages),
        onError: err => showGeneralError(err, t('ERROR_GET_FORMS')),
      },
    );

  return {
    formsAvailable,
    formsCompleted,
    query,
    setQuery,
  };
};

export default useForm;
