import { Fragment, jsx } from "react/jsx-runtime";
import { createContext, useContext, useMemo } from "react";
import { useFieldSchema } from "@tachybase/schema";
import { useCollection, useCollectionManager } from "../collection/index.mjs";
import { CollectionDeletedPlaceholder } from "../components/CollectionDeletedPlaceholder.mjs";
const CollectionFieldContext = /*#__PURE__*/ createContext(null);
CollectionFieldContext.displayName = 'CollectionFieldContext';
const CollectionFieldProvider = (props)=>{
    const { name, children, allowNull } = props;
    const fieldSchema = useFieldSchema();
    const collection = useCollection();
    const collectionManager = useCollectionManager();
    const value = useMemo(()=>{
        var _fieldSchema_xcomponentprops;
        if (!collection) return null;
        const field = null == fieldSchema ? void 0 : null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops['field'];
        return collectionManager.getCollectionField(null == fieldSchema ? void 0 : fieldSchema['x-collection-field']) || field || collection.getField((null == field ? void 0 : field.name) || name);
    }, [
        collection,
        fieldSchema,
        name,
        collectionManager
    ]);
    if (!value && allowNull) return /*#__PURE__*/ jsx(Fragment, {
        children: children
    });
    if (!value) return /*#__PURE__*/ jsx(CollectionDeletedPlaceholder, {
        type: "Field",
        name: name
    });
    return /*#__PURE__*/ jsx(CollectionFieldContext.Provider, {
        value: value,
        children: children
    });
};
const useCollectionField = ()=>{
    const context = useContext(CollectionFieldContext);
    return context;
};
export { CollectionFieldContext, CollectionFieldProvider, useCollectionField };
