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

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

import { sendCourseSurvey } from 'src/services/courses';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { coursesKeys } from '../queries';
import { type Course, type SurveyFormData } from '../types';

const useSendSatisfactionSurvey = (course: Course | undefined) => {
  const { enqueueSnackbar } = useHuSnackbar();
  const { t } = useLokaliseTranslation('learning');
  const queryClient = useQueryClient();

  const courseId = course?.id ?? '';

  return useMutation(
    (formData: SurveyFormData) => sendCourseSurvey(courseId, formData),
    {
      onSuccess: () => {
        enqueueSnackbar({
          title: t('course.satisfaction_survey.success.title'),
          variant: 'success',
        });
        queryClient.invalidateQueries(coursesKeys.detail.course(courseId));
        queryClient.invalidateQueries(coursesKeys.detail.survey(courseId));
      },
      onError: () => {
        enqueueSnackbar({
          title: t('course.satisfaction_survey.error.title'),
          variant: 'error',
        });
      },
    },
  );
};

export default useSendSatisfactionSurvey;
