import { jsx, jsxs } from "react/jsx-runtime";
import { createContext, useContext, useEffect, useState } from "react";
import { RecursionField, useField, useFieldSchema } from "@tachybase/schema";
import { Select } from "antd";
import { differenceBy, unionBy } from "lodash";
import { TableSelectorParamsProvider, useTableSelectorProps } from "../../../block-provider/TableSelectorProvider.mjs";
import { CollectionProvider_deprecated, useCollection_deprecated } from "../../../collection-manager/index.mjs";
import { FormProvider, SchemaComponentOptions } from "../../core/index.mjs";
import { useCompile } from "../../hooks/index.mjs";
import { ActionContextProvider, OpenMode, useActionContext } from "../action/index.mjs";
import { FileSelector } from "../preview/index.mjs";
import { useFieldNames } from "./useFieldNames.mjs";
import { getLabelFormatValue, useLabelUiSchema } from "./util.mjs";
const RecordPickerContext = /*#__PURE__*/ createContext(null);
RecordPickerContext.displayName = 'RecordPickerContext';
function flatData(data) {
    const newArr = [];
    for(let i = 0; i < data.length; i++){
        const children = data[i]['children'];
        if (Array.isArray(children)) newArr.push(...flatData(children));
        newArr.push({
            ...data[i]
        });
    }
    return newArr;
}
const InputRecordPicker_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 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);
        }
    };
};
const useAssociation = (props)=>{
    const fieldSchema = useFieldSchema();
    const { association } = props;
    const { getField } = useCollection_deprecated();
    if (association) return association;
    return getField(fieldSchema.name);
};
const InputRecordPicker = (props)=>{
    const { value, multiple, onChange, quickUpload, selectFile, ...others } = props;
    const fieldNames = useFieldNames(props);
    const [visible, setVisible] = useState(false);
    const fieldSchema = useFieldSchema();
    const collectionField = useAssociation(props);
    const compile = useCompile();
    const labelUiSchema = useLabelUiSchema(collectionField, (null == fieldNames ? void 0 : fieldNames.label) || 'label');
    const showFilePicker = isShowFilePicker(labelUiSchema);
    const [selectedRows, setSelectedRows] = useState([]);
    const [options, setOptions] = useState([]);
    useEffect(()=>{
        if (value) {
            const opts = (Array.isArray(value) ? value : value ? [
                value
            ] : []).map((option)=>{
                const label = option[fieldNames.label];
                return {
                    ...option,
                    [fieldNames.label]: getLabelFormatValue(labelUiSchema, compile(label))
                };
            });
            setOptions(opts);
        }
    }, [
        value,
        null == fieldNames ? void 0 : fieldNames.label
    ]);
    const getValue = ()=>{
        if (null == multiple) return null;
        return Array.isArray(value) ? null == value ? void 0 : value.map((v)=>v[fieldNames.value]) : null == value ? void 0 : value[fieldNames.value];
    };
    const handleSelect = ()=>{
        setVisible(true);
        setSelectedRows([]);
    };
    const handleRemove = (file)=>{
        const newOptions = options.filter((option)=>option.id !== file.id);
        setOptions(newOptions);
        if (0 === newOptions.length) return onChange(null);
        onChange(newOptions);
    };
    return /*#__PURE__*/ jsxs("div", {
        children: [
            showFilePicker ? /*#__PURE__*/ jsx(FileSelector, {
                value: options,
                multiple: multiple,
                quickUpload: quickUpload,
                selectFile: selectFile,
                action: "".concat(null == collectionField ? void 0 : collectionField.target, ":create"),
                onSelect: handleSelect,
                onRemove: handleRemove,
                onChange: (changed)=>{
                    if (changed.every((file)=>'uploading' !== file.status)) {
                        changed = changed.filter((file)=>'done' === file.status).map((file)=>file.response.data);
                        multiple ? onChange([
                            ...options,
                            ...changed
                        ]) : onChange(changed[0]);
                    }
                }
            }) : /*#__PURE__*/ jsx(Select, {
                ...others,
                mode: multiple ? 'multiple' : props.mode,
                fieldNames: fieldNames,
                popupMatchSelectWidth: false,
                onDropdownVisibleChange: (open)=>{
                    setVisible(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);
                        setOptions([]);
                    }
                },
                options: options,
                value: getValue(),
                open: false
            }),
            Drawer({
                multiple,
                onChange,
                selectedRows,
                setSelectedRows,
                collectionField,
                visible,
                setVisible,
                fieldSchema,
                options
            })
        ]
    });
};
const RecordPickerProvider = (props)=>{
    const { multiple, onChange, selectedRows, setSelectedRows, options, collectionField, ...other } = props;
    return /*#__PURE__*/ jsx(RecordPickerContext.Provider, {
        value: {
            multiple,
            onChange,
            selectedRows,
            setSelectedRows,
            options,
            collectionField,
            ...other
        },
        children: props.children
    });
};
const Drawer = (param)=>{
    let { multiple, onChange, selectedRows, setSelectedRows, collectionField, visible, setVisible, fieldSchema, options } = param;
    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 recordPickerProps = {
        multiple,
        onChange,
        selectedRows,
        setSelectedRows,
        options,
        collectionField
    };
    return /*#__PURE__*/ jsx(RecordPickerProvider, {
        ...recordPickerProps,
        children: /*#__PURE__*/ jsx(CollectionProvider_deprecated, {
            allowNull: true,
            name: null == collectionField ? void 0 : collectionField.target,
            children: /*#__PURE__*/ jsx(ActionContextProvider, {
                openMode: OpenMode.DEFAULT,
                visible: visible,
                setVisible: setVisible,
                children: /*#__PURE__*/ jsx(FormProvider, {
                    children: /*#__PURE__*/ jsx(TableSelectorParamsProvider, {
                        params: {
                            filter: getFilter()
                        },
                        children: /*#__PURE__*/ jsx(SchemaComponentOptions, {
                            scope: {
                                useTableSelectorProps: InputRecordPicker_useTableSelectorProps,
                                usePickActionProps
                            },
                            children: /*#__PURE__*/ jsx(RecursionField, {
                                schema: fieldSchema,
                                onlyRenderProperties: true,
                                filterProperties: (s)=>'RecordPicker.Selector' === s['x-component']
                            })
                        })
                    })
                })
            })
        })
    });
};
function isShowFilePicker(labelUiSchema) {
    return (null == labelUiSchema ? void 0 : labelUiSchema['x-component']) === 'Preview';
}
export { InputRecordPicker, RecordPickerContext, RecordPickerProvider, isShowFilePicker };
