import { jsx, jsxs } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { RecursionField, connect, mapProps, observer, onFieldInputValueChange, uid, useField, useFieldSchema, useForm } from "@tachybase/schema";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { App, Space } from "antd";
import { isFunction } from "mathjs";
import { useTranslation } from "react-i18next";
import { RecordProvider, useAPIClient, useApp, useCollectionRecordData } from "../../../index.mjs";
import { isVariable } from "../../../variables/utils/isVariable.mjs";
import { getInnermostKeyAndValue } from "../../common/utils/uitls.mjs";
import { RemoteSelect } from "../remote-select/index.mjs";
import hooks, { useAssociationFieldContext } from "./hooks.mjs";
const filterAnalyses = (filters)=>{
    if (!filters) return;
    const type = Object.keys(filters)[0] || '$and';
    const conditions = filters[type];
    const results = [];
    null == conditions || conditions.map((c)=>{
        var _jsonlogic_value_match, _jsonlogic_value_match1, _jsonlogic_value;
        const jsonlogic = getInnermostKeyAndValue(c);
        const operator = null == jsonlogic ? void 0 : jsonlogic.key;
        if (!operator) return true;
        const regex = /\{\{\$(?:[a-zA-Z_]\w*)\.([a-zA-Z_]\w*)(?:\.id)?\}\}/;
        const fieldName = null == jsonlogic ? void 0 : null == (_jsonlogic_value = jsonlogic.value) ? void 0 : null == (_jsonlogic_value_match1 = _jsonlogic_value.match) ? void 0 : null == (_jsonlogic_value_match = _jsonlogic_value_match1.call(_jsonlogic_value, regex)) ? void 0 : _jsonlogic_value_match[1];
        if (fieldName) results.push(fieldName);
    });
    return results;
};
const InternalAssociationSelect = observer((props)=>{
    var _fieldSchema_xcomponentprops, _field_componentProps_service_params, _field_componentProps_service, _field_componentProps;
    const { objectValue = true } = props;
    const { message } = App.useApp();
    const field = useField();
    const fieldSchema = useFieldSchema();
    const service = hooks(props);
    const { options: collectionField } = useAssociationFieldContext();
    const initValue = isVariable(props.value) ? void 0 : props.value;
    const value = Array.isArray(initValue) ? initValue.filter(Boolean) : initValue;
    const [innerValue, setInnerValue] = useState(value);
    const addMode = null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.addMode;
    const isAllowAddNew = fieldSchema['x-add-new'];
    const { t } = useTranslation();
    const { multiple } = props;
    const form = useForm();
    const api = useAPIClient();
    const resource = api.resource(collectionField.target);
    const linkageFields = filterAnalyses(null == (_field_componentProps = field.componentProps) ? void 0 : null == (_field_componentProps_service = _field_componentProps.service) ? void 0 : null == (_field_componentProps_service_params = _field_componentProps_service.params) ? void 0 : _field_componentProps_service_params.filter);
    const recordData = useCollectionRecordData();
    useEffect(()=>{
        const initValue = isVariable(field.value) ? void 0 : field.value;
        const value = Array.isArray(initValue) ? initValue.filter(Boolean) : initValue;
        setInnerValue(value);
    }, [
        field.value
    ]);
    useEffect(()=>{
        const id = uid();
        form.addEffects(id, ()=>{
            if ((null == linkageFields ? void 0 : linkageFields.length) > 0) onFieldInputValueChange('*', (fieldPath)=>{
                if (linkageFields.includes(fieldPath.props.name) && field.value) {
                    props.onChange(field.initialValue);
                    setInnerValue(field.initialValue);
                }
            });
        });
        return ()=>{
            form.removeEffects(id);
        };
    }, []);
    const handleCreateAction = async (props)=>{
        var _field_componentProps_fieldNames, _field_componentProps;
        const { search: value, callBack } = props;
        const { data: { data } } = await resource.create({
            values: {
                [(null == field ? void 0 : null == (_field_componentProps = field.componentProps) ? void 0 : null == (_field_componentProps_fieldNames = _field_componentProps.fieldNames) ? void 0 : _field_componentProps_fieldNames.label) || 'id']: value
            }
        });
        if (data) {
            if ([
                'm2m',
                'o2m'
            ].includes(null == collectionField ? void 0 : collectionField.interface) && false !== multiple) {
                const values = form.getValuesIn(field.path) || [];
                values.push(data);
                form.setValuesIn(field.path, values);
                field.onInput(values);
            } else {
                form.setValuesIn(field.path, data);
                field.onInput(data);
            }
            isFunction(callBack) && (null == callBack || callBack());
            message.success(t('Saved successfully'));
        }
    };
    const QuickAddContent = (props)=>/*#__PURE__*/ jsxs("div", {
            onClick: ()=>handleCreateAction(props),
            style: {
                cursor: 'pointer',
                padding: '5px 12px',
                color: '#0d0c0c'
            },
            children: [
                /*#__PURE__*/ jsx(PlusOutlined, {}),
                /*#__PURE__*/ jsx("span", {
                    style: {
                        paddingLeft: 5
                    },
                    children: t('Add') + " \u201C".concat(props.search, "\u201D ")
                })
            ]
        });
    return /*#__PURE__*/ jsx("div", {
        children: /*#__PURE__*/ jsxs(Space.Compact, {
            style: {
                display: 'flex',
                lineHeight: '32px'
            },
            children: [
                /*#__PURE__*/ jsx(RemoteSelect, {
                    style: {
                        width: '100%'
                    },
                    ...props,
                    size: 'middle',
                    objectValue: objectValue,
                    value: value || innerValue,
                    service: service,
                    onChange: (value)=>{
                        var _props_onChange;
                        const val = (null == value ? void 0 : value.length) !== 0 ? value : null;
                        null == (_props_onChange = props.onChange) || _props_onChange.call(props, val);
                    },
                    CustomDropdownRender: 'quickAdd' === addMode && QuickAddContent
                }),
                ('modalAdd' === addMode || isAllowAddNew) && /*#__PURE__*/ jsx(RecordProvider, {
                    isNew: true,
                    record: null,
                    parent: recordData,
                    children: /*#__PURE__*/ jsx(RecursionField, {
                        onlyRenderProperties: true,
                        basePath: field.address,
                        schema: fieldSchema,
                        filterProperties: (s)=>'Action' === s['x-component']
                    })
                })
            ]
        })
    }, fieldSchema.name);
}, {
    displayName: 'AssociationSelect'
});
const AssociationSelect = InternalAssociationSelect;
const AssociationSelectReadPretty = connect((props)=>{
    const service = hooks(props);
    useApp();
    if (props.fieldNames) return /*#__PURE__*/ jsx(RemoteSelect.ReadPretty, {
        ...props,
        service: service
    });
    return null;
}, mapProps({
    dataSource: 'options',
    loading: true
}, (props, field)=>({
        ...props,
        fieldNames: props.fieldNames && {
            ...props.fieldNames,
            ...field.componentProps.fieldNames
        },
        suffixIcon: (null == field ? void 0 : field['loading']) || (null == field ? void 0 : field['validating']) ? /*#__PURE__*/ jsx(LoadingOutlined, {}) : props.suffixIcon
    })));
export { AssociationSelect, AssociationSelectReadPretty, filterAnalyses };
