import { jsx, jsxs } from "react/jsx-runtime";
import react, { createContext, useContext, useEffect, useMemo, useRef } from "react";
import { RecursionField, createForm, useField, useFieldSchema } from "@tachybase/schema";
import { Spin } from "antd";
import { withDynamicSchemaProps } from "../application/hoc/withDynamicSchemaProps.mjs";
import { useCollectionManager, useCollectionParentRecordData, useCollectionRecord } from "../data-source/index.mjs";
import { RecordProvider, useRecord } from "../record-provider/index.mjs";
import { useActionContext, useDesignable } from "../schema-component/index.mjs";
import { Templates } from "../schema-component/antd/form-v2/Templates.mjs";
import { BlockProvider, useBlockRequestContext } from "./BlockProvider.mjs";
import { FormActiveFieldsProvider } from "./hooks/useFormActiveFields.mjs";
const FormBlockContext = /*#__PURE__*/ createContext({});
FormBlockContext.displayName = 'FormBlockContext';
const InternalFormBlockProvider = (props)=>{
    var _Object_keys, _record_parentRecord;
    const cm = useCollectionManager();
    const ctx = useFormBlockContext();
    const { action, readPretty, params, collection, association } = props;
    const field = useField();
    const form = useMemo(()=>createForm({
            readPretty
        }), [
        readPretty
    ]);
    const { resource, service, updateAssociationValues } = useBlockRequestContext();
    const formBlockRef = useRef();
    const record = useCollectionRecord();
    const formBlockValue = useMemo(()=>{
        var _cm_getCollectionField;
        return {
            ...ctx,
            params,
            action,
            form,
            type: 'get' === action ? 'update' : 'create',
            field,
            service,
            resource,
            updateAssociationValues,
            formBlockRef,
            collectionName: collection || (null == (_cm_getCollectionField = cm.getCollectionField(association)) ? void 0 : _cm_getCollectionField.target),
            formRecord: record
        };
    }, [
        action,
        association,
        cm,
        collection,
        ctx,
        field,
        form,
        params,
        record,
        resource,
        service,
        updateAssociationValues
    ]);
    if (service.loading && (null == (_Object_keys = Object.keys(null == form ? void 0 : form.initialValues)) ? void 0 : _Object_keys.length) === 0 && action) return /*#__PURE__*/ jsx(Spin, {});
    return /*#__PURE__*/ jsx(FormBlockContext.Provider, {
        value: formBlockValue,
        children: /*#__PURE__*/ jsx(RecordProvider, {
            isNew: null == record ? void 0 : record.isNew,
            parent: null == record ? void 0 : null == (_record_parentRecord = record.parentRecord) ? void 0 : _record_parentRecord.data,
            record: null == record ? void 0 : record.data,
            children: /*#__PURE__*/ jsx("div", {
                ref: formBlockRef,
                children: /*#__PURE__*/ jsx(RenderChildrenWithDataTemplates, {
                    form: form
                })
            })
        })
    });
};
const useFormBlockType = ()=>{
    const ctx = useFormBlockContext() || {};
    const res = useMemo(()=>({
            type: ctx.type
        }), [
        ctx.type
    ]);
    return res;
};
const useIsDetailBlock = ()=>{
    const ctx = useFormBlockContext();
    const { fieldSchema } = useActionContext();
    return 'create' !== ctx.type && (null == fieldSchema ? void 0 : fieldSchema['x-acl-action']) !== 'create' && (null == fieldSchema ? void 0 : fieldSchema['x-action']) !== 'create';
};
const FormBlockProvider = withDynamicSchemaProps((props)=>{
    const parentRecordData = useCollectionParentRecordData();
    const { parentRecord } = props;
    return /*#__PURE__*/ jsx(BlockProvider, {
        name: props.name || 'form',
        ...props,
        block: 'form',
        parentRecord: parentRecord || parentRecordData,
        children: /*#__PURE__*/ jsx(FormActiveFieldsProvider, {
            name: "form",
            children: /*#__PURE__*/ jsx(InternalFormBlockProvider, {
                ...props
            })
        })
    });
});
const useFormBlockContext = ()=>useContext(FormBlockContext);
const useFormBlockProps = function() {
    arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
    var _fieldSchema_xcomponentprops, _ctx_service;
    const ctx = useFormBlockContext();
    const record = useRecord();
    const { fieldSchema } = useActionContext();
    const addChild = null == fieldSchema ? void 0 : null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.addChild;
    useEffect(()=>{
        if (addChild) {
            var _ctx_form;
            null == (_ctx_form = ctx.form) || _ctx_form.query('parent').take((field)=>{
                field.disabled = true;
                field.value = new Proxy({
                    ...null == record ? void 0 : record.__parent
                }, {});
            });
        }
    });
    useEffect(()=>{
        var _ctx_service;
        if (!(null == ctx ? void 0 : null == (_ctx_service = ctx.service) ? void 0 : _ctx_service.loading)) {
            var _ctx_service_data, _ctx_service1, _ctx_form;
            null == (_ctx_form = ctx.form) || _ctx_form.setInitialValues(null == (_ctx_service1 = ctx.service) ? void 0 : null == (_ctx_service_data = _ctx_service1.data) ? void 0 : _ctx_service_data.data);
        }
    }, [
        null == ctx ? void 0 : null == (_ctx_service = ctx.service) ? void 0 : _ctx_service.loading
    ]);
    return {
        form: ctx.form
    };
};
const RenderChildrenWithDataTemplates = (param)=>{
    let { form } = param;
    var _field_component;
    const FieldSchema = useFieldSchema();
    const { findComponent } = useDesignable();
    const field = useField();
    const Component = findComponent(null == (_field_component = field.component) ? void 0 : _field_component[0]) || react.Fragment;
    return /*#__PURE__*/ jsxs(Component, {
        ...field.componentProps,
        children: [
            /*#__PURE__*/ jsx(Templates, {
                style: {
                    marginBottom: 18
                },
                form: form
            }),
            /*#__PURE__*/ jsx(RecursionField, {
                schema: FieldSchema,
                onlyRenderProperties: true
            })
        ]
    });
};
const findFormBlock = (schema)=>{
    while(schema){
        if ('FormBlockProvider' === schema['x-decorator']) return schema;
        schema = schema.parent;
    }
    return null;
};
export { FormBlockContext, FormBlockProvider, findFormBlock, useFormBlockContext, useFormBlockProps, useFormBlockType, useIsDetailBlock };
