import { useMutation } from 'react-query';

import { useModal } from '@material-hu/hooks/useModal';

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

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

import { coursesKeys } from '../../queries';
import { type ColabListItem } from '../../types';

type UseResetProgressModalProps = {
  selectedColab: ColabListItem | null;
  courseName: string;
  courseId: number;
};

const useResetProgressModal = ({
  selectedColab,
  courseName,
  courseId,
}: UseResetProgressModalProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { enqueueSnackbar } = useHuSnackbar();

  const resetProgressMutation = useMutation(
    () => {
      if (!selectedColab) throw new Error();
      return resetCourseProgress(courseId, selectedColab.userId);
    },
    {
      onSuccess: () => {
        closeModal();
        queryClient.invalidateQueries(coursesKeys.detail.reports.all(courseId));
        logEvent(LogEvents.COURSE_RESET_PROGRESS, {
          courseId,
          courseName,
        });
        enqueueSnackbar({
          title: t('reports.reset_progress.success'),
          variant: 'success',
        });
      },
      onError: () => {
        enqueueSnackbar({
          title: t('reports.reset_progress.error'),
          variant: 'error',
        });
      },
    },
  );
  const { modal, showModal, closeModal } = useModal(
    HuDialog,
    { maxWidth: 'sm' },
    {
      title: t('reports.reset_progress.title', {
        colaborator: selectedColab?.name,
      }),
      textBody: t('reports.reset_progress.description', {
        course: courseName,
      }),
      primaryButtonProps: {
        children: t('reports.reset_progress.action'),
        onClick: () => resetProgressMutation.mutate(),
      },
      secondaryButtonProps: {
        children: t('general:cancel'),
        onClick: () => closeModal(),
      },
    },
  );

  return {
    resetProgressModal: modal,
    showResetProgressModal: showModal,
    closeResetProgressModal: closeModal,
  };
};

export default useResetProgressModal;
