import { jsx, jsxs } from "react/jsx-runtime";
import react, { Fragment, createElement, useEffect, useState } from "react";
import { RecursionField, observer, toArr, useField, useFieldSchema } from "@tachybase/schema";
import { CopyOutlined } from "@ant-design/icons";
import { ArrayBase } from "@tego/client";
import { Badge, Card, Collapse, Empty, Input } from "antd";
import classnames from "classnames";
import { cloneDeep } from "lodash";
import { useTranslation } from "react-i18next";
import { useToken } from "../../../style/index.mjs";
import { useStyles } from "./LinkageHeader.style.mjs";
const LinkageRulesTitle = (props)=>{
    var _array_field;
    const array = ArrayBase.useArray();
    const index = ArrayBase.useIndex(props.index);
    const { t } = useTranslation();
    const value = null == array ? void 0 : null == (_array_field = array.field) ? void 0 : _array_field.value[index];
    return /*#__PURE__*/ jsx(Input.TextArea, {
        value: value.title,
        defaultValue: t('Linkage rule'),
        onChange: (ev)=>{
            ev.stopPropagation();
            array.field.value.splice(index, 1, {
                ...value,
                title: ev.target.value
            });
        },
        onBlur: (ev)=>{
            ev.stopPropagation();
            array.field.value.splice(index, 1, {
                ...value,
                title: ev.target.value
            });
        },
        autoSize: true,
        style: {
            width: '70%',
            border: 'none'
        },
        onClick: (e)=>{
            e.stopPropagation();
        }
    });
};
const isAdditionComponent = (schema)=>{
    var _schema_xcomponent_indexOf, _schema_xcomponent;
    return (null == (_schema_xcomponent = schema['x-component']) ? void 0 : null == (_schema_xcomponent_indexOf = _schema_xcomponent.indexOf) ? void 0 : _schema_xcomponent_indexOf.call(_schema_xcomponent, 'Addition')) > -1;
};
const isIndexComponent = (schema)=>{
    var _schema_xcomponent_indexOf, _schema_xcomponent;
    return (null == (_schema_xcomponent = schema['x-component']) ? void 0 : null == (_schema_xcomponent_indexOf = _schema_xcomponent.indexOf) ? void 0 : _schema_xcomponent_indexOf.call(_schema_xcomponent, 'Index')) > -1;
};
const isRemoveComponent = (schema)=>{
    var _schema_xcomponent_indexOf, _schema_xcomponent;
    return (null == (_schema_xcomponent = schema['x-component']) ? void 0 : null == (_schema_xcomponent_indexOf = _schema_xcomponent.indexOf) ? void 0 : _schema_xcomponent_indexOf.call(_schema_xcomponent, 'Remove')) > -1;
};
const isMoveUpComponent = (schema)=>{
    var _schema_xcomponent_indexOf, _schema_xcomponent;
    return (null == (_schema_xcomponent = schema['x-component']) ? void 0 : null == (_schema_xcomponent_indexOf = _schema_xcomponent.indexOf) ? void 0 : _schema_xcomponent_indexOf.call(_schema_xcomponent, 'MoveUp')) > -1;
};
const isMoveDownComponent = (schema)=>{
    var _schema_xcomponent_indexOf, _schema_xcomponent;
    return (null == (_schema_xcomponent = schema['x-component']) ? void 0 : null == (_schema_xcomponent_indexOf = _schema_xcomponent.indexOf) ? void 0 : _schema_xcomponent_indexOf.call(_schema_xcomponent, 'MoveDown')) > -1;
};
const isCopyComponent = (schema)=>{
    var _schema_xcomponent_indexOf, _schema_xcomponent;
    return (null == (_schema_xcomponent = schema['x-component']) ? void 0 : null == (_schema_xcomponent_indexOf = _schema_xcomponent.indexOf) ? void 0 : _schema_xcomponent_indexOf.call(_schema_xcomponent, 'Copy')) > -1;
};
const isOperationComponent = (schema)=>isAdditionComponent(schema) || isRemoveComponent(schema) || isMoveDownComponent(schema) || isMoveUpComponent(schema) || isCopyComponent(schema);
const range = (count)=>Array.from({
        length: count
    }).map((_, i)=>i);
