import { useMutation } from 'react-query';

import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { queryClient } from 'src/config/react-query';
import { type RequestError, type RequestSuccess } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { categoriesKeys } from '../queries';
import { updateCategory } from '../services';
import { type UpdateCategoryParams } from '../types';

export type TSuccess = RequestSuccess<typeof updateCategory>;
export type TError = RequestError;
export type TValues = UpdateCategoryParams;

const useUpdateCategory = () => {
  const { enqueueSnackbar } = useHuSnackbar();
  const { t } = useLokaliseTranslation('learning');

  return useMutation<TSuccess, TError, TValues>({
    mutationFn: params => updateCategory(params),
    onSuccess: () => {
      enqueueSnackbar({
        title: t('categories.save.success'),
        variant: 'success',
      });

      queryClient.invalidateQueries(categoriesKeys.list.all());
    },
    onError: () => {
      enqueueSnackbar({
        title: t('categories.save.error'),
        description: t('general:retry_later'),
        variant: 'error',
      });
    },
  });
};

export default useUpdateCategory;
