import { jsx } from "react/jsx-runtime";
import react, { useCallback, useContext, useMemo } from "react";
import { FieldContext, FormContext, createForm, merge, onFieldValueChange } from "@tachybase/schema";
import { SchemaComponent } from "../../core/index.mjs";
import { useComponent } from "../../hooks/index.mjs";
import { FilterContext } from "./context.mjs";
const DynamicComponent = (props)=>{
    const { dynamicComponent, disabled } = useContext(FilterContext);
    const component = useComponent(dynamicComponent);
    const form = useMemo(()=>createForm({
            values: {
                value: props.value
            },
            disabled,
            effects () {
                onFieldValueChange('value', (field)=>{
                    var _props_onChange;
                    null == props || null == (_props_onChange = props.onChange) || _props_onChange.call(props, field.value);
                });
            }
        }), [
        JSON.stringify(props.value),
        props.schema
    ]);
    const renderSchemaComponent = useCallback(()=>{
        var _props_schema;
        return /*#__PURE__*/ jsx(FieldContext.Provider, {
            value: null,
            children: /*#__PURE__*/ jsx(SchemaComponent, {
                schema: {
                    'x-component': 'Input',
                    ...props.schema,
                    'x-component-props': merge((null == props ? void 0 : null == (_props_schema = props.schema) ? void 0 : _props_schema['x-component-props']) || {}, {
                        style: {
                            minWidth: 150
                        }
                    }),
                    name: 'value',
                    'x-read-pretty': false,
                    'x-validator': void 0,
                    'x-decorator': void 0
                }
            })
        });
    }, [
        props.schema
    ]);
    return /*#__PURE__*/ jsx(FormContext.Provider, {
        value: form,
        children: component ? /*#__PURE__*/ react.createElement(component, {
            value: props.value,
            collectionField: props.collectionField,
            onChange: null == props ? void 0 : props.onChange,
            renderSchemaComponent
        }) : renderSchemaComponent()
    });
};
export { DynamicComponent };