const takeDefaultActiveKeys = (dataSourceLength, defaultOpenPanelCount)=>{
    if (dataSourceLength < defaultOpenPanelCount) return range(dataSourceLength);
    return range(defaultOpenPanelCount);
};
const insertActiveKeys = (activeKeys, index)=>{
    if (activeKeys.length <= index) return activeKeys.concat(index);
    return activeKeys.reduce((buf, key)=>{
        if (key < index) return buf.concat(key);
        if (key === index) return buf.concat([
            key,
            key + 1
        ]);
        return buf.concat(key + 1);
    }, []);
};
const ArrayCollapse = observer((props)=>{
    const { styles } = useStyles();
    const field = useField();
    const dataSource = Array.isArray(field.value) ? field.value : [];
    const [activeKeys, setActiveKeys] = useState(takeDefaultActiveKeys(dataSource.length, props.defaultOpenPanelCount));
    const schema = useFieldSchema();
    useEffect(()=>{
        if (!field.modified && dataSource.length) setActiveKeys(takeDefaultActiveKeys(dataSource.length, props.defaultOpenPanelCount));
    }, [
        dataSource.length,
        field
    ]);
    if (!schema) throw new Error('can not found schema object');
    const renderAddition = ()=>schema.reduceProperties((addition, schema, key)=>{
            if (isAdditionComponent(schema)) return /*#__PURE__*/ jsx(RecursionField, {
                schema: schema,
                name: key
            });
            return addition;
        }, null);
    const renderEmpty = ()=>{
        if (dataSource.length) return;
        return /*#__PURE__*/ jsx(Card, {
            className: classnames("".concat(styles.arrayCollapseItem), props.className),
            children: /*#__PURE__*/ jsx(Empty, {})
        });
    };
    const renderItems = ()=>/*#__PURE__*/ jsx(Collapse, {
            ...props,
            activeKey: activeKeys,
            onChange: (keys)=>setActiveKeys(toArr(keys).map(Number)),
            className: classnames("".concat(styles.arrayCollapseItem), props.className),
            children: dataSource.map((item, index)=>{
                const items = Array.isArray(schema.items) ? schema.items[index] || schema.items[0] : schema.items;
                const panelProps = field.query("".concat(field.address, ".").concat(index)).get('componentProps');
                const props = items['x-component-props'];
                const header = ()=>{
                    const header = "".concat((null == panelProps ? void 0 : panelProps.header) || props.header || field.title);
                    const path = field.address.concat(index);
                    const errors = field.form.queryFeedbacks({
                        type: 'error',
                        address: "".concat(path, ".**")
                    });
                    return /*#__PURE__*/ jsxs(ArrayBase.Item, {
                        index: index,
                        record: ()=>{
                            var _field_value;
                            return null == (_field_value = field.value) ? void 0 : _field_value[index];
                        },
                        children: [
                            /*#__PURE__*/ jsx(RecursionField, {
                                schema: items,
                                name: index,
                                filterProperties: (schema)=>{
                                    if (!isIndexComponent(schema)) return false;
                                    return true;
                                },
                                onlyRenderProperties: true
                            }),
                            errors.length ? /*#__PURE__*/ jsx(Badge, {
                                size: "small",
                                className: "errors-badge",
                                count: errors.length,
                                children: header
                            }) : /*#__PURE__*/ jsx(LinkageRulesTitle, {
                                item: item.initialValue || item,
                                index: index
                            })
                        ]
                    });
                };
                const extra = /*#__PURE__*/ jsxs(ArrayBase.Item, {
                    index: index,
                    record: item,
                    children: [
                        /*#__PURE__*/ jsx(RecursionField, {
                            schema: items,
                            name: index,
                            filterProperties: (schema)=>{
                                if (!isOperationComponent(schema)) return false;
                                return true;
                            },
                            onlyRenderProperties: true
                        }),
                        null == panelProps ? void 0 : panelProps.extra
                    ]
                });
                const content = /*#__PURE__*/ jsx(RecursionField, {
                    schema: items,
                    name: index,
                    filterProperties: (schema)=>{
                        if (isIndexComponent(schema)) return false;
                        if (isOperationComponent(schema)) return false;
                        return true;
                    }
                });
                return /*#__PURE__*/ createElement(Collapse.Panel, {
                    ...props,
                    ...panelProps,
                    forceRender: true,
                    key: index,
                    header: header(),
                    extra: extra
                }, /*#__PURE__*/ jsx(ArrayBase.Item, {
                    index: index,
                    record: item,
                    children: content
                }, index));
            })
        });
    return /*#__PURE__*/ jsxs(ArrayBase, {
        onAdd: (index)=>{
            setActiveKeys(insertActiveKeys(activeKeys, index));
        },
        children: [
            renderEmpty(),
            renderItems(),
            renderAddition()
        ]
    });
}, {
    displayName: 'ArrayCollapse'
});
const CollapsePanel = (param)=>{
    let { children } = param;
    return /*#__PURE__*/ jsx(Fragment, {
        children: children
    });
};
CollapsePanel.displayName = 'CollapsePanel';
ArrayCollapse.defaultProps = {
    defaultOpenPanelCount: 5
};
ArrayCollapse.displayName = 'ArrayCollapse';
ArrayCollapse.CollapsePanel = CollapsePanel;
ArrayBase.mixin(ArrayCollapse);
const LinkageHeader = ArrayCollapse;
ArrayCollapse.Copy = /*#__PURE__*/ react.forwardRef((props, ref)=>{
    var _array_field;
    const { token } = useToken();
    const self = useField();
    const array = ArrayBase.useArray();
    const index = ArrayBase.useIndex(props.index);
    if (!array) return null;
    if ((null == (_array_field = array.field) ? void 0 : _array_field.pattern) !== 'editable') return null;
    return /*#__PURE__*/ jsx(CopyOutlined, {
        ...props,
        style: {
            transition: 'all 0.25s ease-in-out',
            color: token.colorText,
            fontSize: token.fontSizeLG,
            marginLeft: 6
        },
        ref: ref,
        onClick: (e)=>{
            var _array_props, _array_field;
            if (null == self ? void 0 : self.disabled) return;
            e.stopPropagation();
            if (null == (_array_props = array.props) ? void 0 : _array_props.disabled) return;
            const value = cloneDeep(null == array ? void 0 : null == (_array_field = array.field) ? void 0 : _array_field.value[index]);
            array.field.push(value);
            if (props.onClick) props.onClick(e);
        }
    });
});
ArrayCollapse.Copy.displayName = 'ArrayCollapse.Copy';
export { ArrayCollapse, LinkageHeader as default };
