import { jsx, jsxs } from "react/jsx-runtime";
import { memo, useCallback, useContext, useMemo } from "react";
import { ArrayItems, FormLayout } from "@tachybase/components";
import { Schema, SchemaOptionsContext, observer, onFieldValueChange, uid, useField, useFieldSchema } from "@tachybase/schema";
import { ConfigProvider, Space } from "antd";
import lodash from "lodash";
import { useTranslation } from "react-i18next";
import { useAPIClient } from "../../api-client/index.mjs";
import { SchemaInitializerItem, useSchemaInitializerItem } from "../../application/index.mjs";
import { useFormBlockContext } from "../../block-provider/index.mjs";
import { ACLCollectionFieldProvider } from "../../built-in/acl/index.mjs";
import { useCollectionManager_deprecated } from "../../collection-manager/index.mjs";
import { useCollectionManager } from "../../data-source/index.mjs";
import { i18n } from "../../i18n/index.mjs";
import { BlockItem, EditDescription, EditTitle, EditTitleField, FormDialog, FormItem, HTMLEncode, SchemaComponent, SchemaComponentOptions, Select, useCompile, useDesignable } from "../../schema-component/index.mjs";
import { EditCustomDefaultValue, EditFormulaTitleField, GeneralSchemaDesigner, SchemaSettingCollection, SchemaSettingComponent, SchemaSettingsDataScope, SchemaSettingsDivider, SchemaSettingsRemove } from "../../schema-settings/index.mjs";
import { css, cx } from "../../style/index.mjs";
import { useGlobalTheme } from "../../style/theme/index.mjs";
import { gridRowColWrap } from "../utils.mjs";
function _tagged_template_literal(strings, raw) {
    if (!raw) raw = strings.slice(0);
    return Object.freeze(Object.defineProperties(strings, {
        raw: {
            value: Object.freeze(raw)
        }
    }));
}
function _templateObject() {
    const data = _tagged_template_literal([
        "\n          & .ant-space {\n            flex-wrap: wrap;\n          }\n        "
    ]);
    _templateObject = function() {
        return data;
    };
    return data;
}
function _templateObject1() {
    const data = _tagged_template_literal([
        "\n            > .ant-formily-item-label {\n              display: none;\n            }\n          "
    ]);
    _templateObject1 = function() {
        return data;
    };
    return data;
}
const FieldComponentProps = observer((props)=>{
    const { scope, components } = useContext(SchemaOptionsContext);
    const schema = {
        type: 'object',
        properties: {
            options: {
                title: '{{t("Options")}}',
                type: 'array',
                'x-decorator': 'FormItem',
                'x-component': 'ArrayItems',
                items: {
                    type: 'object',
                    properties: {
                        space: {
                            type: 'void',
                            'x-component': 'Space',
                            properties: {
                                sort: {
                                    type: 'void',
                                    'x-decorator': 'FormItem',
                                    'x-component': 'ArrayItems.SortHandle'
                                },
                                label: {
                                    type: 'string',
                                    'x-decorator': 'FormItem',
                                    'x-component': 'Input',
                                    'x-component-props': {
                                        placeholder: '{{t("Option label")}}'
                                    },
                                    required: true
                                },
                                value: {
                                    type: 'string',
                                    'x-decorator': 'FormItem',
                                    'x-component': 'Input',
                                    'x-component-props': {
                                        placeholder: '{{t("Option value")}}'
                                    },
                                    required: true
                                },
                                remove: {
                                    type: 'void',
                                    'x-decorator': 'FormItem',
                                    'x-component': 'ArrayItems.Remove'
                                }
                            }
                        }
                    }
                },
                properties: {
                    add: {
                        type: 'void',
                        title: '{{t("add")}}',
                        'x-component': 'ArrayItems.Addition'
                    }
                }
            }
        }
    };
    return /*#__PURE__*/ jsx(SchemaComponentOptions, {
        scope: {
            ...scope
        },
        components: {
            ArrayItems: ArrayItems,
            FormItem: FormItem,
            Space: Space
        },
        children: /*#__PURE__*/ jsx(SchemaComponent, {
            schema: schema,
            ...props
        })
    });
}, {
    displayName: 'FieldComponentProps'
});
const useFieldComponents = ()=>{
    const { t } = useTranslation();
    const options = [
        {
            label: t('Input'),
            value: 'Input'
        },
        {
            label: t('AutoComplete'),
            value: 'AutoComplete'
        },
        {
            label: t('Select'),
            value: 'Select'
        },
        {
            label: t('AssociationCascader'),
            value: 'AssociationCascader'
        },
        {
            label: t('DatePicker'),
            value: 'DatePicker'
        },
        {
            label: t('Radio group'),
            value: 'Radio.Group'
        },
        {
            label: t('Checkbox group'),
            value: 'Checkbox.Group'
        }
    ];
    return {
        options,
        values: options.map((option)=>option.value)
    };
};
const FilterCustomItemInitializer = /*#__PURE__*/ memo((props)=>{
    const { locale } = useContext(ConfigProvider.ConfigContext);
    const { t } = useTranslation();
    const { scope, components } = useContext(SchemaOptionsContext);
    const { theme } = useGlobalTheme();
    const compile = useCompile();
    const { insert } = props;
    const itemConfig = useSchemaInitializerItem();
    const { getInterface } = useCollectionManager_deprecated();
    const { collections, getCollectionFields } = useCollectionManager_deprecated();
    const allCollection = collections.map((value)=>({
            label: value.title,
            value: value.name
        }));
    const cm = useCollectionManager();
    const { options: fieldComponents, values: fieldComponentValues } = useFieldComponents();
    useAPIClient();
    const handleClick = useCallback(async ()=>{
        var _getInterface_default, _getInterface, _cm_getCollection;
        const values = await FormDialog(t('Add custom field'), ()=>/*#__PURE__*/ jsx(SchemaComponentOptions, {
                scope: {
                    ...scope,
                    useCollectionManager_deprecated: useCollectionManager_deprecated,
                    useAssociationFields (collection) {
                        var _getCollectionFields;
                        var _getCollectionFields_map;
                        return null != (_getCollectionFields_map = null == (_getCollectionFields = getCollectionFields(collection)) ? void 0 : _getCollectionFields.map((field)=>{
                            var _field_uiSchema;
                            return {
                                value: field.name,
                                label: compile(null == (_field_uiSchema = field.uiSchema) ? void 0 : _field_uiSchema.title)
                            };
                        })) ? _getCollectionFields_map : [];
                    }
                },
                components: {
                    ...components,
                    FieldComponentProps,
                    Select: Select
                },
                children: /*#__PURE__*/ jsx(FormLayout, {
                    layout: 'vertical',
                    children: /*#__PURE__*/ jsx(ConfigProvider, {
                        locale: locale,
                        children: /*#__PURE__*/ jsx(SchemaComponent, {
                            schema: {
                                properties: {
                                    name: {
                                        type: 'string',
                                        required: true
                                    },
                                    title: {
                                        type: 'string',
                                        title: t('Field title'),
                                        'x-component': 'Input',
                                        'x-decorator': 'FormItem',
                                        required: true
                                    },
                                    component: {
                                        type: 'string',
                                        title: t('Field component'),
                                        'x-component': 'Select',
                                        'x-decorator': 'FormItem',
                                        required: true,
                                        enum: fieldComponents
                                    },
                                    collection: {
                                        type: 'string',
                                        title: t('Field collection'),
                                        'x-decorator': 'FormItem',
                                        'x-component': 'Select',
                                        enum: allCollection,
                                        description: t('Select a collection field to use metadata of the field'),
                                        'x-visible': false
                                    },
                                    associationField: {
                                        type: 'string',
                                        title: t('Parent Association field'),
                                        'x-decorator': 'FormItem',
                                        'x-component': 'Select',
                                        'x-visible': false,
                                        required: true,
                                        'x-reactions': [
                                            {
                                                dependencies: [
                                                    'collection',
                                                    'component'
                                                ],
                                                fulfill: {
                                                    schema: {
                                                        'x-visible': "{{$deps[0] && $deps[1] === 'AssociationCascader'}}",
                                                        enum: '{{ useAssociationFields($deps[0]) }}'
                                                    }
                                                }
                                            }
                                        ]
                                    },
                                    props: {
                                        type: 'object',
                                        title: t('Component properties'),
                                        'x-decorator': 'FormItem',
                                        'x-component': 'FieldComponentProps',
                                        'x-visible': false,
                                        'x-reactions': [
                                            {
                                                dependencies: [
                                                    'component'
                                                ],
                                                fulfill: {
                                                    schema: {
                                                        'x-visible': "{{$deps[0] === 'Radio.Group' || $deps[0]==='Checkbox.Group'}}"
                                                    }
                                                }
                                            }
                                        ]
                                    }
                                }
                            }
                        })
                    })
                })
            }), theme).open({
            values: {
                name: "f_".concat(uid())
            },
            effects () {
                onFieldValueChange('component', (field)=>{
                    const name = field.value;
                    const collectionComponent = field.query('.collection').take();
                    const propsComponent = field.query('.props').take();
                    if ('Select' === name || 'AutoComplete' === name || 'AssociationCascader' === name) {
                        collectionComponent.setDisplay('visible');
                        collectionComponent.setRequired(true);
                        propsComponent.setDisplay('none');
                        propsComponent.setRequired(false);
                    } else if ('CustomSelect' === name) {
                        collectionComponent.setDisplay('none');
                        collectionComponent.setRequired(false);
                        propsComponent.setDisplay('visible');
                        propsComponent.setRequired(true);
                    } else {
                        collectionComponent.setDisplay('none');
                        collectionComponent.setRequired(false);
                        propsComponent.setDisplay('none');
                        propsComponent.setRequired(false);
                    }
                });
            }
        });
        const { title, component, collection, associationField, props } = values;
        const defaultSchema = (null == (_getInterface = getInterface(component)) ? void 0 : null == (_getInterface_default = _getInterface.default) ? void 0 : _getInterface_default.uiSchema) || {};
        const titleField = null == (_cm_getCollection = cm.getCollection(collection)) ? void 0 : _cm_getCollection.titleField;
        const name = uid();
        const schema = {
            ...defaultSchema,
            type: 'string',
            title: title,
            name: '__custom.' + name,
            required: false,
            'x-component': component,
            'x-toolbar': 'FormItemSchemaToolbar',
            'x-settings': 'fieldSettings:FilterFormCustomSettings',
            'x-decorator': 'FilterFormItem',
            'x-decorator-props': collection,
            'x-component-props': {
                ...defaultSchema['x-component-props'] || {},
                fieldNames: {
                    label: titleField,
                    value: titleField
                },
                associationField,
                collection,
                objectValue: true,
                component: component,
                ...props
            },
            collectionName: collection
        };
        if ('DatePicker' === component) {
            schema['x-settings'] = 'fieldSettings:FilterFormItem';
            schema['x-designer-props'] = {
                interface: 'datetime'
            };
        }
        insert(gridRowColWrap(schema));
    }, [
        theme
    ]);
    return /*#__PURE__*/ jsx(SchemaInitializerItem, {
        ...itemConfig,
        ...props,
        onClick: handleClick
    });
});
const FilterFormItemCustom = ()=>{
    const { insertAdjacent } = useDesignable();
    return /*#__PURE__*/ jsx(FilterCustomItemInitializer, {
        insert: (s)=>insertAdjacent('beforeEnd', s)
    });
};
const FilterItemCustomDesigner = ()=>{
    var _fieldSchema_xcomponentprops_params, _fieldSchema_xcomponentprops;
    const { t } = useTranslation();
    const fieldSchema = useFieldSchema();
    const fieldName = fieldSchema['name'];
    const name = fieldName.includes('__custom') ? fieldSchema['collectionName'] : fieldName;
    const { form } = useFormBlockContext();
    const field = useField();
    const { dn } = useDesignable();
    const component = fieldSchema['x-component'];
    return /*#__PURE__*/ jsxs(GeneralSchemaDesigner, {
        children: [
            /*#__PURE__*/ jsx(EditTitle, {}),
            /*#__PURE__*/ jsx(EditDescription, {}),
            'Input' !== component ? /*#__PURE__*/ jsx(SchemaSettingsDataScope, {
                collectionName: name,
                defaultFilter: (null == fieldSchema ? void 0 : null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : null == (_fieldSchema_xcomponentprops_params = _fieldSchema_xcomponentprops.params) ? void 0 : _fieldSchema_xcomponentprops_params.filter) || {},
                form: form,
                onSubmit: (param)=>{
                    let { filter } = param;
                    var _field_componentProps;
                    lodash.set(field.componentProps, 'params', {
                        ...null == (_field_componentProps = field.componentProps) ? void 0 : _field_componentProps.params,
                        filter
                    });
                    fieldSchema['x-component-props']['params'] = field.componentProps.params;
                    dn.emit('patch', {
                        schema: {
                            ['x-uid']: fieldSchema['x-uid'],
                            'x-component-props': fieldSchema['x-component-props']
                        }
                    });
                }
            }) : null,
            'Select' === component || 'AutoComplete' === component ? /*#__PURE__*/ jsx(SchemaSettingCollection, {}) : null,
            'Select' === component || 'AutoComplete' === component ? /*#__PURE__*/ jsx(SchemaSettingComponent, {}) : null,
            'Select' === component || 'AutoComplete' === component ? /*#__PURE__*/ jsx(EditTitleField, {}) : null,
            'Select' === component || 'AutoComplete' === component ? /*#__PURE__*/ jsx(EditFormulaTitleField, {}) : null,
            /*#__PURE__*/ jsx(EditCustomDefaultValue, {}),
            /*#__PURE__*/ jsx(SchemaSettingsDivider, {}),
            /*#__PURE__*/ jsx(SchemaSettingsRemove, {})
        ]
    });
};
const useCollectionJoinFieldTitle = (name)=>{
    const { getCollection, getCollectionField } = useCollectionManager_deprecated();
    return useMemo(()=>{
        if (!name) return;
        const [collectionName, ...fieldNames] = name.split('.');
        if (!(null == fieldNames ? void 0 : fieldNames.length)) return;
        const collection = getCollection(collectionName);
        let cName = collectionName;
        let field;
        let title = Schema.compile(null == collection ? void 0 : collection.title, {
            t: i18n.t
        });
        while(cName && fieldNames.length > 0){
            var _field_uiSchema;
            const fileName = fieldNames.shift();
            field = getCollectionField("".concat(cName, ".").concat(fileName));
            const fieldTitle = (null == field ? void 0 : null == (_field_uiSchema = field.uiSchema) ? void 0 : _field_uiSchema.title) || (null == field ? void 0 : field.name);
            if (fieldTitle) title += " / ".concat(Schema.compile(fieldTitle, {
                t: i18n.t
            }));
            cName = (null == field ? void 0 : field.target) ? field.target : null;
        }
        return title;
    }, [
        name
    ]);
};
const FilterFormItem = observer((props)=>{
    var _schema_xdecoratorprops;
    const field = useField();
    const schema = useFieldSchema();
    var _schema_xdecoratorprops_showTitle;
    const showTitle = null != (_schema_xdecoratorprops_showTitle = null == (_schema_xdecoratorprops = schema['x-decorator-props']) ? void 0 : _schema_xdecoratorprops.showTitle) ? _schema_xdecoratorprops_showTitle : true;
    const extra = useMemo(()=>'string' == typeof field.description ? /*#__PURE__*/ jsx("div", {
            dangerouslySetInnerHTML: {
                __html: HTMLEncode(field.description).split('\n').join('<br/>')
            }
        }) : field.description, [
        field.description
    ]);
    const className = useMemo(()=>cx(css(_templateObject()), {
            [css(_templateObject1())]: false === showTitle
        }), [
        showTitle
    ]);
    return /*#__PURE__*/ jsx(ACLCollectionFieldProvider, {
        children: /*#__PURE__*/ jsx(BlockItem, {
            className: 'tb-form-item',
            children: /*#__PURE__*/ jsx(FormItem, {
                className: className,
                ...props,
                extra: extra
            })
        })
    });
}, {
    displayName: 'FilterFormItem'
});
export { FilterCustomItemInitializer, FilterFormItem, FilterFormItemCustom, FilterItemCustomDesigner, useCollectionJoinFieldTitle, useFieldComponents };
