import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ from "react/jsx-runtime";
import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_schema__ from "@tachybase/schema";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_utils_client__ from "@tachybase/utils/client";
import * as __WEBPACK_EXTERNAL_MODULE__ant_design_icons__ from "@ant-design/icons";
import * as __WEBPACK_EXTERNAL_MODULE_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_antd_style__ from "antd-style";
import * as __WEBPACK_EXTERNAL_MODULE_classnames__ from "classnames";
import * as __WEBPACK_EXTERNAL_MODULE_dayjs__ from "dayjs";
import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__ from "../../hooks/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__style_mjs__ from "./style.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__XButton_mjs__ from "./XButton.mjs";
const JT_VALUE_RE = /^\s*{{\s*([^{}]+)\s*}}\s*$/;
function parseValue(value) {
    if (null == value) return 'null';
    const type = typeof value;
    if ('string' === type) {
        const matched = value.match(JT_VALUE_RE);
        if (matched) return matched[1].split('.');
    }
    return 'object' === type && value instanceof Date ? 'date' : type;
}
const ConstantTypes = {
    string: {
        label: '{{t("String")}}',
        value: 'string',
        component: function(param) {
            let { onChange, value, ...otherProps } = param;
            return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Input, {
                value: value,
                onChange: (ev)=>onChange(ev.target.value),
                ...otherProps
            });
        },
        default: ''
    },
    number: {
        label: '{{t("Number")}}',
        value: 'number',
        component: function(param) {
            let { onChange, value, ...otherProps } = param;
            return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.InputNumber, {
                value: value,
                onChange: onChange,
                ...otherProps
            });
        },
        default: 0
    },
    boolean: {
        label: '{{t("Boolean")}}',
        value: 'boolean',
        component: function(param) {
            let { onChange, value, ...otherProps } = param;
            const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
            return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Select, {
                value: value,
                onChange: onChange,
                placeholder: t('Select'),
                options: [
                    {
                        value: true,
                        label: t('True')
                    },
                    {
                        value: false,
                        label: t('False')
                    }
                ],
                ...otherProps
            });
        },
        default: false
    },
    date: {
        label: '{{t("Date")}}',
        value: 'date',
        component: function(param) {
            let { onChange, value, ...otherProps } = param;
            return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.DatePicker, {
                value: (0, __WEBPACK_EXTERNAL_MODULE_dayjs__["default"])(value),
                onChange: (d)=>d ? onChange(d.toDate()) : null,
                allowClear: false,
                showTime: true,
                ...otherProps
            });
        },
        default: (()=>{
            const now = new Date();
            return new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
        })()
    },
    null: {
        label: '{{t("Null")}}',
        value: 'null',
        component: function() {
            const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
            return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Input, {
                style: {
                    width: '100%'
                },
                readOnly: true,
                placeholder: t('Null'),
                className: "null-value"
            });
        },
        default: null
    }
};
function getTypedConstantOption(type, types, fieldNames) {
    var _ConstantTypes_type;
    const allTypes = Object.values(ConstantTypes);
    const children = (types ? allTypes.filter((item)=>Array.isArray(types) && types.includes(item.value) || true === types) : allTypes).map((item)=>Object.keys(item).reduce((result, key)=>fieldNames[key] in item ? result : Object.assign(result, {
                [fieldNames[key]]: item[key]
            }), item));
    return {
        value: '',
        label: '{{t("Constant")}}',
        children,
        [fieldNames.value]: '',
        [fieldNames.label]: '{{t("Constant")}}',
        [fieldNames.children]: children,
        component: null === (_ConstantTypes_type = ConstantTypes[type]) || void 0 === _ConstantTypes_type ? void 0 : _ConstantTypes_type.component
    };
}
(0, __WEBPACK_EXTERNAL_MODULE_antd_style__.createStyles)((param, param1)=>{
    let { css } = param, { disabled } = param1;
    return {};
});
function Input(props) {
    var _constantOption_children;
    const { value = '', onChange, children, button, useTypedConstant, style, className, changeOnSelect, fieldNames } = props;
    const scope = 'function' == typeof props.scope ? props.scope() : props.scope;
    const compile = (0, __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__.useCompile)();
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const form = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useForm)();
    const [options, setOptions] = __WEBPACK_EXTERNAL_MODULE_react__["default"].useState([]);
    const [variableText, setVariableText] = __WEBPACK_EXTERNAL_MODULE_react__["default"].useState('');
    const parsed = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>parseValue(value), [
        value
    ]);
    const isConstant = 'string' == typeof parsed;
    const type = isConstant ? parsed : '';
    const variable = isConstant ? null : parsed;
    const names = Object.assign({
        label: 'label',
        value: 'value',
        children: 'children'
    }, null != fieldNames ? fieldNames : {});
    const { component: ConstantComponent, ...constantOption } = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>{
        if (children) return {
            value: '',
            label: t('Constant'),
            [names.value]: '',
            [names.label]: t('Constant')
        };
        if (useTypedConstant) return getTypedConstantOption(type, useTypedConstant, names);
        return {
            value: '',
            label: t('Null'),
            [names.value]: '',
            [names.label]: t('Null'),
            component: ConstantTypes.null.component
        };
    }, [
        type,
        useTypedConstant
    ]);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        setOptions([
            compile(constantOption),
            ...scope ? (0, __WEBPACK_EXTERNAL_MODULE_lodash__.cloneDeep)(scope) : []
        ]);
    }, [
        scope
    ]);
    const loadData = async (selectedOptions)=>{
        var _option_children;
        const option = selectedOptions[selectedOptions.length - 1];
        if (!(null === (_option_children = option.children) || void 0 === _option_children ? void 0 : _option_children.length) && !option.isLeaf && option.loadChildren) {
            await option.loadChildren(option);
            setOptions((prev)=>[
                    ...prev
                ]);
        }
    };
    const onSwitch = (0, __WEBPACK_EXTERNAL_MODULE_react__.useCallback)((next, optionPath)=>{
        if ('' === next[0]) {
            if (next[1]) {
                if (next[1] !== type) {
                    var _ConstantTypes_next_;
                    var _ConstantTypes_next__default;
                    onChange(null !== (_ConstantTypes_next__default = null === (_ConstantTypes_next_ = ConstantTypes[next[1]]) || void 0 === _ConstantTypes_next_ ? void 0 : _ConstantTypes_next_.default) && void 0 !== _ConstantTypes_next__default ? _ConstantTypes_next__default : null, optionPath);
                }
            } else if (variable) onChange(null, optionPath);
            return;
        }
        onChange("{{".concat(next.join('.'), "}}"), optionPath);
    }, [
        type,
        variable,
        onChange
    ]);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        const run = async ()=>{
            if (!variable || options.length <= 1) return;
            let prevOption = null;
            const labels = [];
            for(let i = 0; i < variable.length; i++){
                const key = variable[i];
                try {
                    if (0 === i) prevOption = options.find((item)=>item[names.value] === key);
                    else {
                        var _prevOption_children;
                        if (prevOption.loadChildren && !(null === (_prevOption_children = prevOption.children) || void 0 === _prevOption_children ? void 0 : _prevOption_children.length)) await prevOption.loadChildren(prevOption);
                        prevOption = prevOption.children.find((item)=>item[names.value] === key);
                    }
                    if (!prevOption) return;
                    labels.push(prevOption[names.label]);
                } catch (err) {
                    (0, __WEBPACK_EXTERNAL_MODULE__tachybase_utils_client__.error)(err);
                }
            }
            setOptions([
                ...options
            ]);
            setVariableText(labels.join(' / '));
        };
        run();
    }, [
        variable,
        options.length
    ]);
    const disabled = props.disabled || form.disabled;
    const { styles } = (0, __WEBPACK_EXTERNAL_MODULE__style_mjs__.useStyles)({
        disabled
    });
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE_antd__.Space.Compact, {
        style: style,
        className: (0, __WEBPACK_EXTERNAL_MODULE_classnames__["default"])(styles.outerContainer, styles.fixInput, className),
        children: [
            variable ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)("div", {
                className: (0, __WEBPACK_EXTERNAL_MODULE_classnames__["default"])('variable', styles.container2),
                children: [
                    /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
                        role: "button",
                        "aria-label": "variable-tag",
                        onInput: (e)=>e.preventDefault(),
                        onKeyDown: (e)=>{
                            if ('Backspace' !== e.key) {
                                e.preventDefault();
                                return;
                            }
                            onChange(null);
                        },
                        className: (0, __WEBPACK_EXTERNAL_MODULE_classnames__["default"])('ant-input', {
                            'ant-input-disabled': disabled
                        }),
                        contentEditable: !disabled,
                        suppressContentEditableWarning: true,
                        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Tag, {
                            contentEditable: false,
                            color: "blue",
                            children: variableText
                        })
                    }),
                    disabled ? null : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("span", {
                        role: "button",
                        "aria-label": "icon-close",
                        className: (0, __WEBPACK_EXTERNAL_MODULE_classnames__["default"])('clear-button'),
                        unselectable: "on",
                        onClick: ()=>onChange(null),
                        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.CloseCircleFilled, {})
                    })
                ]
            }) : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
                style: {
                    flex: 1
                },
                children: null != children ? children : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(ConstantComponent, {
                    role: "button",
                    "aria-label": "variable-constant",
                    value: value,
                    onChange: onChange
                })
            }),
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Cascader, {
                options: options,
                value: null != variable ? variable : [
                    '',
                    ...!children && (null === (_constantOption_children = constantOption.children) || void 0 === _constantOption_children ? void 0 : _constantOption_children.length) ? [
                        type
                    ] : []
                ],
                onChange: onSwitch,
                loadData: loadData,
                changeOnSelect: changeOnSelect,
                fieldNames: fieldNames,
                disabled: disabled,
                children: null != button ? button : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__XButton_mjs__.XButton, {
                    className: styles.button2,
                    type: variable ? 'primary' : 'default'
                })
            })
        ]
    });
}
export { Input };
