import { useMutation, useQueryClient } from 'react-query';

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

import { useLokaliseTranslation } from 'src/utils/i18n';

import { librariesKeys } from '../queries';
import { updateArticleStatus } from '../services';
import { type Article, ArticleStatus } from '../types';

type UpdateArticleStatusVars = {
  article: Article;
  rootId?: number;
  status: ArticleStatus;
};

export const useUpdateArticleStatus = () => {
  const { t } = useLokaliseTranslation('libraries');
  const { enqueueSnackbar } = useSnackbar();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ article, status }: UpdateArticleStatusVars) =>
      updateArticleStatus(article.id, {
        status,
        sendNotification: article.notify ?? false,
        notificationType: article.notificationType,
      }),
    onSuccess: (_, { article, rootId, status }) => {
      queryClient.invalidateQueries(librariesKeys.article.byId(article.id));

      if (article.parentId) {
        queryClient.invalidateQueries(
          librariesKeys.article.byId(article.parentId),
        );
      }

      if (rootId) {
        queryClient.invalidateQueries(
          librariesKeys.article.childrenTree(rootId),
        );
      } else {
        queryClient.invalidateQueries(librariesKeys.article.rootList());
      }

      const isActivating = status === ArticleStatus.ENABLED;

      enqueueSnackbar({
        variant: 'success',
        title: isActivating
          ? t('article.activate.success')
          : t('article.deactivate.success'),
      });
    },
  });
};
