import { useMutation } from 'react-query';
import { matchPath, useLocation, useNavigate } from 'react-router-dom';

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

import { queryClient } from 'src/config/react-query';
import useGeneralError from 'src/hooks/useGeneralError';
import { deleteAcknowledgement } from 'src/pages/dashboard/acknowledgements/services';
import { type Acknowledgement } from 'src/pages/dashboard/acknowledgements/types';
import { removeUserAcknowledgement } from 'src/pages/dashboard/profile/queries';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { acknowledgementsKeys, removeAcknowledgement } from '../queries';
import {
  acknowledgementsRoutes,
  acknowledgementsSkeletonRoutes,
} from '../routes';

const PATH = acknowledgementsSkeletonRoutes.acknowledgements();

export const useDeleteAcknowledgement = () => {
  const { enqueueSnackbar } = useSnackbar();
  const showGeneralError = useGeneralError();
  const location = useLocation();
  const navigate = useNavigate();
  const { t } = useLokaliseTranslation('acknowledgements');

  const isAcknowledgementView = !!matchPath(
    { path: PATH, end: false },
    location.pathname,
  );

  return useMutation({
    mutationFn: (acknowledgement: Acknowledgement) =>
      deleteAcknowledgement(acknowledgement.id),
    onSuccess: (_, acknowledgement) => {
      if (isAcknowledgementView) {
        removeAcknowledgement(acknowledgement.id);
        navigate(acknowledgementsRoutes.acknowledgements());
        queryClient.removeQueries(
          acknowledgementsKeys.detail(acknowledgement.id),
        );
      } else {
        removeUserAcknowledgement(acknowledgement);
      }

      queryClient.invalidateQueries(acknowledgementsKeys.ranking.all());

      enqueueSnackbar({
        title: t('success_delete_acknowledgement'),
        variant: 'success',
      });
    },
    onError: err => {
      showGeneralError(err, t('error_delete_acknowledgement'));
    },
  });
};
