import { a as __awaiter } from './tslib.es6-es.js';
import React__default, { forwardRef, useEffect, useImperativeHandle } from 'react';
import { useForm, FormProvider } from 'react-hook-form';

const Form = forwardRef(function InternalForm({ onSubmit, children, onStateChange }, ref) {
    const methods = useForm({
        mode: "onTouched",
    });
    const { trigger, handleSubmit, formState: { isDirty, isValid }, } = methods;
    useEffect(() => onStateChange && onStateChange({ isDirty, isValid }), [isDirty, isValid]);
    useImperativeHandle(ref, () => ({
        /**
         * The `trigger()` method can also accept an array
         * of fields to validate. We may at some point want
         * to consider adding a `validate()` method to the
         * `Form` component.
         */
        submit: () => __awaiter(this, void 0, void 0, function* () {
            const valid = yield trigger(undefined, { shouldFocus: true });
            if (valid) {
                submitHandler();
            }
        }),
    }));
    /**
     * If an onSubmit is not passed into a form, it will only be used
     * for validation. For that, we do not need to wrap it in a <form>
     * tag. This allows the <Form> component to be used in legacy code.
     */
    const Wrapper = onSubmit ? "form" : "div";
    const formProps = {
        onSubmit: onSubmit && handleSubmit(submitHandler),
    };
    return (React__default.createElement(FormProvider, Object.assign({}, methods),
        React__default.createElement(Wrapper, Object.assign({}, formProps, { "data-testid": "atlantis-form" }), children)));
    function submitHandler() {
        onSubmit && onSubmit();
    }
});

export { Form as F };
