import { useMutation } from 'react-query';
import { matchPath, useLocation } 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 { updateAcknowledgement } from 'src/pages/dashboard/acknowledgements/services';
import { formatAcknowledgementValues } from 'src/pages/dashboard/acknowledgements/utils';
import { updateUserAcknowledgements } from 'src/pages/dashboard/profile/queries';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { type CreateKudosFormValues } from '../components/KudosCreateDrawer/types';
import { acknowledgementsKeys, updateAcknowledgementById } from '../queries';
import { acknowledgementsSkeletonRoutes } from '../routes';

export const useUpdateAcknowledgement = (acknowledgementId?: number) => {
  const { enqueueSnackbar } = useSnackbar();
  const showGeneralError = useGeneralError();
  const location = useLocation();
  const { t } = useLokaliseTranslation('acknowledgements');

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

  return useMutation({
    mutationFn: async (values: CreateKudosFormValues) => {
      if (!acknowledgementId) {
        throw new Error(
          '[useUpdateAcknowledgement] Acknowledgement ID is required',
        );
      }
      const payload = formatAcknowledgementValues(values);
      return updateAcknowledgement(acknowledgementId, payload);
    },
    onSuccess: response => {
      if (!response?.data) return;

      if (isAcknowledgementView) updateAcknowledgementById(response.data);
      else updateUserAcknowledgements(response.data);

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

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