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

import Stack from '@material-hu/mui/Stack';

import useUnsavedWarning from 'src/hooks/useUnsavedWarning';
import { LearningUnsavedDialog } from 'src/pages/dashboard/Learning/common/components/LearningUnsavedDialog';
import { pathsRoutes } from 'src/pages/dashboard/Learning/Paths/routes';
import { type NewPathFormValues } from 'src/pages/dashboard/Learning/Paths/types';
import { LogEvents, logEvent, NewExitAction } from 'src/utils/logging';

import { useCreatePath } from '../../../hooks/useCreatePath';
import { useNewPathStepper } from '../../../hooks/useNewPathStepper';
import PathNewFooter from '../PathNewFooter';
import PathNewHeader from '../PathNewHeader';
import PathNewMain from '../PathNewMain';

type PathFormProps = {
  loadingPath: boolean;
  pathRef: MutableRefObject<NewPathFormValues | null>;
};

const PathForm = ({ loadingPath, pathRef }: PathFormProps) => {
  const { control, formState } = useFormContext<NewPathFormValues>();
  const { currentStep } = useNewPathStepper();
  const isNew = !!useMatch(pathsRoutes.new());

  const pathId = useWatch({
    control,
    name: 'basic_information.id',
  });

  const { handleSaveOnClose, handleNextStep, publishPathDialog, isLoading } =
    useCreatePath(pathId, pathRef);

  const { modal: unsavedWarningModal } = useUnsavedWarning(
    props => (
      <LearningUnsavedDialog
        {...props}
        loading={isLoading}
        onSave={handleSaveOnClose}
        onExit={() => {
          logEvent(LogEvents.NEW_PATH_EXIT, {
            pathId,
            pathStep: currentStep.id,
            pathFunnel: isNew ? NewExitAction.creation : NewExitAction.edition,
          });
        }}
      />
    ),
    !formState.isDirty || formState.isSubmitted,
  );

  return (
    <Stack
      sx={{ height: '100vh' }}
      component="form"
    >
      {unsavedWarningModal}
      {publishPathDialog}
      <PathNewHeader />
      <PathNewMain loadingPath={loadingPath} />
      <PathNewFooter
        loading={isLoading}
        onNextStep={handleNextStep}
      />
    </Stack>
  );
};

export default PathForm;
