import { useMutation } from 'react-query';
import { useNavigate } from 'react-router';

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

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

import { formatCreateCourseData, getNotificationType } from '../New/utils';
import { coursesKeys } from '../queries';
import { coursesRoutes } from '../routes';
import { CourseStatus, type StepsTypes } from '../types';

import useAudienceMutation from './useAudienceMutation';
import useCourseStatus from './useCourseStatus';

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

const useEditFullCourse = () => {
  const navigate = useNavigate();
  const { isEdit, isDraftEdit, isDuplicate } = useCourseStatus();
  const { enqueueSnackbar } = useHuSnackbar();
  const { t } = useLokaliseTranslation('learning');

  const audienceMutation = useAudienceMutation();

  return useMutation<TSuccess, TError, TValues>(
    async ({ courseId, values, prevValues }) => {
      const payload = await formatCreateCourseData(values, prevValues);
      return editCourse(courseId, payload);
    },
    {
      onSuccess: async (response, payload) => {
        const courseId = response.data.id;
        const prevCourseStatus = payload.prevValues?.basicInformation.status;

        queryClient.setQueryData(coursesKeys.detail.course(courseId), response);

        // We only update the audience if the course in new and is being activated
        // If its an edit, the audience is updated before this step
        if (prevCourseStatus !== CourseStatus.ACTIVE) {
          await audienceMutation.mutateAsync({
            courseId,
            values: payload.values,
          });
        }

        enqueueSnackbar({
          title: t(isEdit ? 'course.edited' : 'course.created', {
            name: payload.values.basicInformation.title,
          }),
          variant: 'success',
        });

        logEvent(LogEvents.COURSE_NOTIFICATION_SENT, {
          courseId,
          notificationType: getNotificationType(isEdit, isDuplicate),
        });

        logEvent(
          isEdit || isDraftEdit
            ? LogEvents.COURSE_EDITED
            : LogEvents.NEW_COURSE_CREATED,
          { courseId },
        );

        navigate(coursesRoutes.base());
      },
    },
  );
};

export default useEditFullCourse;
