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_dayjs__ from "dayjs";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE__async_data_provider_index_mjs__ from "../../../../async-data-provider/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__ from "../../../../schema-component/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__Configuration_interfaces_mjs__ from "../../../Configuration/interfaces.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__ from "../../../hooks/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__ResourceActionProvider_mjs__ from "../../../ResourceActionProvider.mjs";
const inferInterface = (field, value)=>{
    if (field.toLowerCase().includes('id')) return 'id';
    if ('number' == typeof value) {
        if (Number.isInteger(value)) return 'integer';
        return 'number';
    }
    if ('boolean' == typeof value) return 'checkbox';
    if ((0, __WEBPACK_EXTERNAL_MODULE_dayjs__["default"])(value).isValid()) return 'datetime';
    return 'input';
};
const useSourceFieldsOptions = ()=>{
    const form = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useForm)();
    const { sources = [] } = form.values;
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const { getCollection, getInheritCollections, getParentCollectionFields } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__.useCollectionManager_deprecated)();
    const data = [];
    sources.forEach((item)=>{
        var _collection_fields_filter;
        const collection = getCollection(item);
        const inherits = getInheritCollections(item);
        const result = inherits.map((v)=>{
            const fields = getParentCollectionFields(v, item);
            return {
                type: 'group',
                key: v,
                label: t("Parent collection fields") + t("(".concat(getCollection(v).title, ")")),
                children: fields.filter((v)=>![
                        'hasOne',
                        'hasMany',
                        'belongsToMany'
                    ].includes(null == v ? void 0 : v.type)).map((k)=>{
                    var _k_uiSchema;
                    return {
                        value: k.name,
                        label: t(null === (_k_uiSchema = k.uiSchema) || void 0 === _k_uiSchema ? void 0 : _k_uiSchema.title)
                    };
                })
            };
        });
        if (!collection) return;
        const children = null === (_collection_fields_filter = collection.fields.filter((v)=>![
                'hasOne',
                'hasMany',
                'belongsToMany'
            ].includes(null == v ? void 0 : v.type))) || void 0 === _collection_fields_filter ? void 0 : _collection_fields_filter.map((v)=>{
            var _v_uiSchema;
            return {
                value: v.name,
                label: t(null === (_v_uiSchema = v.uiSchema) || void 0 === _v_uiSchema ? void 0 : _v_uiSchema.title)
            };
        });
        data.push({
            value: item,
            label: t(collection.title),
            children: [
                ...children,
                ...result
            ]
        });
    });
    return data;
};
const FieldsConfigure = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.observer)(()=>{
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const [dataSource, setDataSource] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
    const { data: res, error, loading } = (0, __WEBPACK_EXTERNAL_MODULE__async_data_provider_index_mjs__.useAsyncData)();
    const { data, fields: sourceFields } = res || {};
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const { data: curFields } = (0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(__WEBPACK_EXTERNAL_MODULE__ResourceActionProvider_mjs__.ResourceActionContext);
    const compile = (0, __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.useCompile)();
    const { getInterface, getCollectionField } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__.useCollectionManager_deprecated)();
    const options = (0, __WEBPACK_EXTERNAL_MODULE__Configuration_interfaces_mjs__.useFieldInterfaceOptions)();
    const interfaceOptions = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>options.filter((v)=>![
                'relation'
            ].includes(v.key)).map((options, index)=>({
                ...options,
                key: index,
                label: compile(options.label),
                options: options.children.map((option)=>({
                        ...option,
                        label: compile(option.label)
                    }))
            })), [
        compile
    ]);
    const sourceFieldsOptions = useSourceFieldsOptions();
    const refGetInterface = (0, __WEBPACK_EXTERNAL_MODULE_react__.useRef)(getInterface);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        var _field_value;
        const fieldsMp = new Map();
        if (!loading) {
            if (data && data.length) Object.entries((null == data ? void 0 : data[0]) || {}).forEach((param)=>{
                let [col, val] = param;
                var _refGetInterface_current;
                const sourceField = sourceFields[col];
                const fieldInterface = inferInterface(col, val);
                const defaultConfig = null === (_refGetInterface_current = refGetInterface.current(fieldInterface)) || void 0 === _refGetInterface_current ? void 0 : _refGetInterface_current.default;
                const uiSchema = (null == sourceField ? void 0 : sourceField.uiSchema) || (null == defaultConfig ? void 0 : defaultConfig.uiSchema) || {};
                fieldsMp.set(col, {
                    name: col,
                    interface: (null == sourceField ? void 0 : sourceField.interface) || fieldInterface,
                    type: (null == sourceField ? void 0 : sourceField.type) || (null == defaultConfig ? void 0 : defaultConfig.type),
                    source: null == sourceField ? void 0 : sourceField.source,
                    uiSchema: {
                        title: col,
                        ...uiSchema
                    }
                });
            });
            else Object.entries(sourceFields || {}).forEach((param)=>{
                let [col, val] = param;
                return fieldsMp.set(col, {
                    name: col,
                    ...val,
                    uiSchema: {
                        title: col,
                        ...(null == val ? void 0 : val.uiSchema) || {}
                    }
                });
            });
        }
        if (null === (_field_value = field.value) || void 0 === _field_value ? void 0 : _field_value.length) field.value.forEach((item)=>{
            if (fieldsMp.has(item.name)) fieldsMp.set(item.name, item);
        });
        const fields = Array.from(fieldsMp.values());
        if (!fields.length) return;
        setDataSource(fields);
        field.setValue(fields);
    }, [
        loading,
        data,
        field,
        sourceFields,
        curFields
    ]);
    if (loading) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Spin, {});
    if (!data && !error) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Alert, {
        showIcon: true,
        message: t('Please use a valid SELECT or WITH AS statement')
    });
    const err = error;
    if (err) {
        var _err_response_data_errors_map, _err_response_data_errors, _err_response_data, _err_response;
        const errMsg = (null == err ? void 0 : null === (_err_response = err.response) || void 0 === _err_response ? void 0 : null === (_err_response_data = _err_response.data) || void 0 === _err_response_data ? void 0 : null === (_err_response_data_errors = _err_response_data.errors) || void 0 === _err_response_data_errors ? void 0 : null === (_err_response_data_errors_map = _err_response_data_errors.map) || void 0 === _err_response_data_errors_map ? void 0 : _err_response_data_errors_map.call(_err_response_data_errors, (item)=>item.message).join('\n')) || err.message;
        return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Alert, {
            showIcon: true,
            message: "".concat(t('SQL error: ')).concat(errMsg),
            type: "error"
        });
    }
    const handleFieldChange = (record, index)=>{
        const fields = [
            ...dataSource
        ];
        fields.splice(index, 1, record);
        setDataSource(fields);
        field.setValue(fields.map((f)=>{
            var _f_source_filter, _f_source_filter1, _f_source;
            return {
                ...f,
                source: 'string' == typeof f.source ? f.source : (null === (_f_source = f.source) || void 0 === _f_source ? void 0 : null === (_f_source_filter1 = _f_source.filter) || void 0 === _f_source_filter1 ? void 0 : null === (_f_source_filter = _f_source_filter1.call(_f_source, Boolean)) || void 0 === _f_source_filter ? void 0 : _f_source_filter.join('.')) || null
            };
        }));
    };
    const columns = [
        {
            title: t('Field name'),
            dataIndex: 'name',
            key: 'name',
            width: 130
        },
        {
            title: t('Field source'),
            dataIndex: 'source',
            key: 'source',
            width: 200,
            render: (text, record, index)=>{
                const field = dataSource[index];
                return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Cascader, {
                    defaultValue: 'string' == typeof text ? null == text ? void 0 : text.split('.') : text,
                    allowClear: true,
                    options: compile(sourceFieldsOptions),
                    placeholder: t('Select field source'),
                    onChange: (value)=>{
                        let sourceField = sourceFields[null == value ? void 0 : value[1]];
                        if (!sourceField) sourceField = getCollectionField((null == value ? void 0 : value.join('.')) || '');
                        handleFieldChange({
                            ...field,
                            source: value,
                            interface: null == sourceField ? void 0 : sourceField.interface,
                            type: null == sourceField ? void 0 : sourceField.type,
                            uiSchema: null == sourceField ? void 0 : sourceField.uiSchema
                        }, index);
                    }
                });
            }
        },
        {
            title: t('Field interface'),
            dataIndex: 'interface',
            key: 'interface',
            width: 150,
            render: (text, record, index)=>{
                var _getInterface;
                const field = dataSource[index];
                return field.source ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Tag, {
                    children: compile(null === (_getInterface = getInterface(text)) || void 0 === _getInterface ? void 0 : _getInterface.title) || text
                }) : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Select, {
                    defaultValue: field.interface || 'input',
                    style: {
                        width: '100%'
                    },
                    popupMatchSelectWidth: false,
                    onChange: (value)=>{
                        var _interfaceConfig_default, _interfaceConfig_default_uiSchema, _interfaceConfig_default1, _field_uiSchema, _interfaceConfig_default2;
                        const interfaceConfig = getInterface(value);
                        handleFieldChange({
                            ...field,
                            interface: value || null,
                            uiSchema: {
                                ...null == interfaceConfig ? void 0 : null === (_interfaceConfig_default = interfaceConfig.default) || void 0 === _interfaceConfig_default ? void 0 : _interfaceConfig_default.uiSchema,
                                title: (null == interfaceConfig ? void 0 : null === (_interfaceConfig_default1 = interfaceConfig.default) || void 0 === _interfaceConfig_default1 ? void 0 : null === (_interfaceConfig_default_uiSchema = _interfaceConfig_default1.uiSchema) || void 0 === _interfaceConfig_default_uiSchema ? void 0 : _interfaceConfig_default_uiSchema.title) || (null === (_field_uiSchema = field.uiSchema) || void 0 === _field_uiSchema ? void 0 : _field_uiSchema.title)
                            },
                            type: null == interfaceConfig ? void 0 : null === (_interfaceConfig_default2 = interfaceConfig.default) || void 0 === _interfaceConfig_default2 ? void 0 : _interfaceConfig_default2.type
                        }, index);
                    },
                    allowClear: true,
                    options: interfaceOptions
                });
            }
        },
        {
            title: t('Field display name'),
            dataIndex: 'title',
            key: 'title',
            width: 180,
            render: (text, record, index)=>{
                var _field_uiSchema, _field_uiSchema1;
                const field = dataSource[index];
                return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Input, {
                    value: (null === (_field_uiSchema = field.uiSchema) || void 0 === _field_uiSchema ? void 0 : _field_uiSchema.title) || text,
                    defaultValue: (null === (_field_uiSchema1 = field.uiSchema) || void 0 === _field_uiSchema1 ? void 0 : _field_uiSchema1.title) !== void 0 ? field.uiSchema.title : null == field ? void 0 : field.name,
                    onChange: (e)=>handleFieldChange({
                            ...field,
                            uiSchema: {
                                ...null == field ? void 0 : field.uiSchema,
                                title: e.target.value
                            }
                        }, index)
                });
            }
        }
    ];
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Table, {
        bordered: true,
        size: "small",
        columns: columns,
        dataSource: dataSource,
        scroll: {
            y: 300
        },
        pagination: false,
        rowClassName: "editable-row",
        rowKey: "name"
    });
}, {
    displayName: 'FieldsConfigure'
});
export { FieldsConfigure };
