import { useFormikContext } from 'formik';
import React, { useState } from 'react';
import { noop } from '../../../helpers/utils';
import { NavigationAPI, useReactRouterPause } from '../../../hooks';
import { handleNavigationAttempt } from './handleNavigationAttempt';

interface SaveOnNavigateProps {
  /** If set to true, will prevent form submission when navigating away. (default: false) */
  isSubmitting?: boolean;
  /** Callback that will be called when a navigation attempt was cancelled */
  onNavigationCancelled?: () => void;
}

/**
 * Performs logic to keep user on the page if form is not valid, as well as saving valid forms on navigation.
 */
export const SaveOnNavigate: React.FC<SaveOnNavigateProps> = ({
  isSubmitting = false,
  onNavigationCancelled = noop,
}) => {
  const { dirty, isValid, submitForm } = useFormikContext();
  const [canSubmit, setCanSubmit] = useState<boolean>(true);

  useReactRouterPause(
    {
      handler: (navigation: NavigationAPI) =>
        handleNavigationAttempt(
          navigation,
          dirty,
          isValid,
          submitForm,
          isSubmitting,
          canSubmit,
          setCanSubmit,
          onNavigationCancelled,
        ),
    },
    dirty,
  );

  return null;
};
