import { useMutation } from 'react-query';

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

import { editCourseAudience } from 'src/pages/dashboard/Learning/Courses/services';
import { type RequestError, type RequestSuccess } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { formatEditCourseAudienceData } from '../New/utils';
import { type StepsTypes } from '../types';

export type TSuccess = RequestSuccess<typeof editCourseAudience>;
export type TError = RequestError;
export type TValues = {
  courseId: number;
  values: StepsTypes;
};

const useAudienceMutation = () => {
  const { enqueueSnackbar } = useHuSnackbar();
  const { t } = useLokaliseTranslation('learning');

  return useMutation<TSuccess, TError, TValues>(
    ({ courseId, values }) =>
      editCourseAudience(courseId, formatEditCourseAudienceData(values)),
    {
      onError: () => {
        enqueueSnackbar({
          title: t('general:create_segmentation_error'),
          variant: 'error',
        });
      },
    },
  );
};

export default useAudienceMutation;
