import { useMutation } from 'react-query';

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

import useGeneralError from 'src/hooks/useGeneralError';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

export type UseCommentEnableDisableConfig = {
  id: number;
  enableService: (id: number, enabled: boolean) => Promise<any>;
  onSuccess: (enabled: boolean) => void;
};

export const useCommentEnableDisable = ({
  id,
  enableService,
  onSuccess,
}: UseCommentEnableDisableConfig) => {
  const { enqueueSnackbar } = useHuSnackbar();
  const { t } = useTranslation();
  const showGeneralError = useGeneralError();

  const disabledComment = useMutation(() => enableService(id, false), {
    onSuccess: () => {
      onSuccess(false);
      enqueueSnackbar({
        title: t('post:deactivated_post_comments'),
        variant: 'success',
      });
    },
    onError: err => {
      showGeneralError(err, t('post:error_disable_comment'));
    },
  });

  const enableComment = useMutation(() => enableService(id, true), {
    onSuccess: () => {
      onSuccess(true);
      enqueueSnackbar({
        title: t('post:success_enable_comment'),
        variant: 'success',
      });
    },
    onError: err => {
      showGeneralError(err, t('post:error_enable_comment'));
    },
  });

  const handleDisableComment = () => disabledComment.mutate();
  const handleEnableComment = () => enableComment.mutate();

  return {
    handleDisableComment,
    handleEnableComment,
    isDisabling: disabledComment.isLoading,
    isEnabling: enableComment.isLoading,
  };
};
