import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useContext, useMemo, useState } from "react";
import { RecursionField, action, exchangeArrayState, isArr, observer, useFieldSchema } from "@tachybase/schema";
import { Button } from "antd";
import { createStyles } from "antd-style";
import { unionBy, uniqBy } from "lodash";
import { useTranslation } from "react-i18next";
import { FormProvider, RecordPickerContext, RecordPickerProvider, SchemaComponentOptions, useActionContext } from "../../index.mjs";
import { useCreateActionProps } from "../../../block-provider/hooks/index.mjs";
import { FormActiveFieldsProvider } from "../../../block-provider/hooks/useFormActiveFields.mjs";
import { TableSelectorParamsProvider } from "../../../block-provider/TableSelectorProvider.mjs";
import { CollectionProvider_deprecated } from "../../../collection-manager/index.mjs";
import { CollectionRecordProvider, useCollectionRecord } from "../../../data-source/index.mjs";
import { markRecordAsNew } from "../../../data-source/collection-record/isNewRecord.mjs";
import { FlagProvider } from "../../../flag-provider/index.mjs";
import { useCompile } from "../../hooks/index.mjs";
import { ActionContextProvider, OpenMode } from "../action/index.mjs";
import { Table } from "../table-v2/Table.mjs";
import { useAssociationFieldContext, useFieldNames } from "./hooks.mjs";
import { useTableSelectorProps } from "./InternalPicker.mjs";
import { InternalCollapse } from "./SubTabs/InternalCollapse.mjs";
import { getLabelFormatValue, useLabelUiSchema } from "./util.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      display: block;\n      border-radius: 0px;\n      border-right: 1px solid rgba(0, 0, 0, 0.06);\n    "
    ]);
    _templateObject = function() {
        return data;
    };
    return data;
}
function _templateObject1() {
    const data = _tagged_template_literal([
        "\n      display: block;\n      border-radius: 0px;\n    "
    ]);
    _templateObject1 = function() {
        return data;
    };
    return data;
}
function _templateObject2() {
    const data = _tagged_template_literal([
        "\n      .ant-formily-item.ant-formily-item-feedback-layout-loose {\n        margin-bottom: 0px !important;\n      }\n      .ant-formily-editable {\n        vertical-align: sub;\n      }\n      .ant-table-footer {\n        display: flex;\n      }\n    "
    ]);
    _templateObject2 = function() {
        return data;
    };
    return data;
}
function _templateObject3() {
    const data = _tagged_template_literal([
        "\n      .ant-table-footer {\n        padding: 0 !important;\n      }\n      .ant-formily-item-error-help {\n        display: none;\n      }\n      .ant-description-textarea {\n        line-height: 34px;\n      }\n      .ant-table-cell .ant-formily-item-error-help {\n        display: block;\n        position: absolute;\n        font-size: 12px;\n        top: 100%;\n        background: #fff;\n        width: 100%;\n        margin-top: -15px;\n        padding: 3px;\n        z-index: 1;\n        border-radius: 3px;\n        box-shadow: 0 0 10px #eee;\n        animation: none;\n        transform: translateY(0);\n        opacity: 1;\n      }\n    "
    ]);
    _templateObject3 = function() {
        return data;
    };
    return data;
}
function _templateObject4() {
    const data = _tagged_template_literal([
        "\n      position: relative;\n      .ant-input {\n        width: 100%;\n      }\n    "
    ]);
    _templateObject4 = function() {
        return data;
    };
    return data;
}
const useStyles = createStyles((param)=>{
    let { css } = param;
    return {
        addNew: css(_templateObject()),
        select: css(_templateObject1()),
        table: css(_templateObject2()),
        container: css(_templateObject3()),
        input: css(_templateObject4())
    };
});
const SubTable = observer((props)=>{
    const { openSize } = props;
    const { styles } = useStyles();
    const { field, options: collectionField } = useAssociationFieldContext();
    const { t } = useTranslation();
    const [visibleSelector, setVisibleSelector] = useState(false);
    const [selectedRows, setSelectedRows] = useState([]);
    const fieldNames = useFieldNames(props);
    const fieldSchema = useFieldSchema();
    const compile = useCompile();
    const labelUiSchema = useLabelUiSchema(collectionField, (null == fieldNames ? void 0 : fieldNames.label) || 'label');
    const recordV2 = useCollectionRecord();
    const [fieldValue, setFieldValue] = useState([]);
    const move = (fromIndex, toIndex)=>{
        if (void 0 === toIndex) return;
        if (!isArr(field.value)) return;
        if (fromIndex === toIndex) return;
        return action(()=>{
            const fromItem = field.value[fromIndex];
            field.value.splice(fromIndex, 1);
            field.value.splice(toIndex, 0, fromItem);
            exchangeArrayState(field, {
                fromIndex,
                toIndex
            });
            return field.onInput(field.value);
        });
    };
    field.move = move;
    const options = useMemo(()=>{
        if (field.value && Object.keys(field.value).length > 0) {
            const opts = (Array.isArray(field.value) ? field.value : field.value ? [
                field.value
            ] : []).filter(Boolean).map((option)=>{
                const label = null == option ? void 0 : option[fieldNames.label];
                return {
                    ...option,
                    [fieldNames.label]: getLabelFormatValue(compile(labelUiSchema), compile(label))
                };
            });
            return opts;
        }
        return [];
    }, [
        field.value,
        null == fieldNames ? void 0 : fieldNames.label
    ]);
    const pickerProps = {
        size: 'small',
        fieldNames: field.componentProps.fieldNames,
        multiple: true,
        association: {
            target: null == collectionField ? void 0 : collectionField.target
        },
        options,
        onChange: null == props ? void 0 : props.onChange,
        selectedRows,
        setSelectedRows,
        collectionField
    };
    const usePickActionProps = ()=>{
        const { setVisible } = useActionContext();
        const { selectedRows, options, collectionField } = useContext(RecordPickerContext);
        return {
            onClick () {
                const selectData = unionBy(selectedRows, options, (null == collectionField ? void 0 : collectionField.targetKey) || 'id');
                const data = field.value || [];
                field.value = uniqBy(data.concat(selectData), (null == collectionField ? void 0 : collectionField.targetKey) || 'id');
                field.onInput(field.value);
                setVisible(false);
            }
        };
    };
    const getFilter = ()=>{
        const targetKey = (null == collectionField ? void 0 : collectionField.targetKey) || 'id';
        const list = options.map((option)=>option[targetKey]).filter(Boolean);
        const filter = list.length ? {
            $and: [
                {
                    ["".concat(targetKey, ".$ne")]: list
                }
            ]
        } : {};
        return filter;
    };
    const tabsProps = {
        ...props,
        fieldValue,
        setFieldValue
    };
    return /*#__PURE__*/ jsxs("div", {
        className: styles.container,
        children: [
            /*#__PURE__*/ jsx(FlagProvider, {
                isInSubTable: true,
                children: /*#__PURE__*/ jsx(CollectionRecordProvider, {
                    record: null,
                    parentRecord: recordV2,
                    children: /*#__PURE__*/ jsxs(FormActiveFieldsProvider, {
                        name: "nester",
                        children: [
                            /*#__PURE__*/ jsx(InternalCollapse, {
                                ...tabsProps
                            }),
                            /*#__PURE__*/ jsx(Table, {
                                className: styles.table,
                                bordered: true,
                                size: 'small',
                                field: field,
                                showIndex: true,
                                dragSort: field.editable,
                                showDel: field.editable,
                                setFieldValue: setFieldValue,
                                pagination: !!field.componentProps.pagination,
                                rowSelection: {
                                    type: 'none',
                                    hideSelectAll: true
                                },
                                footer: ()=>{
                                    var _field_componentProps, _field_componentProps1;
                                    return field.editable && /*#__PURE__*/ jsxs(Fragment, {
                                        children: [
                                            (null == (_field_componentProps = field.componentProps) ? void 0 : _field_componentProps.allowAddnew) !== false && /*#__PURE__*/ jsx(Button, {
                                                type: 'text',
                                                block: true,
                                                className: styles.addNew,
                                                onClick: ()=>{
                                                    field.value = field.value || [];
                                                    field.value.push(markRecordAsNew({}));
                                                    setFieldValue([
                                                        ...field.value
                                                    ]);
                                                },
                                                children: t('Add new')
                                            }),
                                            (null == (_field_componentProps1 = field.componentProps) ? void 0 : _field_componentProps1.allowSelectExistingRecord) && /*#__PURE__*/ jsx(Button, {
                                                type: 'text',
                                                block: true,
                                                className: styles.select,
                                                onClick: ()=>{
                                                    setVisibleSelector(true);
                                                },
                                                children: t('Select')
                                            })
                                        ]
                                    });
                                },
                                isSubTable: true
                            })
                        ]
                    })
                })
            }),
            /*#__PURE__*/ jsx(ActionContextProvider, {
                value: {
                    openSize,
                    openMode: OpenMode.DEFAULT,
                    visible: visibleSelector,
                    setVisible: setVisibleSelector
                },
                children: /*#__PURE__*/ jsx(RecordPickerProvider, {
                    ...pickerProps,
                    children: /*#__PURE__*/ jsx(CollectionProvider_deprecated, {
                        name: null == collectionField ? void 0 : collectionField.target,
                        children: /*#__PURE__*/ jsx(FormProvider, {
                            children: /*#__PURE__*/ jsx(TableSelectorParamsProvider, {
                                params: {
                                    filter: getFilter()
                                },
                                children: /*#__PURE__*/ jsx(SchemaComponentOptions, {
                                    scope: {
                                        usePickActionProps,
                                        useTableSelectorProps: useTableSelectorProps,
                                        useCreateActionProps: useCreateActionProps
                                    },
                                    children: /*#__PURE__*/ jsx(RecursionField, {
                                        onlyRenderProperties: true,
                                        basePath: field.address,
                                        schema: fieldSchema.parent,
                                        filterProperties: (s)=>'AssociationField.Selector' === s['x-component']
                                    })
                                })
                            })
                        })
                    })
                })
            })
        ]
    });
}, {
    displayName: 'SubTable'
});
export { SubTable };
