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

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

import { editCourseStatus } 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 { throwNoCourseSelected } from '../List/utils';
import { coursesKeys } from '../queries';
import {
  type CourseListItem,
  CourseStatus,
  type EditCourseStatusData,
  NotificationTypes,
} from '../types';

export type TData = RequestSuccess<typeof editCourseStatus>;
export type TError = RequestError;
export type TValues = EditCourseStatusData;

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

  return useMutation<TData, TError, TValues>(
    values => {
      if (!selected?.id) return throwNoCourseSelected();
      return editCourseStatus(selected.id, values);
    },
    {
      ...options,
      onSuccess: (data, values, context) => {
        queryClient.invalidateQueries(coursesKeys.list.all());
        options?.onSuccess?.(data, values, context);

        enqueueSnackbar({
          title: t('course.status_edited', {
            name: selected?.title,
            newStatus:
              values.status === CourseStatus.ACTIVE
                ? t('common.activated')
                : t('common.deactivated'),
          }),
          variant: 'success',
        });

        logEvent(LogEvents.COURSE_STATE_CHANGED, {
          courseId: selected?.id,
          courseState: values.status,
        });

        if (values.sendNotification) {
          logEvent(LogEvents.COURSE_NOTIFICATION_SENT, {
            courseId: selected?.id,
            notificationType: NotificationTypes.ACTIVATE,
          });
        }
      },
    },
  );
};

export default useEditCourseStatus;
