import { MouseEventHandler } from 'react';
import classNames from 'classnames';
import { useFormikContext } from 'formik';
import SubmitFormButton from './SubmitFormButton';
import { FormDefaults } from './FormDefaults';

export interface StandardFormActionsProps {
  /** Allow the form to be submitted without any changes. By default this is not allowed. */
  allowPristineSubmit?: boolean;
  /** The cancel button's `onClick`.
   * @defaultValue `window.history.back()`
   */
  handleCancel?: MouseEventHandler<HTMLButtonElement>;
}

/** Standard submit and cancel buttons. */
export default function StandardFormActions({
  allowPristineSubmit,
  handleCancel,
}: StandardFormActionsProps) {
  const { isSubmitting } = useFormikContext();

  return (
    <>
      <SubmitFormButton allowPristineSubmit={allowPristineSubmit} />
      &nbsp;
      <button
        className={classNames(
          FormDefaults.cssClassPrefix + 'standard-form-actions-cancel-button'
        )}
        type="button"
        disabled={isSubmitting}
        onClick={handleCancel || goBack}>
        Cancel
      </button>
    </>
  );
  function goBack() {
    window.history.back();
  }
}
