import { useMutation, useQueryClient } from 'react-query';

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

import { fillCalibration } from 'src/pages/dashboard/performance/services';
import { type FillCalibrationBody } from 'src/pages/dashboard/performance/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

type UseFillCalibrationParams = {
  cycleId: string | number;
  formReviewId: number;
  onSuccess?: () => void;
};

const useFillCalibration = ({
  cycleId,
  formReviewId,
  onSuccess,
}: UseFillCalibrationParams) => {
  const queryClient = useQueryClient();
  const { enqueueSnackbar } = useSnackbar();
  const { t } = useLokaliseTranslation(['performance']);

  return useMutation(
    (body: FillCalibrationBody) => fillCalibration(cycleId, formReviewId, body),
    {
      onSuccess: () => {
        queryClient.invalidateQueries(performanceKeys.calibrations(cycleId));
        queryClient.invalidateQueries(
          performanceKeys.calibrationsSidebar(cycleId),
        );
        queryClient.invalidateQueries(
          performanceKeys.calibrationDetail(cycleId, formReviewId),
        );
        queryClient.invalidateQueries(performanceKeys.cycle(cycleId));
        enqueueSnackbar({
          title: t('performance:calibration.detail.success'),
          variant: 'success',
        });
        onSuccess?.();
      },
      onError: () => {
        enqueueSnackbar({
          title: t('performance:calibration.detail.error.generic'),
          variant: 'error',
        });
      },
    },
  );
};

export default useFillCalibration;
