import { useMutation } from 'react-query';

import { type AxiosError } from 'axios';

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

import { assignShiftRotation, ShiftErrorCodes } from 'src/services/shifts';
import { type ResponseError } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { invalidateShiftsCalendar } from '../queries';

type Props = {
  onSuccessCleanup?: () => void;
  onError?: () => void;
};

export const useAssignTemplateMutation = ({
  onSuccessCleanup,
  onError,
}: Props) => {
  const { t } = useLokaliseTranslation('shifts');
  const { enqueueSnackbar } = useHuSnackbar();

  const { mutate: assignTemplateMutation, isLoading: isAssigningTemplate } =
    useMutation({
      mutationFn: ({
        id,
        userIds,
        startDate,
      }: {
        id: string;
        userIds: number[];
        startDate: string;
        templateName: string;
      }) => assignShiftRotation(id, { userIds, startDate }),
      onSuccess: async (_, variables) => {
        await invalidateShiftsCalendar();
        enqueueSnackbar({
          title: t('templates.feedback.success_assign_count', {
            count: variables.userIds.length,
            templateName: variables.templateName,
          }),
          variant: 'success',
        });
        onSuccessCleanup?.();
      },
      onError: (error: AxiosError<ResponseError>) => {
        onError?.();
        if (
          error.response?.data.code ===
            ShiftErrorCodes.SHIFT_MANAGEMENT_REST_SHIFT_OVERLAP ||
          error.response?.data.code ===
            ShiftErrorCodes.SHIFT_MANAGEMENT_INVALID_TIME_SLOTS
        ) {
          enqueueSnackbar({
            title: t('templates.feedback.error_assign_conflict'),
            description: t(
              'templates.feedback.error_assign_conflict_description',
            ),
            variant: 'error',
          });
          return;
        }
        enqueueSnackbar({
          title: t('templates.feedback.error_assign'),
          description: t('actions.try_again'),
          variant: 'error',
        });
      },
    });

  return { assignTemplateMutation, isAssigningTemplate };
};
