import { type UseMutationOptions, useMutation } from 'react-query';

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

import { logEvent } from 'src/config/logging';
import useGeneralError from 'src/hooks/useGeneralError';
import { EventName } from 'src/types/amplitude';
import { type RequestError, type RequestSuccess } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { deleteArticle } from '../services';
import { type Article, ArticleErrors } from '../types';
import { invalidateSidebarArticles } from '../utils';

type TSuccess = RequestSuccess<typeof deleteArticle>;
type TError = RequestError;
type TOptions = UseMutationOptions<TSuccess, TError, Article>;

export const useDeleteArticle = (
  parentId?: number | null,
  options: TOptions = {},
) => {
  const { t } = useLokaliseTranslation('libraries');
  const { enqueueSnackbar } = useSnackbar();
  const showGeneralError = useGeneralError();

  return useMutation<TSuccess, TError, Article>({
    mutationFn: (article: Article) => deleteArticle(article.id),
    ...options,
    onSuccess: (response, article, ...rest) => {
      options.onSuccess?.(response, article, ...rest);
      enqueueSnackbar({
        title: t('article.delete.success'),
        variant: 'success',
      });
      logEvent(EventName.LIBRARY_DELETE, {
        libraryId: article.id,
        parentId: article.parentId,
        title: article.title,
      });
      invalidateSidebarArticles(parentId ?? undefined);
    },
    onError: (err, ...args) => {
      options.onError?.(err, ...args);
      if (err.response?.data?.code === ArticleErrors.DELETE_WITH_CHILDREN) {
        enqueueSnackbar({
          title: t('library.delete.error.children'),
          variant: 'error',
        });
        return;
      }
      showGeneralError(err);
    },
  });
};
