import { useMutation } from 'react-query';

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

import { logEvent } from 'src/config/logging';
import { queryClient } from 'src/config/react-query';
import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import { createAcknowledgement } from 'src/pages/dashboard/acknowledgements/services';
import { formatAcknowledgementValues } from 'src/pages/dashboard/acknowledgements/utils';
import { EventName } from 'src/types/amplitude';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

export const useCreateAcknowledgement = () => {
  const { user } = useAuth();
  const { enqueueSnackbar } = useSnackbar();
  const showGeneralError = useGeneralError();
  const { t } = useLokaliseTranslation('acknowledgements');

  return useMutation({
    mutationFn: async (values: CreateKudosFormValues) => {
      if (!user?.id) {
        throw new Error('[useCreateAcknowledgement] User ID is required');
      }
      const payload = formatAcknowledgementValues(values);
      return createAcknowledgement(payload);
    },
    onSuccess: response => {
      if (!response?.data) return;

      const created = response.data;

      addAcknowledgementInListAcknowledgements(created);
      queryClient.invalidateQueries(acknowledgementsKeys.ranking.all());
      queryClient.invalidateQueries(acknowledgementsKeys.categories.active());

      if (created.category) {
        logEvent(EventName.ACKNOW_GIVE, {
          userIds: (created.acknowledgeds ?? [])
            .map(acknowledged => acknowledged.id)
            .join(', '),
          acknowledgementCategoryId: created.category.id,
          points: created.category.points,
        });
      }

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