import { useMutation } from 'react-query';

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

import { queryClient } from 'src/config/react-query';
import { forceCourseCompletion } from 'src/pages/dashboard/Learning/Courses/services';
import { type ColabStatus } from 'src/pages/dashboard/Learning/Courses/types';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';

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

type UseForceCompletionProps = {
  courseId: number;
  courseName: string;
};

type MutationVariables = {
  userId: number;
  previousStatus: ColabStatus;
};

const useForceCompletion = ({
  courseId,
  courseName,
}: UseForceCompletionProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { enqueueSnackbar } = useHuSnackbar();

  return useMutation({
    mutationFn: ({ userId }: MutationVariables) =>
      forceCourseCompletion(courseId, userId),
    onSuccess: (_data, { userId, previousStatus }) => {
      queryClient.invalidateQueries(coursesKeys.detail.reports.all(courseId));
      logEvent(LogEvents.COURSE_FORCE_COMPLETE, {
        courseId,
        courseName,
        previousStatus,
        userId,
      });
      enqueueSnackbar({
        title: t('reports.force_completion.success'),
        variant: 'success',
      });
    },
    onError: () => {
      enqueueSnackbar({
        title: t('reports.force_completion.error'),
        variant: 'error',
      });
    },
  });
};

export default useForceCompletion;
