import { jsx, jsxs } from "react/jsx-runtime";
import { useLayoutEffect } from "react";
import { useField, useFieldSchema } from "@tachybase/schema";
import { CollectionFieldContext, SortableItem, useCollectionManager_deprecated, useCollection_deprecated, useCompile, useDesigner, useFlag } from "../../../index.mjs";
import { useStyles } from "./Table.Column.ActionBar.mjs";
import { isCollectionFieldComponent } from "./utils.mjs";
const useColumnSchema = ()=>{
    const { getField } = useCollection_deprecated();
    const compile = useCompile();
    const columnSchema = useFieldSchema();
    const { getCollectionJoinField } = useCollectionManager_deprecated();
    const fieldSchema = columnSchema.reduceProperties((buf, s)=>{
        if (isCollectionFieldComponent(s)) return s;
        return buf;
    }, null);
    if (!fieldSchema) return {};
    const collectionField = getField(fieldSchema.name) || getCollectionJoinField(null == fieldSchema ? void 0 : fieldSchema['x-collection-field']);
    return {
        columnSchema,
        fieldSchema,
        collectionField,
        uiSchema: compile(null == collectionField ? void 0 : collectionField.uiSchema)
    };
};
const TableColumnDecorator = (props)=>{
    const Designer = useDesigner();
    const { isInSubTable } = useFlag() || {};
    const { styles } = useStyles({
        margin: isInSubTable ? '-12px -8px' : '-18px -16px',
        padding: isInSubTable ? '12px 8px' : '18px 16px'
    });
    const field = useField();
    const { fieldSchema, uiSchema, collectionField } = useColumnSchema();
    const compile = useCompile();
    useLayoutEffect(()=>{
        if (field.title) return;
        if (!fieldSchema) return;
        if (null == uiSchema ? void 0 : uiSchema.title) field.title = null == uiSchema ? void 0 : uiSchema.title;
    }, [
        null == uiSchema ? void 0 : uiSchema.title
    ]);
    return /*#__PURE__*/ jsx(SortableItem, {
        className: styles.designer,
        children: /*#__PURE__*/ jsxs(CollectionFieldContext.Provider, {
            value: collectionField,
            children: [
                /*#__PURE__*/ jsx(Designer, {
                    fieldSchema: fieldSchema,
                    uiSchema: uiSchema,
                    collectionField: collectionField
                }),
                /*#__PURE__*/ jsx("div", {
                    role: "button",
                    children: (null == field ? void 0 : field.title) || compile(null == uiSchema ? void 0 : uiSchema.title)
                })
            ]
        })
    });
};
export { TableColumnDecorator, useColumnSchema };
