import { useMutation } from 'react-query';

import { AxiosError } from 'axios';

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

import useGeneralError from 'src/hooks/useGeneralError';
import {
  AssignShiftParams,
  assignShift,
  ShiftErrorCodes,
} from 'src/services/shifts';
import { ResponseError } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

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

export const useAssignmentMutation = ({
  onSuccessCleanup,
  onConflictError,
  onError,
}: Props) => {
  const { t } = useLokaliseTranslation(['shifts', 'general']);
  const { enqueueSnackbar } = useHuSnackbar();
  const showGeneralError = useGeneralError();

  const { mutate: assignShiftMutation, isLoading: isAssigningShift } =
    useMutation({
      mutationFn: (data: AssignShiftParams) => assignShift(data),
      onSuccess: async (_: unknown, variables: AssignShiftParams) => {
        await invalidateShiftsCalendar();
        if (variables.shift.saveAsTemplate) {
          await invalidateShiftsRepository();
        }
        enqueueSnackbar({
          title: t('actions.assign.success'),
          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
        ) {
          onConflictError?.();
          return;
        }
        showGeneralError(error, t('actions.assign.error'), true, {
          description: t('actions.assign.error_description'),
        });
      },
    });

  return {
    assignShiftMutation,
    isAssigningShift,
  };
};
