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

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

import { deleteCourse } 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 { coursesKeys } from '../queries';
import { type CourseListItem } from '../types';

export type TData = RequestSuccess<typeof deleteCourse>;
export type TError = RequestError;
export type TValues = CourseListItem;

const useDeleteCourse = (
  options?: UseMutationOptions<TData, TError, TValues>,
) => {
  const { t } = useLokaliseTranslation('learning');
  const { enqueueSnackbar } = useHuSnackbar();
  const queryClient = useQueryClient();

  return useMutation<TData, TError, TValues>(
    course => deleteCourse(course.id),
    {
      ...options,
      onSuccess: (data, course, context) => {
        options?.onSuccess?.(data, course, context);

        queryClient.invalidateQueries(coursesKeys.list.all());

        enqueueSnackbar({
          title: t('course.deleted', { name: course.title }),
          variant: 'success',
        });

        logEvent(LogEvents.COURSE_DELETED, { courseId: course.id });
      },
    },
  );
};

export default useDeleteCourse;
