import { jsx } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from "react";
import { observer, useField, useFieldSchema } from "@tachybase/schema";
import { useCollectionManager_deprecated } from "../../../collection-manager/index.mjs";
import { markRecordAsNew } from "../../../data-source/collection-record/isNewRecord.mjs";
import { AssociationFieldContext } from "./context.mjs";
const AssociationFieldProvider = observer((props)=>{
    var _fieldSchema_xcomponentprops, _fieldSchema_xcomponentprops1, _fieldSchema_xcomponentprops2;
    const field = useField();
    const { getCollectionJoinField, getCollection } = useCollectionManager_deprecated();
    const fieldSchema = useFieldSchema();
    const allowMultiple = (null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.multiple) !== false;
    const allowDissociate = (null == (_fieldSchema_xcomponentprops1 = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops1.allowDissociate) !== false;
    const collectionField = useMemo(()=>getCollectionJoinField(fieldSchema['x-collection-field']), [
        fieldSchema['x-collection-field'],
        fieldSchema.name
    ]);
    const isFileCollection = useMemo(()=>{
        var _getCollection;
        return (null == (_getCollection = getCollection(null == collectionField ? void 0 : collectionField.target)) ? void 0 : _getCollection.template) === 'file';
    }, [
        fieldSchema['x-collection-field']
    ]);
    const isTreeCollection = useMemo(()=>{
        var _getCollection;
        return (null == (_getCollection = getCollection(null == collectionField ? void 0 : collectionField.target)) ? void 0 : _getCollection.template) === 'tree';
    }, [
        fieldSchema['x-collection-field']
    ]);
    const currentMode = useMemo(()=>{
        var _fieldSchema_xcomponentprops;
        return (null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.mode) || (isFileCollection ? 'FileManager' : isTreeCollection ? 'Cascader' : 'Select');
    }, [
        null == (_fieldSchema_xcomponentprops2 = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops2.mode
    ]);
    const fieldValue = useMemo(()=>JSON.stringify(field.value), [
        field.value
    ]);
    const [loading, setLoading] = useState(true);
    useEffect(()=>{
        setLoading(true);
        if (!collectionField) return void setLoading(false);
        if (field.value && field.form['__template'] && [
            'Nester',
            'SubTable',
            'PopoverNester'
        ].includes(currentMode)) {
            if ([
                'belongsTo',
                'hasOne'
            ].includes(collectionField.type)) {
                var _field_value;
                if (null == (_field_value = field.value) ? void 0 : _field_value[collectionField.targetKey]) delete field.value[collectionField.targetKey];
                field.value = {
                    ...field.initialValue,
                    ...field.value
                };
            } else if ([
                'belongsToMany',
                'hasMany'
            ].includes(collectionField.type)) {
                if (Array.isArray(field.value)) field.value = field.value.map((v)=>{
                    var _field_initialValue;
                    delete v[collectionField.targetKey];
                    return {
                        ...null == (_field_initialValue = field.initialValue) ? void 0 : _field_initialValue[0],
                        ...v
                    };
                });
            }
        }
        if (null !== field.value && void 0 !== field.value) {
            if ([
                'Nester',
                'PopoverNester'
            ].includes(currentMode) && Array.isArray(field.value)) {
                if (0 === field.value.length && [
                    'belongsToMany',
                    'hasMany'
                ].includes(collectionField.type)) field.value = [
                    markRecordAsNew({})
                ];
            }
            setLoading(false);
            return;
        }
        if ([
            'Nester'
        ].includes(currentMode)) {
            if ([
                'belongsTo',
                'hasOne'
            ].includes(collectionField.type)) field.value = {};
            else if ([
                'belongsToMany',
                'hasMany'
            ].includes(collectionField.type)) field.value = [
                markRecordAsNew({})
            ];
        }
        if ('SubTable' === currentMode) field.value = [];
        setLoading(false);
    }, [
        currentMode,
        collectionField,
        fieldValue
    ]);
    if (loading) return null;
    return collectionField ? /*#__PURE__*/ jsx(AssociationFieldContext.Provider, {
        value: {
            options: collectionField,
            field,
            allowMultiple,
            allowDissociate,
            currentMode
        },
        children: props.children
    }) : null;
}, {
    displayName: 'AssociationFieldProvider'
});
export { AssociationFieldProvider };
