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__index_mjs__ from "../../../index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__ from "../../../api-client/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__Configuration_interfaces_mjs__ from "../../Configuration/interfaces.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_useCollectionManager_deprecated_mjs__ from "../../hooks/useCollectionManager_deprecated.mjs";
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)=>v.children.length > 0);
};
const PreviewCom = (props)=>{
    const { databaseView, viewName, sources, schema } = props;
    const { data: fields } = (0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.ResourceActionContext);
    const api = (0, __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__.useAPIClient)();
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const [loading, setLoading] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
    const [dataSource, setDataSource] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
    const [sourceFields, setSourceFields] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
    const [sourceCollections, setSourceCollections] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(sources);
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const form = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useForm)();
    const { getCollection, getInterface, getCollectionFields, getInheritCollections, getParentCollectionFields } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_useCollectionManager_deprecated_mjs__.useCollectionManager_deprecated)();
    const compile = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useCompile)();
    const options = (0, __WEBPACK_EXTERNAL_MODULE__Configuration_interfaces_mjs__.useFieldInterfaceOptions)();
    const initOptions = options.filter((v)=>![
            'relation',
            'systemInfo'
        ].includes(v.key));
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        const data = [];
        sourceCollections.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)
                        };
                    })
                };
            });
            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,
                    key: v.name,
                    label: t((null === (_v_uiSchema = v.uiSchema) || void 0 === _v_uiSchema ? void 0 : _v_uiSchema.title) || v.name)
                };
            }).concat(result);
            data.push({
                value: item,
                label: t(collection.title || collection.name),
                children
            });
        });
        setSourceFields(data);
    }, [
        sourceCollections,
        databaseView
    ]);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        if (databaseView) {
            setLoading(true);
            api.resource("dbViews").get({
                filterByTk: viewName,
                schema
            }).then((param)=>{
                let { data } = param;
                if (data) {
                    var _Object_values, _data_data;
                    setLoading(false);
                    setDataSource([]);
                    const fieldsData = null === (_Object_values = Object.values(null == data ? void 0 : null === (_data_data = data.data) || void 0 === _data_data ? void 0 : _data_data.fields)) || void 0 === _Object_values ? void 0 : _Object_values.map((v)=>{
                        if (v.source) {
                            var _option_uiSchema;
                            const option = (null == fields ? void 0 : fields.data.find((h)=>h.name === v.name)) || v;
                            return {
                                ...v,
                                uiSchema: {
                                    ...(0, __WEBPACK_EXTERNAL_MODULE_lodash__.omit)(option.uiSchema, 'rawTitle'),
                                    title: (null === (_option_uiSchema = option.uiSchema) || void 0 === _option_uiSchema ? void 0 : _option_uiSchema.title) || option.name
                                }
                            };
                        }
                        {
                            var _option_uiSchema1;
                            const option = (null == fields ? void 0 : fields.data.find((h)=>h.name === v.name)) || v;
                            return {
                                ...option,
                                uiSchema: {
                                    ...(0, __WEBPACK_EXTERNAL_MODULE_lodash__.omit)(option.uiSchema, 'rawTitle'),
                                    title: (null === (_option_uiSchema1 = option.uiSchema) || void 0 === _option_uiSchema1 ? void 0 : _option_uiSchema1.title) || option.name
                                }
                            };
                        }
                    });
                    field.value = fieldsData;
                    setTimeout(()=>{
                        var _data_data, _data_data1;
                        setDataSource(fieldsData);
                        form.setValuesIn('sources', null === (_data_data = data.data) || void 0 === _data_data ? void 0 : _data_data.sources);
                        setSourceCollections(null === (_data_data1 = data.data) || void 0 === _data_data1 ? void 0 : _data_data1.sources);
                    });
                }
            }).catch;
        }
    }, [
        databaseView
    ]);
    const handleFieldChange = (record, index)=>{
        dataSource.splice(index, 1, record);
        setDataSource(dataSource);
        field.value = dataSource.map((v)=>{
            var _v_source_filter, _v_source_filter1, _v_source;
            const source = 'string' == typeof v.source ? v.source : null === (_v_source = v.source) || void 0 === _v_source ? void 0 : null === (_v_source_filter1 = _v_source.filter) || void 0 === _v_source_filter1 ? void 0 : null === (_v_source_filter = _v_source_filter1.call(_v_source, Boolean)) || void 0 === _v_source_filter ? void 0 : _v_source_filter.join('.');
            return {
                ...v,
                source
            };
        });
    };
    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)=>/*#__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,
                    style: {
                        width: '100%'
                    },
                    options: compile(sourceFields),
                    onChange: (value, selectedOptions)=>{
                        var _getCollectionFields;
                        const sourceField = null === (_getCollectionFields = getCollectionFields(null == value ? void 0 : value[0])) || void 0 === _getCollectionFields ? void 0 : _getCollectionFields.find((v)=>v.name === (0, __WEBPACK_EXTERNAL_MODULE_lodash__.last)(value));
                        handleFieldChange({
                            ...record,
                            source: value,
                            uiSchema: null == sourceField ? void 0 : sourceField.uiSchema
                        }, index);
                    },
                    placeholder: t('Select field source')
                })
        },
        {
            title: t('Field type'),
            dataIndex: 'type',
            width: 140,
            key: 'type',
            render: (text, _, index)=>{
                const item = dataSource[index];
                return (null == item ? void 0 : item.source) || !(null == item ? void 0 : item.possibleTypes) ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Tag, {
                    children: text
                }) : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Select, {
                    defaultValue: text,
                    popupMatchSelectWidth: false,
                    style: {
                        width: '100%'
                    },
                    options: (null == item ? void 0 : item.possibleTypes.map((v)=>({
                            label: v,
                            value: v
                        }))) || [],
                    onChange: (value)=>handleFieldChange({
                            ...item,
                            type: value
                        }, index)
                });
            }
        },
        {
            title: t('Field interface'),
            dataIndex: 'interface',
            key: 'interface',
            width: 150,
            render: (text, _, index)=>{
                const item = dataSource[index];
                const data = getInterfaceOptions(initOptions, item.type);
                return item.source ? text : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Select, {
                    defaultValue: text,
                    style: {
                        width: '100%'
                    },
                    popupMatchSelectWidth: false,
                    onChange: (value)=>{
                        var _interfaceConfig_default;
                        const interfaceConfig = getInterface(value);
                        handleFieldChange({
                            ...item,
                            interface: value,
                            uiSchema: null == interfaceConfig ? void 0 : null === (_interfaceConfig_default = interfaceConfig.default) || void 0 === _interfaceConfig_default ? void 0 : _interfaceConfig_default.uiSchema
                        }, index);
                    },
                    children: data.map((group)=>/*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Select.OptGroup, {
                            label: compile(group.label),
                            children: group.children.map((item)=>/*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Select.Option, {
                                    value: item.name,
                                    children: compile(item.label)
                                }, item.value))
                        }, group.key))
                });
            }
        },
        {
            title: t('Field display name'),
            dataIndex: 'title',
            key: 'title',
            width: 180,
            render: (text, record, index)=>{
                var _item_uiSchema;
                const item = dataSource[index];
                return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Input, {
                    defaultValue: (null == item ? void 0 : null === (_item_uiSchema = item.uiSchema) || void 0 === _item_uiSchema ? void 0 : _item_uiSchema.title) || text,
                    onChange: (e)=>handleFieldChange({
                            ...item,
                            uiSchema: {
                                ...(0, __WEBPACK_EXTERNAL_MODULE_lodash__.omit)(null == item ? void 0 : item.uiSchema, 'rawTitle'),
                                title: e.target.value
                            }
                        }, index)
                });
            }
        }
    ];
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Spin, {
        spinning: loading,
        children: dataSource.length > 0 && /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
            children: [
                /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)("div", {
                    className: "ant-formily-item-label",
                    style: {
                        display: 'flex',
                        padding: '0 0 8px'
                    },
                    children: [
                        /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
                            className: "ant-formily-item-label-content",
                            children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("span", {
                                children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("label", {
                                    children: t('Fields')
                                })
                            })
                        }),
                        /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("span", {
                            className: "ant-formily-item-colon",
                            children: ":"
                        })
                    ]
                }),
                /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Table, {
                    bordered: true,
                    size: 'middle',
                    columns: columns,
                    dataSource: dataSource,
                    scroll: {
                        y: 300
                    },
                    pagination: false,
                    rowClassName: "editable-row"
                }, viewName)
            ]
        })
    });
};
function areEqual(prevProps, nextProps) {
    return nextProps.name === prevProps.name && nextProps.sources === prevProps.sources;
}
const PreviewFields = /*#__PURE__*/ __WEBPACK_EXTERNAL_MODULE_react__["default"].memo(PreviewCom, areEqual);
PreviewFields.displayName = 'PreviewFields';
export { PreviewFields };
