import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import react, { useCallback, useContext } from "react";
import { RecursionField, action, each, observer, spliceArrayState, useFieldSchema } from "@tachybase/schema";
import { CloseOutlined, PlusOutlined } from "@ant-design/icons";
import { Button, Card, Divider, Tooltip } from "antd";
import { createStyles } from "antd-style";
import { useTranslation } from "react-i18next";
import { FormActiveFieldsProvider } from "../../../block-provider/index.mjs";
import { useCollection } from "../../../data-source/index.mjs";
import { useCollectionRecord, useCollectionRecordData } from "../../../data-source/collection-record/CollectionRecordProvider.mjs";
import { isNewRecord, markRecordAsNew } from "../../../data-source/collection-record/isNewRecord.mjs";
import { FlagProvider } from "../../../flag-provider/index.mjs";
import { RecordIndexProvider, RecordProvider } from "../../../record-provider/index.mjs";
import { isPatternDisabled, isSystemField } from "../../../schema-settings/index.mjs";
import { DefaultValueProvider, interfacesOfUnsupportedDefaultValue } from "../../../schema-settings/hooks/useIsAllowToSetDefaultValue.mjs";
import { AssociationFieldContext } from "./context.mjs";
import { SubFormProvider, useAssociationFieldContext } from "./hooks.mjs";
function _tagged_template_literal(strings, raw) {
    if (!raw) raw = strings.slice(0);
    return Object.freeze(Object.defineProperties(strings, {
        raw: {
            value: Object.freeze(raw)
        }
    }));
}
function _templateObject() {
    const data = _tagged_template_literal([
        "\n      position: relative;\n      .ant-input {\n        width: 100%;\n      }\n    "
    ]);
    _templateObject = function() {
        return data;
    };
    return data;
}
function _templateObject1() {
    const data = _tagged_template_literal([
        "\n      > .ant-card-body > .ant-divider:last-child {\n        display: none;\n      }\n    "
    ]);
    _templateObject1 = function() {
        return data;
    };
    return data;
}
function _templateObject2() {
    const data = _tagged_template_literal([
        "\n      border: 1px solid #f0f0f0 !important;\n      box-shadow: none;\n    "
    ]);
    _templateObject2 = function() {
        return data;
    };
    return data;
}
const useStyles = createStyles((param)=>{
    let { css } = param;
    return {
        input: css(_templateObject()),
        card: css(_templateObject1()),
        button: css(_templateObject2())
    };
});
const Nester = (props)=>{
    const { options } = useContext(AssociationFieldContext);
    if ([
        'hasOne',
        'belongsTo'
    ].includes(options.type)) return /*#__PURE__*/ jsx(FlagProvider, {
        isInSubForm: true,
        children: /*#__PURE__*/ jsx(ToOneNester, {
            ...props
        })
    });
    if ([
        'hasMany',
        'belongsToMany'
    ].includes(options.type)) return /*#__PURE__*/ jsx(FlagProvider, {
        isInSubForm: true,
        children: /*#__PURE__*/ jsx(ToManyNester, {
            ...props
        })
    });
    return null;
};
const ToOneNester = (props)=>{
    const { field } = useAssociationFieldContext();
    const recordV2 = useCollectionRecord();
    const collection = useCollection();
    const isAllowToSetDefaultValue = useCallback((param)=>{
        let { form, fieldSchema, collectionField, getInterface, formBlockType } = param;
        var _fieldSchema_xcomponentprops;
        if (!collectionField) return false;
        if (collectionField.target && (null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.mode) && ![
            'Picker',
            'Select'
        ].includes(fieldSchema['x-component-props'].mode)) return false;
        if ('update' === formBlockType) return false;
        return !(null == form ? void 0 : form.readPretty) && !isPatternDisabled(fieldSchema) && !interfacesOfUnsupportedDefaultValue.includes(null == collectionField ? void 0 : collectionField.interface) && !isSystemField(collectionField, getInterface);
    }, []);
    return /*#__PURE__*/ jsx(FormActiveFieldsProvider, {
        name: "nester",
        children: /*#__PURE__*/ jsx(SubFormProvider, {
            value: {
                value: field.value,
                collection
            },
            children: /*#__PURE__*/ jsx(RecordProvider, {
                isNew: null == recordV2 ? void 0 : recordV2.isNew,
                record: field.value,
                parent: null == recordV2 ? void 0 : recordV2.data,
                children: /*#__PURE__*/ jsx(DefaultValueProvider, {
                    isAllowToSetDefaultValue: isAllowToSetDefaultValue,
                    children: /*#__PURE__*/ jsx(Card, {
                        bordered: true,
                        children: props.children
                    })
                })
            })
        })
    });
};
const ToManyNester = observer((props)=>{
    const fieldSchema = useFieldSchema();
    const { options, field, allowMultiple, allowDissociate } = useAssociationFieldContext();
    const { t } = useTranslation();
    const recordData = useCollectionRecordData();
    const collection = useCollection();
    if (!Array.isArray(field.value)) field.value = [];
    const isAllowToSetDefaultValue = useCallback((param)=>{
        let { form, fieldSchema, collectionField, getInterface } = param;
        var _fieldSchema_xcomponentprops;
        if (!collectionField) return false;
        if (collectionField.target && (null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.mode) && ![
            'Picker',
            'Select'
        ].includes(fieldSchema['x-component-props'].mode)) return false;
        return !(null == form ? void 0 : form.readPretty) && !isPatternDisabled(fieldSchema) && !interfacesOfUnsupportedDefaultValue.includes(null == collectionField ? void 0 : collectionField.interface) && !isSystemField(collectionField, getInterface);
    }, []);
    const { styles } = useStyles();
    return field.value.length > 0 ? /*#__PURE__*/ jsx(Card, {
        bordered: true,
        style: {
            position: 'relative'
        },
        className: styles.card,
        children: field.value.map((value, index)=>{
            let allowed = allowDissociate;
            if (!allowDissociate) allowed = !(null == value ? void 0 : value[options.targetKey]);
            return /*#__PURE__*/ jsxs(react.Fragment, {
                children: [
                    /*#__PURE__*/ jsxs("div", {
                        style: {
                            textAlign: 'right'
                        },
                        children: [
                            field.editable && allowMultiple && /*#__PURE__*/ jsx(Tooltip, {
                                title: t('Add new'),
                                children: /*#__PURE__*/ jsx(PlusOutlined, {
                                    style: {
                                        zIndex: 1000,
                                        marginRight: '10px',
                                        color: '#a8a3a3'
                                    },
                                    onClick: ()=>{
                                        action(()=>{
                                            if (!Array.isArray(field.value)) field.value = [];
                                            spliceArrayState(field, {
                                                startIndex: index + 1,
                                                insertCount: 1
                                            });
                                            field.value.splice(index + 1, 0, markRecordAsNew({}));
                                            each(field.form.fields, (targetField, key)=>{
                                                if (!targetField) delete field.form.fields[key];
                                            });
                                            return field.onInput(field.value);
                                        });
                                    }
                                })
                            }, 'add'),
                            !field.readPretty && allowed && /*#__PURE__*/ jsx(Tooltip, {
                                title: t('Remove'),
                                children: /*#__PURE__*/ jsx(CloseOutlined, {
                                    style: {
                                        zIndex: 1000,
                                        color: '#a8a3a3'
                                    },
                                    onClick: ()=>{
                                        action(()=>{
                                            spliceArrayState(field, {
                                                startIndex: index,
                                                deleteCount: 1
                                            });
                                            field.value.splice(index, 1);
                                            return field.onInput(field.value);
                                        });
                                    }
                                })
                            }, 'remove')
                        ]
                    }),
                    /*#__PURE__*/ jsx(FormActiveFieldsProvider, {
                        name: "nester",
                        children: /*#__PURE__*/ jsx(SubFormProvider, {
                            value: {
                                value,
                                collection
                            },
                            children: /*#__PURE__*/ jsx(RecordProvider, {
                                isNew: isNewRecord(value),
                                record: value,
                                parent: recordData,
                                children: /*#__PURE__*/ jsx(RecordIndexProvider, {
                                    index: index,
                                    children: /*#__PURE__*/ jsx(DefaultValueProvider, {
                                        isAllowToSetDefaultValue: isAllowToSetDefaultValue,
                                        children: /*#__PURE__*/ jsx(RecursionField, {
                                            onlyRenderProperties: true,
                                            basePath: field.address.concat(index),
                                            schema: fieldSchema
                                        })
                                    })
                                })
                            })
                        })
                    }),
                    /*#__PURE__*/ jsx(Divider, {})
                ]
            }, index);
        })
    }) : /*#__PURE__*/ jsx(Fragment, {
        children: field.editable && allowMultiple && /*#__PURE__*/ jsx(Tooltip, {
            title: t('Add new'),
            children: /*#__PURE__*/ jsx(Button, {
                type: 'default',
                className: styles.button,
                block: true,
                icon: /*#__PURE__*/ jsx(PlusOutlined, {}),
                onClick: ()=>{
                    const result = field.value;
                    result.push({});
                    field.value = result;
                }
            })
        }, 'add')
    });
}, {
    displayName: 'ToManyNester'
});
export { Nester };
