import { __assign } from "tslib";
import { jsxs as _jsxs } from "react/jsx-runtime";
import { useFieldSet, FormProvider, } from './formulr';
import { defaultRenderError, useFormChild, } from './shared';
import { useImperativeHandle } from 'react';
import { useObservableEagerState } from 'observable-hooks';
export function FieldSet(props) {
    var _a = props, scrollAnchorRef = _a.scrollAnchorRef, _b = _a.renderError, renderError = _b === void 0 ? defaultRenderError : _b, validators = _a.validators, modelRef = _a.modelRef;
    var name = props.name;
    var rawModel = props.model;
    var _c = useFieldSet((name !== null && name !== void 0 ? name : rawModel), validators), ctx = _c[0], model = _c[1];
    if (isFieldSetViewDrivenProps(props)) {
        var normalizeBeforeSubmit = props.normalizeBeforeSubmit, destroyOnUnmount = props.destroyOnUnmount;
        model.destroyOnUnmount = Boolean(destroyOnUnmount);
        if (normalizeBeforeSubmit) {
            model.normalizeBeforeSubmit = normalizeBeforeSubmit;
        }
    }
    useImperativeHandle(modelRef, function () { return model; }, [model]);
    useFormChild(model, scrollAnchorRef);
    useObservableEagerState(model.error$);
    return (_jsxs(FormProvider, __assign({ value: ctx }, { children: [props.children, renderError(model.error)] }), void 0));
}
function isFieldSetViewDrivenProps(props) {
    return props.name !== undefined;
}
