import { type MouseEvent } from 'react';
import { useFormContext } from 'react-hook-form';
import { useMatch, useNavigate } from 'react-router-dom';

import { newCourseFields } from 'src/pages/dashboard/Learning/Courses/New/forms';
import {
  getCourseFunnel,
  validateDraft,
  validateStep,
} from 'src/pages/dashboard/Learning/Courses/New/utils';
import { coursesRoutes } from 'src/pages/dashboard/Learning/Courses/routes';
import {
  Steps,
  type StepsTypes,
} from 'src/pages/dashboard/Learning/Courses/types';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';

import BasicModal from 'src/components/BasicModal';

enum CONTEXT {
  EDIT = 'edit',
  INVALID = 'invalid',
  DRAFT = 'draft',
  EMPTY = 'empty',
}

const getContext = (isEdit: boolean, values: StepsTypes) => {
  if (isEdit) return CONTEXT.EDIT;
  if (!validateStep(Steps.BASIC_INFORMATION, values, true))
    return CONTEXT.EMPTY;
  if (!validateDraft(values)) return CONTEXT.INVALID;
  return CONTEXT.DRAFT;
};

export type CloseModalProps = {
  onClose: (event: MouseEvent<HTMLButtonElement>) => void;
  onSave: (callback: Function) => void;
  loading?: boolean;
  stepId: Steps;
};

export const CloseModal = ({
  onClose,
  onSave,
  loading = false,
  stepId,
}: CloseModalProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { getValues, watch, setFocus } = useFormContext();
  const navigate = useNavigate();

  const values = watch() as StepsTypes;

  const isEdit = !!useMatch(coursesRoutes.editCourse());
  const isDuplicate = !!useMatch(coursesRoutes.duplicateCourse());

  const context = getContext(isEdit, values);

  const handleCancel = () => {
    const courseName = getValues(newCourseFields.basicInformation.title());
    logEvent(LogEvents.NEW_COURSE_EXIT, {
      courseName,
      courseStep: stepId,
      courseFunnel: getCourseFunnel(isEdit, isDuplicate),
    });

    navigate(-1);
  };

  const handleSaveCallback = (event: MouseEvent<HTMLButtonElement>) => {
    onClose(event);
    handleCancel();
  };

  const handleKeepEditing = (event: MouseEvent<HTMLButtonElement>) => {
    if (context === CONTEXT.EMPTY) {
      onClose(event);
      setFocus(newCourseFields.basicInformation.title());
    }

    if (context === CONTEXT.EDIT || context === CONTEXT.INVALID) onClose(event);
    if (context === CONTEXT.DRAFT) onSave(handleSaveCallback);
  };

  return (
    <BasicModal
      Icon={null}
      title={t('general:unsaved_changes_title')}
      body={t(`course.close_creation_modal.${context}`)}
      buttonColor="primary"
      primaryButtonProps={{
        id: 'keep-editing-course-button',
        children: t(`course.close_creation_modal.action.${context}`),
        onClick: handleKeepEditing,
        loading,
      }}
      secondaryButtonProps={{
        id: 'close-editing-course-button',
        variant: 'text',
        children: t('general:exit_without_saving'),
        disabled: loading,
        onClick: handleCancel,
      }}
    />
  );
};

export default CloseModal;
