"use strict";
// The require scope
var __webpack_require__ = {};
/************************************************************************/ // webpack/runtime/compat_get_default_export
(()=>{
    // getDefaultExport function for compatibility with non-ESM modules
    __webpack_require__.n = function(module) {
        var getter = module && module.__esModule ? function() {
            return module['default'];
        } : function() {
            return module;
        };
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
// webpack/runtime/define_property_getters
(()=>{
    __webpack_require__.d = function(exports1, definition) {
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
// webpack/runtime/has_own_property
(()=>{
    __webpack_require__.o = function(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    };
})();
// webpack/runtime/make_namespace_object
(()=>{
    // define __esModule on exports
    __webpack_require__.r = function(exports1) {
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
/************************************************************************/ var __webpack_exports__ = {};
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
    default: ()=>/* binding */ Form_rslib_entry_
});
const external_react_namespaceObject = require("react");
var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
const react_namespaceObject = require("@chakra-ui/react");
const external_react_hook_form_namespaceObject = require("react-hook-form");
const devtools_namespaceObject = require("@hookform/devtools");
const yup_namespaceObject = require("@hookform/resolvers/yup");
const external_yup_namespaceObject = require("yup");
const useReactHookForm_js_namespaceObject = require("../../hooks/useReactHookForm.js");
var useReactHookForm_js_default = /*#__PURE__*/ __webpack_require__.n(useReactHookForm_js_namespaceObject);
const FormField_js_namespaceObject = require("../FormField/FormField.js");
var FormField_js_default = /*#__PURE__*/ __webpack_require__.n(FormField_js_namespaceObject);
const NumberInput_js_namespaceObject = require("../Inputs/NumberInput/NumberInput.js");
var NumberInput_js_default = /*#__PURE__*/ __webpack_require__.n(NumberInput_js_namespaceObject);
const RadioGroup_js_namespaceObject = require("../Inputs/RadioGroup/RadioGroup.js");
var RadioGroup_js_default = /*#__PURE__*/ __webpack_require__.n(RadioGroup_js_namespaceObject);
const Select_js_namespaceObject = require("../Inputs/Select/Select.js");
var Select_js_default = /*#__PURE__*/ __webpack_require__.n(Select_js_namespaceObject);
const RPSlider_js_namespaceObject = require("../Inputs/Slider/RPSlider.js");
var RPSlider_js_default = /*#__PURE__*/ __webpack_require__.n(RPSlider_js_namespaceObject);
const ColumnSelect_js_namespaceObject = require("../Inputs/ColumnSelect/ColumnSelect.js");
var ColumnSelect_js_default = /*#__PURE__*/ __webpack_require__.n(ColumnSelect_js_namespaceObject);
const Button_js_namespaceObject = require("../Button/Button.js");
var Button_js_default = /*#__PURE__*/ __webpack_require__.n(Button_js_namespaceObject);
const PasswordInput_js_namespaceObject = require("../Inputs/PasswordInput/PasswordInput.js");
var PasswordInput_js_default = /*#__PURE__*/ __webpack_require__.n(PasswordInput_js_namespaceObject);
// Create an array of objects, based on the provided CustomFields, later used
// to transform into Yup validation schema.
// Note: This function is recursive to support nested fields, such as those
// in a `CustomFormSection`.
//
// Previously, with tuples, it made it difficult to flatten the array, (since
// TS tuples are really just arrays. Instead, we now use objects to better flatten
// the array and then map over those objects to create the schema.
function generateValidationSchemaObject(fields) {
    let schema = fields.filter((field)=>'displaySection' !== field.fieldType).map((field)=>{
        if ('custom' === field.fieldType && 'fields' in field) return generateValidationSchemaObject(field.fields);
        return {
            name: field.name,
            schema: field.schema
        };
    });
    return schema.flat();
}
// Create an array of initial/default values for Yup based on the provided
// CustomFields.
// Note: This function is recursive to support nested fields, such as those
// in a `CustomFormSection`.
function generateInitialValuesObject(fields) {
    const initialValues = fields.filter((field)=>'displaySection' !== field.fieldType).map((field)=>{
        if ('custom' === field.fieldType && 'fields' in field) return generateInitialValuesObject(field.fields);
        if ('select' !== field.fieldType || !field.defaultValue) return {
            name: field.name,
            defaultValue: field.defaultValue
        };
        {
            const selectField = field;
            return {
                name: selectField.name,
                defaultValue: selectField.isMulti ? selectField.defaultValue : selectField.defaultValue.value
            };
        }
    });
    return initialValues.flat();
}
function Form({ onValid, onInvalid, fields, button, autofocus, mode, developerView, isDisabled, isFetching, actions, onInvalidFormValidation }) {
    // generate initial schemas (validation and default values)
    const filteredFields = fields.filter((field)=>!field.hide);
    const initialSchemaValues = Object.fromEntries(generateInitialValuesObject(filteredFields).map((fieldObj)=>[
            fieldObj.name,
            fieldObj.defaultValue
        ]));
    const schema = Object.fromEntries(generateValidationSchemaObject(filteredFields).map((fieldObj)=>[
            fieldObj.name,
            fieldObj.schema
        ]));
    const validationSchema = external_yup_namespaceObject.object().shape(schema);
    // used for custom form sections so the validation context can be passed to
    // custom validators for that section
    const [validationContext, setValidationContext] = (0, external_react_namespaceObject.useState)({});
    // Focus
    const inputRef = (0, external_react_namespaceObject.useRef)();
    (0, external_react_namespaceObject.useEffect)(()=>{
        if (autofocus && inputRef) inputRef.current?.focus();
    }, [
        inputRef,
        autofocus
    ]);
    const { formValues, setFormMethods } = useReactHookForm_js_default()();
    const defaultValues = formValues && Object.entries(formValues).length > 0 ? {
        ...initialSchemaValues,
        ...formValues
    } : initialSchemaValues;
    // Form management
    const formMethods = (0, external_react_hook_form_namespaceObject.useForm)({
        mode: mode || 'all',
        defaultValues,
        resolver: (0, yup_namespaceObject.yupResolver)(validationSchema),
        context: validationContext
    });
    (0, external_react_namespaceObject.useEffect)(()=>{
        setFormMethods(formMethods);
    }, []);
    const { register, handleSubmit, setValue, control, formState: { isSubmitting, errors } } = formMethods;
    const isFormDisabled = isSubmitting || isDisabled || isFetching;
    const isFormSubmissionDisabled = isFormDisabled || Object.keys(errors).length > 0;
    (0, external_react_namespaceObject.useEffect)(()=>{
        if (isFormSubmissionDisabled && void 0 !== onInvalidFormValidation) onInvalidFormValidation();
    }, [
        isFormSubmissionDisabled
    ]);
    const allActions = /*#__PURE__*/ external_react_default().createElement(external_react_default().Fragment, null, /*#__PURE__*/ external_react_default().createElement(Button_js_default(), {
        variant: button.variant ?? 'brand',
        "aria-label": button.label,
        "data-testid": button.label,
        type: "submit",
        isLoading: isSubmitting || isFetching,
        isDisabled: isFormSubmissionDisabled
    }, button.text), actions);
    const mapFields = (fields)=>{
        const mappedFields = fields.map(({ label, columns, help, description, footerDescription, tooltip, heading, showRequiredIndicator, ...field })=>{
            if ('displaySection' === field.fieldType) return /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Box, {
                key: field.name
            }, heading && /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Heading, {
                as: "h5",
                size: "md"
            }, heading), description && /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Text, null, description));
            // TODO: expand repeater to build out form structure in an automated
            // way similar to the other form fields
            if ('repeater' === field.fieldType) return /*#__PURE__*/ external_react_default().createElement(external_react_default().Fragment, null);
            if ('custom' === field.fieldType) {
                let f = field;
                return /*#__PURE__*/ external_react_default().createElement(f.component, {
                    form: formMethods,
                    setValidationContext: setValidationContext,
                    key: field.name
                });
            }
            return /*#__PURE__*/ external_react_default().createElement(external_react_namespaceObject.Fragment, {
                key: field.name
            }, /*#__PURE__*/ external_react_default().createElement(FormField_js_default(), {
                description: description,
                footerDescription: footerDescription,
                tooltip: tooltip,
                isRequired: 'hidden' !== field.fieldType && false !== field.isRequired,
                isDisabled: field.isDisabled || isFormDisabled,
                key: field.name,
                hidden: 'hidden' === field.fieldType,
                style: columns && {
                    gridColumn: `span ${columns}`
                },
                label: label,
                isInvalid: !!errors[field.name],
                errorText: errors[field.name]?.message,
                helpText: help,
                showRequiredIndicator: showRequiredIndicator
            }, {
                text: /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Input, {
                    "data-testid": `${field.name}_field`,
                    placeholder: field.placeholder,
                    pattern: field.pattern,
                    type: field.inputMode,
                    ...register(field.name)
                }),
                password: /*#__PURE__*/ external_react_default().createElement(external_react_hook_form_namespaceObject.Controller, {
                    name: field.name,
                    control: control,
                    render: ({ field: renderField })=>{
                        /**
                         * Ref has to be excluded due to a limitation of the components
                         * Chakra implementation is using function components where ref cannot be provided
                         */ const { ref, ...rest } = renderField;
                        const passwordField = field;
                        return /*#__PURE__*/ external_react_default().createElement(PasswordInput_js_default(), {
                            ...rest,
                            name: passwordField.name,
                            placeholder: passwordField.placeholder,
                            pattern: passwordField.pattern,
                            type: passwordField.inputMode,
                            defaultShowPassword: passwordField.defaultShowPassword,
                            showEyeIndicator: passwordField.showEyeIndicator
                        });
                    }
                }),
                toggle: /*#__PURE__*/ external_react_default().createElement(external_react_hook_form_namespaceObject.Controller, {
                    name: field.name,
                    control: control,
                    render: ({ field: renderField })=>{
                        const toggleField = field;
                        return /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Box, {
                            "data-testid": `${toggleField.name}_field`
                        }, /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Switch, {
                            ...renderField,
                            defaultChecked: 'true' === toggleField.defaultValue
                        }));
                    }
                }),
                hidden: /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Input, {
                    "data-testid": `${field.name}_field`,
                    hidden: true,
                    type: "none",
                    ...register(field.name)
                }),
                number: /*#__PURE__*/ external_react_default().createElement(external_react_hook_form_namespaceObject.Controller, {
                    name: field.name,
                    control: control,
                    render: ({ field: renderField })=>{
                        /**
                         * Ref has to be excluded due to a limitation of the components
                         * Chakra implementation is using function components where ref cannot be provided
                         */ const { ref, ...rest } = renderField;
                        const numberField = field;
                        return /*#__PURE__*/ external_react_default().createElement(NumberInput_js_default(), {
                            ...rest,
                            name: numberField.name,
                            min: numberField.min,
                            max: numberField.max,
                            step: numberField.step,
                            placeholder: numberField.placeholder
                        });
                    }
                }),
                radio: /*#__PURE__*/ external_react_default().createElement(external_react_hook_form_namespaceObject.Controller, {
                    name: field.name,
                    control: control,
                    render: ({ field: renderField })=>{
                        const { ref, ...rest } = renderField;
                        const radioField = field;
                        if ('circle' === radioField.radioVariant) return /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Box, {
                            "data-testid": `${field.name}_field`,
                            mt: 2
                        }, /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.RadioGroup, {
                            ...rest,
                            defaultValue: field.defaultValue,
                            onChange: (nextValue)=>{
                                setValue(radioField.name, nextValue);
                                setFormMethods(formMethods);
                            }
                        }, /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Stack, {
                            direction: radioField.radioStackDirection
                        }, radioField.options.map(({ label, value, disabled, invalid, ...otherOptionProps })=>/*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Radio, {
                                key: `${value}`,
                                value: `${value}`,
                                isDisabled: disabled,
                                isInvalid: invalid,
                                ...otherOptionProps
                            }, /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Text, {
                                "aria-invalid": invalid,
                                _invalid: {
                                    textColor: 'red.500',
                                    borderColor: 'red.500'
                                }
                            }, label))))));
                        return /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Box, {
                            "data-testid": `${field.name}_field`
                        }, /*#__PURE__*/ external_react_default().createElement(RadioGroup_js_default(), {
                            ...rest,
                            isAttached: radioField.isAttached,
                            options: radioField.options || [],
                            defaultValue: radioField.defaultValue,
                            onChange: (nextValue)=>{
                                setValue(radioField.name, nextValue);
                                setFormMethods(formMethods);
                            }
                        }));
                    }
                }),
                select: /*#__PURE__*/ external_react_default().createElement(external_react_hook_form_namespaceObject.Controller, {
                    name: field.name,
                    control: control,
                    render: ({ field: renderField })=>{
                        const { ref, ...rest } = renderField;
                        const selectField = field;
                        return /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Box, {
                            "data-testid": `${selectField.name}_field`
                        }, /*#__PURE__*/ external_react_default().createElement(Select_js_default(), {
                            menuPlacement: "auto",
                            ...rest,
                            innerRef: selectField.innerRef,
                            placeholder: selectField.placeholder,
                            isLoading: selectField.isLoading,
                            isMulti: selectField.isMulti,
                            options: selectField.options,
                            defaultValue: selectField.defaultValue,
                            onChange: (nextValue)=>{
                                setValue(selectField.name, nextValue);
                                setFormMethods(formMethods);
                            }
                        }));
                    }
                }),
                columnSelect: /*#__PURE__*/ external_react_default().createElement(external_react_hook_form_namespaceObject.Controller, {
                    name: field.name,
                    control: control,
                    render: ({ field: renderField })=>{
                        const { ref, ...rest } = renderField;
                        const columnSelectField = field;
                        return /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Box, {
                            "data-testid": `${columnSelectField.name}_field`
                        }, /*#__PURE__*/ external_react_default().createElement(ColumnSelect_js_default(), {
                            menuPlacement: "auto",
                            ...rest,
                            innerRef: columnSelectField.innerRef,
                            placeholder: columnSelectField.placeholder,
                            isLoading: columnSelectField.isLoading,
                            options: columnSelectField.options,
                            defaultValue: columnSelectField.defaultValue,
                            firstTextPosition: columnSelectField.firstTextPosition,
                            headerColumns: columnSelectField.headerColumns,
                            footer: columnSelectField.footer,
                            singleValueText: columnSelectField.singleValueText,
                            onChange: (nextValue)=>{
                                setValue(columnSelectField.name, nextValue);
                                setFormMethods(formMethods);
                            }
                        }));
                    }
                }),
                textarea: /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Textarea, {
                    ...register(field.name),
                    "data-testid": `${field.name}_field`,
                    placeholder: field.placeholder
                }),
                slider: /*#__PURE__*/ external_react_default().createElement(external_react_hook_form_namespaceObject.Controller, {
                    name: field.name,
                    control: control,
                    render: ({ field: renderField })=>{
                        const { ref, ...rest } = renderField;
                        const sliderField = field;
                        const { fieldType, ...sliderRest } = sliderField;
                        return /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Box, {
                            "data-testid": `${sliderField.name}_field`
                        }, /*#__PURE__*/ external_react_default().createElement(RPSlider_js_default(), {
                            ...sliderRest,
                            ...rest,
                            onChange: (nextValue)=>{
                                setValue(sliderField.name, nextValue);
                                setFormMethods(formMethods);
                            }
                        }));
                    }
                }),
                displaySection: /*#__PURE__*/ external_react_default().createElement(external_react_default().Fragment, null),
                checkbox: /*#__PURE__*/ external_react_default().createElement(external_react_hook_form_namespaceObject.Controller, {
                    name: field.name,
                    control: control,
                    render: ({ field: renderField })=>{
                        const checkboxField = field;
                        return /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Box, {
                            "data-testid": `${checkboxField.name}_field`
                        }, /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Checkbox, renderField, checkboxField.text));
                    }
                })
            }[field.fieldType || 'text']));
        });
        return mappedFields.flat();
    };
    return /*#__PURE__*/ external_react_default().createElement(external_react_default().Fragment, null, /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.chakra.form, {
        onChange: ()=>setFormMethods(formMethods),
        onSubmit: handleSubmit(onValid, onInvalid)
    }, /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.chakra.fieldset, null, /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.VStack, {
        alignItems: "left",
        gap: 6
    }, mapFields(fields), button.spanFullWidth ? allActions : /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.Box, null, /*#__PURE__*/ external_react_default().createElement(react_namespaceObject.ButtonGroup, null, allActions))))), developerView ? /*#__PURE__*/ external_react_default().createElement(devtools_namespaceObject.DevTool, {
        control: control
    }) : null);
}
/* ESM default export */ const Form_rslib_entry_ = Form;
var __webpack_export_target__ = exports;
for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
    value: true
});
