import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useContext, useMemo, useState } from "react";
import { RecursionField, observer, useField, useFieldSchema } from "@tachybase/schema";
import { Select, Space } from "antd";
import { differenceBy, unionBy } from "lodash";
import { FormProvider, RecordPickerContext, RecordPickerProvider, SchemaComponentOptions, useActionContext } from "../../index.mjs";
import { CollectionProvider_deprecated, RecordProvider, useCollectionRecordData, useFormBlockContext } from "../../../index.mjs";
import { TableSelectorParamsProvider, useTableSelectorProps } from "../../../block-provider/TableSelectorProvider.mjs";
import { useCompile } from "../../hooks/index.mjs";
import { ActionContextProvider, OpenMode } from "../action/index.mjs";
import { useAssociationFieldContext, useFieldNames, useInsertSchema } from "./hooks.mjs";
import schema from "./schema.mjs";
import { flatData, getLabelFormatValue, useLabelUiSchema } from "./util.mjs";
const InternalPicker_useTableSelectorProps = ()=>{
    const field = useField();
    const { multiple, options = [], setSelectedRows, selectedRows: rcSelectRows = [], onChange } = useContext(RecordPickerContext);
    const { onRowSelectionChange, rowKey = 'id', ...others } = useTableSelectorProps();
    const { setVisible } = useActionContext();
    return {
        ...others,
        rowKey,
        rowSelection: {
            type: multiple ? 'checkbox' : 'radio',
            selectedRowKeys: null == rcSelectRows ? void 0 : rcSelectRows.filter((item)=>options.every((row)=>row[rowKey] !== item[rowKey])).map((item)=>item[rowKey])
        },
        onRowSelectionChange (selectedRowKeys, selectedRows) {
            if (multiple) {
                const scopeRows = flatData(field.value) || [];
                const allSelectedRows = rcSelectRows || [];
                const otherRows = differenceBy(allSelectedRows, scopeRows, rowKey);
                const unionSelectedRows = unionBy(otherRows, selectedRows, rowKey);
                const unionSelectedRowKeys = unionSelectedRows.map((item)=>item[rowKey]);
                null == setSelectedRows || setSelectedRows(unionSelectedRows);
                null == onRowSelectionChange || onRowSelectionChange(unionSelectedRowKeys, unionSelectedRows);
            } else {
                null == setSelectedRows || setSelectedRows(selectedRows);
                null == onRowSelectionChange || onRowSelectionChange(selectedRowKeys, selectedRows);
                onChange((null == selectedRows ? void 0 : selectedRows[0]) || null);
                setVisible(false);
            }
        }
    };
};
const InternalPicker = observer((props)=>{
    var _fieldSchema_xcomponentprops;
    const { value, multiple, openSize, onChange, quickUpload, selectFile, shouldMountElement, ...others } = props;
    const field = useField();
    const fieldNames = useFieldNames(props);
    const [visibleSelector, setVisibleSelector] = useState(false);
    const fieldSchema = useFieldSchema();
    const insertSelector = useInsertSchema('Selector');
    const { options: collectionField } = useAssociationFieldContext();
    const { collectionName } = useFormBlockContext();
    const compile = useCompile();
    const labelUiSchema = useLabelUiSchema(collectionField, (null == fieldNames ? void 0 : fieldNames.label) || 'label');
    const isAllowAddNew = fieldSchema['x-add-new'];
    const [selectedRows, setSelectedRows] = useState([]);
    const recordData = useCollectionRecordData();
    const options = useMemo(()=>{
        if (value && Object.keys(value).length > 0) {
            const opts = (Array.isArray(value) ? value : value ? [
                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 [];
    }, [
        value,
        null == fieldNames ? void 0 : fieldNames.label
    ]);
    const pickerProps = {
        size: 'small',
        fieldNames,
        multiple: false !== multiple && [
            'o2m',
            'm2m'
        ].includes(null == collectionField ? void 0 : collectionField.interface),
        association: {
            target: null == collectionField ? void 0 : collectionField.target
        },
        options,
        onChange: null == props ? void 0 : props.onChange,
        selectedRows,
        setSelectedRows,
        collectionField,
        currentFormCollection: collectionName
    };
    const getValue = ()=>{
        var _value_filter;
        if (null == multiple) return null;
        return Array.isArray(value) ? null == (_value_filter = value.filter(Boolean)) ? void 0 : _value_filter.map((v)=>null == v ? void 0 : v[fieldNames.value]) : null == value ? void 0 : value[fieldNames.value];
    };
    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 usePickActionProps = ()=>{
        const { setVisible } = useActionContext();
        const { multiple, selectedRows, onChange, options, collectionField } = useContext(RecordPickerContext);
        return {
            onClick () {
                multiple ? onChange(unionBy(selectedRows, options, (null == collectionField ? void 0 : collectionField.targetKey) || 'id')) : onChange((null == selectedRows ? void 0 : selectedRows[0]) || null);
                setVisible(false);
            },
            style: {
                display: false !== multiple && [
                    'o2m',
                    'm2m'
                ].includes(null == collectionField ? void 0 : collectionField.interface) ? 'block' : 'none'
            }
        };
    };
    return /*#__PURE__*/ jsxs(Fragment, {
        children: [
            /*#__PURE__*/ jsxs(Space.Compact, {
                style: {
                    display: 'flex',
                    lineHeight: '32px'
                },
                children: [
                    /*#__PURE__*/ jsx("div", {
                        style: {
                            width: '100%'
                        },
                        children: /*#__PURE__*/ jsx(Select, {
                            role: "button",
                            "data-testid": "select-data-picker",
                            style: {
                                width: '100%'
                            },
                            popupMatchSelectWidth: false,
                            ...others,
                            mode: multiple ? 'multiple' : props.mode,
                            fieldNames: fieldNames,
                            onDropdownVisibleChange: (open)=>{
                                insertSelector(schema.Selector);
                                setVisibleSelector(true);
                            },
                            allowClear: true,
                            onChange: (changed)=>{
                                if (changed) {
                                    if (Array.isArray(changed)) {
                                        if (!changed.length) {
                                            onChange([]);
                                            setSelectedRows([]);
                                            return;
                                        }
                                        const values = null == options ? void 0 : options.filter((option)=>changed.includes(option[fieldNames.value]));
                                        onChange(values);
                                        setSelectedRows(values);
                                    }
                                } else {
                                    const value = multiple ? [] : null;
                                    onChange(value);
                                    setSelectedRows(value);
                                }
                            },
                            options: options,
                            value: getValue(),
                            open: false
                        })
                    }),
                    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']
                        })
                    })
                ]
            }),
            /*#__PURE__*/ jsx(ActionContextProvider, {
                value: {
                    openSize: (null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops['openSize']) || 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: InternalPicker_useTableSelectorProps
                                    },
                                    children: /*#__PURE__*/ jsx(RecursionField, {
                                        onlyRenderProperties: true,
                                        basePath: field.address,
                                        schema: fieldSchema,
                                        filterProperties: (s)=>'AssociationField.Selector' === s['x-component']
                                    })
                                })
                            })
                        })
                    })
                })
            })
        ]
    });
}, {
    displayName: 'InternalPicker'
});
export { InternalPicker, InternalPicker_useTableSelectorProps as useTableSelectorProps };
