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_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE__data_source_index_mjs__ from "../../../data-source/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__ from "../../../schema-component/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__ from "../../hooks/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__interfaces_mjs__ from "../interfaces.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__xlsxFormValueContextProvider_mjs__ from "./xlsxFormValueContextProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__xlsxImportAction_mjs__ from "./xlsxImportAction.mjs";
const xlsxFieldsConfigure = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.observer)((props)=>{
    const { filedata } = props;
    const { fields, data } = filedata;
    (0, __WEBPACK_EXTERNAL_MODULE__data_source_index_mjs__.useDataSourceManager)();
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const initOptions = (0, __WEBPACK_EXTERNAL_MODULE__interfaces_mjs__.useFieldInterfaceOptions)();
    const compile = (0, __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.useCompile)();
    const [selectedTitleField, setSelectedTitleField] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)();
    const form = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useForm)();
    const [formValue, setFormValue] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(fields);
    const { getInterface } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__.useCollectionManager_deprecated)();
    const getDefaultUiSchema = (interfaceType, title)=>{
        var _interfaceConfigValues_default;
        const interfaceConfig = getInterface(interfaceType) || {};
        const interfaceConfigValues = (0, __WEBPACK_EXTERNAL_MODULE_lodash__.cloneDeep)(interfaceConfig);
        const defaultUiSchema = (null == interfaceConfigValues ? void 0 : null === (_interfaceConfigValues_default = interfaceConfigValues.default) || void 0 === _interfaceConfigValues_default ? void 0 : _interfaceConfigValues_default.uiSchema) || {};
        return {
            ...defaultUiSchema,
            title
        };
    };
    const handleFieldChange = (updatedField, index)=>{
        const updatedFieldData = [
            ...formValue
        ];
        updatedFieldData[index] = updatedField;
        setFormValue(updatedFieldData);
    };
    const handleFieldTypeChange = async (updatedField, index)=>{
        const { type, name: dataIndex, uiSchema } = updatedField;
        const updatedData = [
            ...data
        ];
        let hasError = false;
        const typeToInterface = {
            json: 'json',
            boolean: 'checkbox',
            string: 'input',
            integer: 'integer',
            float: 'number',
            date: 'datetime'
        };
        updatedField.interface = await typeToInterface[type] || null;
        const currentUiSchema = await getDefaultUiSchema(updatedField.interface, uiSchema.title);
        updatedField.uiSchema = currentUiSchema;
        updatedData.forEach((row, rowIndex)=>{
            try {
                if (void 0 !== row[dataIndex]) row[dataIndex] = parseValue(row[dataIndex], type);
            } catch (error) {
                hasError = true;
                __WEBPACK_EXTERNAL_MODULE_antd__.message.error("Row ".concat(rowIndex + 1, ", Column ").concat(uiSchema.title, ": ").concat(error.message));
            }
        });
        if (!hasError) {
            __WEBPACK_EXTERNAL_MODULE_antd__.message.success("".concat(t('Fields'), ' "').concat(uiSchema.title, '"').concat(t('Converted to'), " ").concat(type));
            const updatedFieldData = [
                ...formValue
            ];
            updatedFieldData[index] = updatedField;
            setFormValue(updatedFieldData);
        }
    };
    const handleFieldInterfaceChange = async (updatedField, index)=>{
        const currentUiSchema = await getDefaultUiSchema(updatedField.interface, updatedField.uiSchema.title);
        updatedField.uiSchema = currentUiSchema;
        const updatedFieldData = [
            ...formValue
        ];
        updatedFieldData[index] = updatedField;
        setFormValue(updatedFieldData);
    };
    const parseValue = (value, type)=>{
        try {
            switch(type){
                case 'boolean':
                    if ('true' === value.toLowerCase()) return true;
                    if ('false' === value.toLowerCase()) return false;
                    throw new Error('Invalid boolean');
                case 'integer':
                    if (!/^-?\d+$/.test(value)) throw new Error('Invalid integer');
                    return parseInt(value, 10);
                case 'float':
                    if (!/^-?\d+(\.\d+)?$/.test(value)) throw new Error('Invalid number');
                    return Number(value);
                case 'json':
                    return JSON.parse(value);
                case 'date':
                    if (isNaN(Date.parse(value))) throw new Error('Invalid date');
                    return new Date(value);
                default:
                    if (null == value || '' === value) return '';
                    return value.toString();
            }
        } catch (error) {
            throw new Error("Type conversion error: ".concat(error.message));
        }
    };
    const handleTitleChange = (checked, field)=>{
        const newTitleField = checked ? field.name : null;
        setSelectedTitleField(newTitleField);
        form.setValuesIn('titleField', newTitleField);
    };
    const isTitleField = (field)=>{
        var _getInterface;
        return !field.isForeignKey && (null === (_getInterface = getInterface(field.interface)) || void 0 === _getInterface ? void 0 : _getInterface.titleUsable);
    };
    const getOptions = (type)=>{
        const InterfaceOptions = getInterfaceOptions(initOptions, type);
        const options = InterfaceOptions.map((group)=>({
                label: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("span", {
                    children: compile(group.label)
                }),
                title: group.key,
                options: group.children.map((item)=>({
                        label: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("span", {
                            children: compile(item.label)
                        }),
                        value: item.name
                    }))
            }));
        return options;
    };
    const getInterfaceOptions = (data, type)=>{
        const interfaceOptions = [];
        data.forEach((item)=>{
            const options = item.children.filter((h)=>{
                var _h_availableTypes;
                return null == h ? void 0 : null === (_h_availableTypes = h.availableTypes) || void 0 === _h_availableTypes ? void 0 : _h_availableTypes.includes(type);
            });
            interfaceOptions.push({
                label: item.label,
                key: item.key,
                children: options
            });
        });
        return interfaceOptions.filter((v)=>{
            if ('sort' === type) return 'advanced' === v.key;
            return v.children.length > 0;
        });
    };
    const columns = [
        {
            title: t('Field display name'),
            dataIndex: 'title',
            key: 'title',
            render: (text, record, index)=>{
                const field = formValue[index];
                return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Input, {
                    value: field.uiSchema.title || text,
                    onChange: (e)=>handleFieldChange({
                            ...field,
                            uiSchema: {
                                title: e.target.value
                            }
                        }, index)
                });
            }
        },
        {
            title: t('Field name'),
            dataIndex: 'name',
            key: 'name',
            render: (text, record, index)=>{
                const field = formValue[index];
                return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Input, {
                    value: field.name || text,
                    variant: "borderless",
                    disabled: true
                });
            }
        },
        {
            title: t('Field type'),
            dataIndex: 'type',
            key: 'type',
            render: (text, record, index)=>{
                const field = formValue[index];
                return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Select, {
                    value: field.type || text,
                    onChange: (e)=>handleFieldTypeChange({
                            ...field,
                            type: e
                        }, index),
                    options: [
                        {
                            value: 'string',
                            label: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("span", {
                                children: "string"
                            })
                        },
                        {
                            value: 'boolean',
                            label: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("span", {
                                children: "boolean"
                            })
                        },
                        {
                            value: 'integer',
                            label: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("span", {
                                children: "integer"
                            })
                        },
                        {
                            value: 'float',
                            label: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("span", {
                                children: "float"
                            })
                        },
                        {
                            value: 'json',
                            label: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("span", {
                                children: "json"
                            })
                        },
                        {
                            value: 'date',
                            label: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("span", {
                                children: "date"
                            })
                        }
                    ]
                });
            }
        },
        {
            title: t('Field interface'),
            dataIndex: 'interface',
            key: 'interface',
            render: (text, record, index)=>{
                const field = formValue[index];
                const options = getOptions(field.type);
                return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Select, {
                    "aria-label": "field-interface-".concat(null == field ? void 0 : field.type),
                    role: "button",
                    value: field.interface,
                    popupMatchSelectWidth: false,
                    onChange: (e)=>handleFieldInterfaceChange({
                            ...field,
                            interface: e
                        }, index),
                    options: options
                });
            }
        },
        {
            dataIndex: 'titleField',
            title: t('Title field'),
            render: function(_, record, index) {
                const field = formValue[index];
                return isTitleField(field) ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Tooltip, {
                    title: t('Default title for each record'),
                    placement: "right",
                    overlayInnerStyle: {
                        textAlign: 'center'
                    },
                    children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Switch, {
                        "aria-label": "switch-title-field-".concat(field.name),
                        size: "small",
                        checked: field.name === selectedTitleField,
                        onChange: (checked)=>handleTitleChange(checked, field)
                    })
                }) : null;
            }
        },
        {
            title: t('Description'),
            dataIndex: 'description',
            key: 'description',
            render: (text, record, index)=>{
                const field = formValue[index];
                return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Input.TextArea, {
                    value: field.description,
                    variant: "borderless",
                    disabled: true
                });
            }
        },
        {
            title: t('Actions'),
            dataIndex: 'actions',
            key: 'actions',
            render: (text, record, index)=>{
                const field = formValue[index];
                return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Space, {
                    size: "middle",
                    children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__xlsxImportAction_mjs__.XlsxEditFieldAction, {
                        record: {
                            index,
                            ...field
                        },
                        ...props
                    })
                });
            }
        }
    ];
    const previewTablecolumns = formValue.map((field)=>({
            title: field.uiSchema.title,
            dataIndex: field.name,
            key: field.name,
            render: (text)=>{
                if ('boolean' == typeof text) return text ? 'True' : 'False';
                if ('date' === field.type && text) return new Date(text).toLocaleString();
                if ('json' === field.type && text) try {
                    return 'string' == typeof text ? text : JSON.stringify(text, null, 2);
                } catch (error) {
                    return 'Invalid JSON';
                }
                return text;
            },
            width: 200
        }));
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        form.setValuesIn('fields', formValue);
        form.setValuesIn('collectionData', filedata.data);
        console.log('%c Line:294 🍔 filedata.data', 'font-size:18px;color:#42b983;background:#3f7cff', filedata.data);
    }, [
        formValue
    ]);
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE__xlsxFormValueContextProvider_mjs__.xlsxFormValueContext.Provider, {
        value: {
            value: formValue,
            setFormValue
        },
        children: [
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Table, {
                bordered: true,
                size: "small",
                columns: columns,
                dataSource: formValue,
                scroll: {
                    y: 300
                },
                pagination: false,
                rowClassName: "row",
                rowKey: "uid",
                style: {
                    marginBottom: '16px'
                },
                ...props
            }),
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)("div", {
                style: {
                    fontWeight: 'bold',
                    marginBottom: '10px'
                },
                children: [
                    t('Preview'),
                    ":"
                ]
            }),
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Table, {
                bordered: true,
                size: "small",
                columns: previewTablecolumns,
                dataSource: filedata.data,
                scroll: {
                    y: 300,
                    x: 'max-content'
                },
                rowKey: "name"
            })
        ]
    });
}, {
    displayName: 'FieldsConfigure'
});
export { xlsxFieldsConfigure };
