import { jsx } from "react/jsx-runtime";
import { useCallback, useMemo } from "react";
import { useField, useFieldSchema } from "@tachybase/schema";
import { ArrayCollapse, FormLayout } from "@tego/client";
import { createStyles } from "antd-style";
import lodash from "lodash";
import { useTranslation } from "react-i18next";
import { FormProvider, SchemaComponent, useActionContext, useCollectionManager_deprecated, useCollection_deprecated, useDesignable, useRecord } from "../index.mjs";
import { useFormBlockContext, useTableBlockContext } from "../block-provider/index.mjs";
import { useCollectionFilterOptionsV2 } from "../collection-manager/action-hooks.mjs";
import { FlagProvider, useFlag } from "../flag-provider/index.mjs";
import { useLocalVariables, useVariables } from "../variables/index.mjs";
import { isVariable } from "../variables/utils/isVariable.mjs";
import { SchemaSettingsModalItem, findParentFieldSchema, getFieldDefaultValue } from "./SchemaSettings.mjs";
import { formatVariableScop } from "./VariableInput/utils/formatVariableScop.mjs";
import { VariableInput, getShouldChange } from "./VariableInput/VariableInput.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      & > .tb-form-item {\n        flex: 1;\n      }\n    "
    ]);
    _templateObject = function() {
        return data;
    };
    return data;
}
const useStyles = createStyles((param)=>{
    let { css } = param;
    return {
        defaultInput: css(_templateObject())
    };
});
const SchemaSettingsDefaultValue = function(props) {
    var _actionCtx_fieldSchema;
    const { styles } = useStyles();
    const currentSchema = useFieldSchema();
    var _props_fieldSchema;
    const fieldSchema = null != (_props_fieldSchema = null == props ? void 0 : props.fieldSchema) ? _props_fieldSchema : currentSchema;
    const field = useField();
    const { dn } = useDesignable();
    const { t } = useTranslation();
    const actionCtx = useActionContext();
    let targetField;
    const { getField } = useCollection_deprecated();
    const { getCollectionJoinField, getCollectionFields, getAllCollectionsInheritChain } = useCollectionManager_deprecated();
    const variables = useVariables();
    const localVariables = useLocalVariables();
    const collection = useCollection_deprecated();
    const record = useRecord();
    const { form } = useFormBlockContext();
    const { getFields } = useCollectionFilterOptionsV2(collection);
    const { isInSubForm, isInSubTable } = useFlag() || {};
    const { name } = collection;
    const collectionField = useMemo(()=>getField(fieldSchema['name']) || getCollectionJoinField(fieldSchema['x-collection-field']), [
        fieldSchema,
        getCollectionJoinField,
        getField
    ]);
    const fieldSchemaWithoutRequired = lodash.omit(fieldSchema, 'required');
    if (null == collectionField ? void 0 : collectionField.target) {
        var _fieldSchema_xcomponentprops_fieldNames, _fieldSchema_xcomponentprops;
        targetField = getCollectionJoinField("".concat(collectionField.target, ".").concat((null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : null == (_fieldSchema_xcomponentprops_fieldNames = _fieldSchema_xcomponentprops.fieldNames) ? void 0 : _fieldSchema_xcomponentprops_fieldNames.label) || 'id'));
    }
    const parentFieldSchema = (null == collectionField ? void 0 : collectionField.interface) === 'm2o' && findParentFieldSchema(fieldSchema);
    const parentCollectionField = parentFieldSchema && getCollectionJoinField(null == parentFieldSchema ? void 0 : parentFieldSchema['x-collection-field']);
    const tableCtx = useTableBlockContext();
    const isAllowContextVariable = (null == actionCtx ? void 0 : null == (_actionCtx_fieldSchema = actionCtx.fieldSchema) ? void 0 : _actionCtx_fieldSchema['x-action']) === 'customize:create' && ((null == collectionField ? void 0 : collectionField.interface) === 'm2m' || (null == parentCollectionField ? void 0 : parentCollectionField.type) === 'hasMany' && (null == collectionField ? void 0 : collectionField.interface) === 'm2o');
    const returnScope = useCallback((scope)=>{
        const currentForm = scope.find((item)=>'$nForm' === item.value);
        const fields = getCollectionFields(name);
        if (!(null == fields ? void 0 : fields.length) && currentForm) currentForm.children = formatVariableScop(getFields());
        return scope;
    }, [
        getFields,
        name
    ]);
    const DefaultValueComponent = useMemo(()=>({
            ArrayCollapse: ArrayCollapse,
            FormLayout: FormLayout,
            VariableInput: (props)=>/*#__PURE__*/ jsx(FlagProvider, {
                    isInSubForm: isInSubForm,
                    isInSubTable: isInSubTable,
                    isInSetDefaultValueDialog: true,
                    collectionField: collectionField,
                    children: /*#__PURE__*/ jsx(VariableInput, {
                        ...props
                    })
                })
        }), [
        isInSubForm,
        isInSubTable
    ]);
    const schema = useMemo(()=>({
            type: 'object',
            title: t('Set default value'),
            properties: {
                default: {
                    'x-decorator': 'FormItem',
                    'x-component': 'VariableInput',
                    'x-component-props': {
                        ...null == fieldSchema ? void 0 : fieldSchema['x-component-props'],
                        collectionField,
                        contextCollectionName: isAllowContextVariable && tableCtx.collection,
                        schema: null == collectionField ? void 0 : collectionField.uiSchema,
                        targetFieldSchema: fieldSchema,
                        className: styles.defaultInput,
                        form,
                        record,
                        returnScope,
                        shouldChange: getShouldChange({
                            collectionField,
                            variables,
                            localVariables,
                            getAllCollectionsInheritChain
                        }),
                        renderSchemaComponent: function(props) {
                            const s = lodash.cloneDeep(fieldSchemaWithoutRequired) || {};
                            s.title = '';
                            s.name = 'default';
                            s['x-read-pretty'] = false;
                            s['x-disabled'] = false;
                            const defaultValue = getFieldDefaultValue(s, collectionField);
                            if (collectionField.target && s['x-component-props']) s['x-component-props'].mode = 'Select';
                            if (null == collectionField ? void 0 : collectionField.uiSchema.type) s.type = collectionField.uiSchema.type;
                            if ((null == collectionField ? void 0 : collectionField.uiSchema['x-component']) === 'Checkbox') {
                                lodash.set(s, 'x-component-props.defaultChecked', defaultValue);
                                s.type = 'void';
                            }
                            const schema = {
                                ...s,
                                'x-decorator': 'FormItem',
                                'x-component-props': {
                                    ...s['x-component-props'],
                                    collectionName: null == collectionField ? void 0 : collectionField.collectionName,
                                    targetField,
                                    onChange: props.onChange,
                                    defaultValue: isVariable(defaultValue) ? '' : defaultValue,
                                    style: {
                                        width: '100%',
                                        verticalAlign: 'top',
                                        minWidth: '200px'
                                    }
                                },
                                default: isVariable(defaultValue) ? '' : defaultValue
                            };
                            return /*#__PURE__*/ jsx(FormProvider, {
                                children: /*#__PURE__*/ jsx(SchemaComponent, {
                                    schema: schema
                                })
                            });
                        }
                    },
                    title: t('Default value'),
                    default: getFieldDefaultValue(fieldSchema, collectionField)
                }
            }
        }), [
        collectionField,
        fieldSchema,
        fieldSchemaWithoutRequired,
        form,
        getAllCollectionsInheritChain,
        isAllowContextVariable,
        localVariables,
        record,
        returnScope,
        t,
        tableCtx.collection,
        targetField,
        variables,
        styles
    ]);
    const handleSubmit = useCallback((v)=>{
        const schema = {
            ['x-uid']: fieldSchema['x-uid']
        };
        v.default = v.default || null;
        field.value = v.default;
        fieldSchema.default = v.default;
        if (!v.default && 0 !== v.default) field.value = null;
        schema.default = v.default;
        dn.emit('patch', {
            schema,
            currentSchema
        });
    }, [
        currentSchema,
        dn,
        field,
        fieldSchema
    ]);
    return /*#__PURE__*/ jsx(SchemaSettingsModalItem, {
        title: t('Set default value'),
        components: DefaultValueComponent,
        width: 800,
        schema: schema,
        onSubmit: handleSubmit
    });
};
export { SchemaSettingsDefaultValue };
