import { jsx } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { observer, useField, useForm } from "@tachybase/schema";
import { AutoComplete, Select } from "antd";
import { useRecord } from "../../../record-provider/index.mjs";
import { useCompile } from "../../../schema-component/index.mjs";
import { useCollectionManager_deprecated } from "../../hooks/index.mjs";
const supportTypes = [
    'string',
    'bigInt',
    'integer',
    'uuid',
    'uid'
];
const SourceForeignKey = observer(()=>{
    const record = useRecord();
    const { getCollection } = useCollectionManager_deprecated();
    const collection = (null == record ? void 0 : record.collectionName) ? getCollection(record.collectionName) : record;
    const field = useField();
    useForm();
    const { getCollectionFields } = useCollectionManager_deprecated();
    return /*#__PURE__*/ jsx("div", {
        children: /*#__PURE__*/ jsx(Select, {
            allowClear: true,
            placeholder: '留空时，自动生成 FK 字段',
            disabled: field.disabled,
            value: field.value,
            options: getCollectionFields(collection.name).filter((field)=>field.type).map((field)=>{
                var _field_uiSchema;
                return {
                    label: (null == field ? void 0 : null == (_field_uiSchema = field.uiSchema) ? void 0 : _field_uiSchema.title) || field.name,
                    value: field.name
                };
            })
        })
    });
}, {
    displayName: 'SourceForeignKey'
});
const ThroughForeignKey = observer(()=>{
    const field = useField();
    const form = useForm();
    const { getCollectionFields } = useCollectionManager_deprecated();
    return /*#__PURE__*/ jsx("div", {
        children: /*#__PURE__*/ jsx(Select, {
            allowClear: true,
            popupMatchSelectWidth: false,
            placeholder: '留空时，自动生成 FK 字段',
            disabled: field.disabled,
            value: field.value,
            options: getCollectionFields(form.values.through).filter((field)=>field.type).map((field)=>{
                var _field_uiSchema;
                return {
                    label: (null == field ? void 0 : null == (_field_uiSchema = field.uiSchema) ? void 0 : _field_uiSchema.title) || field.name,
                    value: field.name
                };
            })
        })
    });
}, {
    displayName: 'ThroughForeignKey'
});
const TargetForeignKey = observer(()=>{
    const field = useField();
    const form = useForm();
    const { getCollectionFields } = useCollectionManager_deprecated();
    return /*#__PURE__*/ jsx("div", {
        children: /*#__PURE__*/ jsx(Select, {
            allowClear: true,
            popupMatchSelectWidth: false,
            placeholder: '留空时，自动生成 FK 字段',
            disabled: field.disabled,
            value: field.value,
            options: getCollectionFields(form.values.target).filter((field)=>field.type).map((field)=>{
                var _field_uiSchema;
                return {
                    label: (null == field ? void 0 : null == (_field_uiSchema = field.uiSchema) ? void 0 : _field_uiSchema.title) || field.name,
                    value: field.name
                };
            })
        })
    });
}, {
    displayName: 'TargetForeignKey'
});
const SourceCollection = observer(()=>{
    const record = useRecord();
    const { getCollection } = useCollectionManager_deprecated();
    const collection = (null == record ? void 0 : record.collectionName) ? getCollection(record.collectionName) : record;
    const compile = useCompile();
    return /*#__PURE__*/ jsx("div", {
        children: /*#__PURE__*/ jsx(Select, {
            disabled: true,
            popupMatchSelectWidth: false,
            value: collection.name,
            options: [
                {
                    value: collection.name,
                    label: compile(collection.title)
                }
            ]
        })
    });
}, {
    displayName: 'SourceCollection'
});
const SourceKey = observer((props)=>{
    var _getCollection_fields, _getCollection, _options_;
    const { sourceKey, collectionName, name } = useRecord();
    const { getCollection } = useCollectionManager_deprecated();
    const field = useField();
    const compile = useCompile();
    const options = null == (_getCollection = getCollection(collectionName || name)) ? void 0 : null == (_getCollection_fields = _getCollection.fields) ? void 0 : _getCollection_fields.filter((v)=>v.primaryKey || v.unique).map((k)=>{
        var _k_uiSchema;
        return {
            value: k.name,
            label: compile((null == (_k_uiSchema = k.uiSchema) ? void 0 : _k_uiSchema.title) || k.name)
        };
    });
    useEffect(()=>{
        var _options_;
        field.initialValue = (null == options ? void 0 : null == (_options_ = options[0]) ? void 0 : _options_.value) || sourceKey;
    }, []);
    return /*#__PURE__*/ jsx("div", {
        children: /*#__PURE__*/ jsx(Select, {
            disabled: sourceKey,
            options: options,
            defaultValue: sourceKey || (null == options ? void 0 : null == (_options_ = options[0]) ? void 0 : _options_.value),
            onChange: null == props ? void 0 : props.onChange,
            showSearch: true
        })
    });
}, {
    displayName: 'SourceKey'
});
const TargetKey = observer((props)=>{
    const { value, disabled } = props;
    const { targetKey, target, type } = useRecord();
    const { getCollection } = useCollectionManager_deprecated();
    const [options, setOptions] = useState([]);
    const [initialValue, setInitialValue] = useState(value || targetKey);
    const form = useForm();
    const compile = useCompile();
    const field = useField();
    field.required = true;
    useEffect(()=>{
        if (target && '__temp__' !== target) {
            var _getCollection_fields;
            setOptions(null == (_getCollection_fields = getCollection(target).fields) ? void 0 : _getCollection_fields.filter((v)=>{
                if ('hasMany' !== type) return v.primaryKey || v.unique;
                return supportTypes.includes(v.type);
            }).map((k)=>{
                var _k_uiSchema;
                return {
                    value: k.name,
                    label: compile((null == k ? void 0 : null == (_k_uiSchema = k.uiSchema) ? void 0 : _k_uiSchema.title) || k.title || k.name)
                };
            }));
        }
    }, []);
    return /*#__PURE__*/ jsx("div", {
        children: /*#__PURE__*/ jsx(Select, {
            showSearch: true,
            options: options,
            onDropdownVisibleChange: async (open)=>{
                const { target, type } = form.values;
                if (target && open) {
                    var _getCollection_fields;
                    setOptions(null == (_getCollection_fields = getCollection(target).fields) ? void 0 : _getCollection_fields.filter((v)=>{
                        if ('hasMany' !== type) return v.primaryKey || v.unique;
                        return supportTypes.includes(v.type);
                    }).map((k)=>{
                        var _k_uiSchema;
                        return {
                            value: k.name,
                            label: compile((null == k ? void 0 : null == (_k_uiSchema = k.uiSchema) ? void 0 : _k_uiSchema.title) || k.title || k.name)
                        };
                    }));
                }
            },
            onChange: (value)=>{
                var _props_onChange;
                null == props || null == (_props_onChange = props.onChange) || _props_onChange.call(props, value);
                setInitialValue(value);
            },
            value: initialValue,
            disabled: disabled
        })
    });
}, {
    displayName: 'TargetKey'
});
const ForeignKey = observer((props)=>{
    const { disabled } = props;
    const [options, setOptions] = useState([]);
    const { getCollection } = useCollectionManager_deprecated();
    const record = useRecord();
    const field = useField();
    const { collectionName, target, type, through, name, template } = record;
    const value = record[field.props.name];
    const compile = useCompile();
    const form = useForm();
    const [initialValue, setInitialValue] = useState(value || ('view' === template ? null : field.initialValue));
    useEffect(()=>{
        var _getCollection;
        const effectField = [
            'belongsTo'
        ].includes(type) ? collectionName : [
            'belongsToMany'
        ].includes(type) ? through : target;
        const fields = null == (_getCollection = getCollection(effectField)) ? void 0 : _getCollection.fields;
        if (fields) {
            const sourceOptions = null == fields ? void 0 : fields.filter((v)=>supportTypes.includes(v.type)).map((k)=>{
                var _k_uiSchema;
                return {
                    value: k.name,
                    label: compile((null == (_k_uiSchema = k.uiSchema) ? void 0 : _k_uiSchema.title) || k.name)
                };
            });
            setOptions(sourceOptions);
            if (value) {
                const option = sourceOptions.find((v)=>v.value === value);
                setInitialValue((null == option ? void 0 : option.label) || value);
            }
        }
    }, [
        type
    ]);
    const Compoent = 'view' === template ? Select : AutoComplete;
    return /*#__PURE__*/ jsx("div", {
        children: /*#__PURE__*/ jsx(Compoent, {
            disabled: disabled,
            value: initialValue,
            options: options,
            showSearch: true,
            onDropdownVisibleChange: async (open)=>{
                const { target, type, through } = form.values;
                const effectField = [
                    'belongsTo'
                ].includes(type) ? collectionName || name : [
                    'belongsToMany'
                ].includes(type) ? through : target;
                if (effectField && open) {
                    var _getCollection;
                    const fields = (null == (_getCollection = getCollection(effectField)) ? void 0 : _getCollection.fields) || [];
                    setOptions(null == fields ? void 0 : fields.filter((v)=>supportTypes.includes(v.type)).map((k)=>{
                        var _k_uiSchema;
                        return {
                            value: k.name,
                            label: compile((null == (_k_uiSchema = k.uiSchema) ? void 0 : _k_uiSchema.title) || k.name)
                        };
                    }));
                }
            },
            onChange: (value, option)=>{
                var _props_onChange;
                null == props || null == (_props_onChange = props.onChange) || _props_onChange.call(props, value);
                setInitialValue(option.label || value);
            }
        })
    });
}, {
    displayName: 'ForeignKey'
});
const ThroughCollection = observer((props)=>{
    const { disabled } = props;
    const compile = useCompile();
    const { getCollections } = useCollectionManager_deprecated();
    const [options, setOptions] = useState([]);
    const field = useField();
    const record = useRecord();
    const value = record[field.props.name];
    const [initialValue, setInitialValue] = useState(value || field.initialValue);
    const [defOptions, setDefOptions] = useState([]);
    const loadCollections = ()=>{
        const filteredItems = getCollections().filter((item)=>{
            const isAutoCreateAndThrough = item.autoCreate && item.isThrough;
            if (isAutoCreateAndThrough) return false;
            return true;
        });
        return filteredItems.map((item)=>({
                label: compile(item.title),
                value: item.name
            }));
    };
    useEffect(()=>{
        const data = loadCollections();
        setOptions(data);
        setDefOptions(data);
        if (value) {
            const option = data.find((v)=>v.value === value);
            setInitialValue((null == option ? void 0 : option.label) || value);
        }
    }, []);
    const handleSearch = (value)=>{
        if (value) {
            const filteredOptions = defOptions.filter((option)=>option.label.toLowerCase().includes(value.toLowerCase()));
            setOptions(filteredOptions);
        } else setOptions(defOptions);
    };
    return /*#__PURE__*/ jsx("div", {
        children: /*#__PURE__*/ jsx(AutoComplete, {
            disabled: disabled,
            showSearch: true,
            popupMatchSelectWidth: false,
            value: initialValue,
            options: options,
            onSearch: handleSearch,
            onChange: (value, option)=>{
                var _props_onChange;
                null == props || null == (_props_onChange = props.onChange) || _props_onChange.call(props, value);
                setInitialValue(option.label || value);
            }
        })
    });
}, {
    displayName: 'ThroughCollection'
});
export { ForeignKey, SourceCollection, SourceForeignKey, SourceKey, TargetForeignKey, TargetKey, ThroughCollection, ThroughForeignKey };
