import { jsx, jsxs } from "react/jsx-runtime";
import { useContext, useEffect, useState } from "react";
import { RecursionField, connect, useField, useFieldSchema } from "@tachybase/schema";
import { differenceBy, unionBy } from "lodash";
import { FormProvider, RecordPickerContext, RecordPickerProvider, SchemaComponentOptions, useActionContext } from "../../index.mjs";
import { TableSelectorParamsProvider, useTableSelectorProps } from "../../../block-provider/TableSelectorProvider.mjs";
import { CollectionProvider_deprecated, useCollectionManager_deprecated, useCollection_deprecated } from "../../../collection-manager/index.mjs";
import { useCompile } from "../../hooks/index.mjs";
import { ActionContextProvider, OpenMode } from "../action/index.mjs";
import { EllipsisWithTooltip } from "../input/index.mjs";
import { FileSelector, Preview } from "../preview/index.mjs";
import { useFieldNames, useInsertSchema } from "./hooks.mjs";
import schema from "./schema.mjs";
import { flatData, getLabelFormatValue, useLabelUiSchema } from "./util.mjs";
const FileManager_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 InternalFileManager = (props)=>{
    var _fieldSchema_xcomponentprops, _fieldSchema_xcomponentprops1;
    const { value, multiple, onChange, ...others } = props;
    const fieldSchema = useFieldSchema();
    const [visibleSelector, setVisibleSelector] = useState(false);
    const [selectedRows, setSelectedRows] = useState([]);
    const insertSelector = useInsertSchema('Selector');
    const fieldNames = useFieldNames(props);
    const field = useField();
    const [options, setOptions] = useState([]);
    const { getField } = useCollection_deprecated();
    const collectionField = getField(field.props.name);
    const labelUiSchema = useLabelUiSchema(null == collectionField ? void 0 : collectionField.target, (null == fieldNames ? void 0 : fieldNames.label) || 'label');
    const compile = useCompile();
    const { modalProps } = useActionContext();
    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 handleSelect = ()=>{
        insertSelector(schema.Selector);
        setVisibleSelector(true);
        setSelectedRows([]);
    };
    useEffect(()=>{
        if (value && Object.keys(value).length > 0) {
            const opts = (Array.isArray(value) ? value : value ? [
                value
            ] : []).filter(Boolean).map((option)=>{
                const label = option[fieldNames.label];
                return {
                    ...option,
                    [fieldNames.label]: getLabelFormatValue(compile(labelUiSchema), compile(label))
                };
            });
            setOptions(opts);
        } else setOptions([]);
    }, [
        value,
        null == fieldNames ? void 0 : fieldNames.label
    ]);
    const handleRemove = (file)=>{
        const newOptions = options.filter((option)=>option.id !== file.id);
        setOptions(newOptions);
        if (0 === newOptions.length) return onChange(null);
        onChange(newOptions);
    };
    const pickerProps = {
        size: 'small',
        fieldNames,
        multiple: [
            'o2m',
            'm2m'
        ].includes(null == collectionField ? void 0 : collectionField.interface) && multiple,
        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 { 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);
            }
        };
    };
    return /*#__PURE__*/ jsxs("div", {
        style: {
            width: '100%',
            overflow: 'auto'
        },
        children: [
            /*#__PURE__*/ jsx(FileSelector, {
                value: options,
                multiple: multiple,
                quickUpload: (null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.quickUpload) !== false,
                selectFile: (null == (_fieldSchema_xcomponentprops1 = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops1.selectFile) !== false,
                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(ActionContextProvider, {
                value: {
                    openMode: OpenMode.DEFAULT,
                    visible: visibleSelector,
                    setVisible: setVisibleSelector,
                    modalProps: {
                        getContainer: (null == others ? void 0 : others.getContainer) || (null == modalProps ? void 0 : modalProps.getContainer)
                    },
                    formValueChanged: false
                },
                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: FileManager_useTableSelectorProps
                                    },
                                    children: /*#__PURE__*/ jsx(RecursionField, {
                                        onlyRenderProperties: true,
                                        basePath: field.address,
                                        schema: fieldSchema,
                                        filterProperties: (s)=>'AssociationField.Selector' === s['x-component']
                                    })
                                })
                            })
                        })
                    })
                })
            })
        ]
    });
};
const FileManageReadPretty = connect((props)=>{
    const fieldSchema = useFieldSchema();
    const { getField } = useCollection_deprecated();
    const { getCollectionJoinField } = useCollectionManager_deprecated();
    const collectionField = getField(fieldSchema.name) || getCollectionJoinField(fieldSchema['x-collection-field']);
    return /*#__PURE__*/ jsx(EllipsisWithTooltip, {
        ellipsis: true,
        children: collectionField ? /*#__PURE__*/ jsx(Preview, {
            ...props
        }) : null
    });
});
export { FileManageReadPretty, InternalFileManager };
