import { jsx, jsxs } from "react/jsx-runtime";
import { createElement, useEffect, useRef, useState } from "react";
import { connect, mapProps, mapReadPretty } from "@tachybase/schema";
import { DeleteOutlined, DownloadOutlined, InboxOutlined, LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { Lightbox } from "@tego/client";
import { Button, Progress, Space, Upload } from "antd";
import classnames from "classnames";
import { saveAs } from "file-saver";
import { useTranslation } from "react-i18next";
import { useApp } from "../../../application/index.mjs";
import { withDynamicSchemaProps } from "../../../application/hoc/withDynamicSchemaProps.mjs";
import { useProps } from "../../hooks/useProps.mjs";
import { ReadPretty } from "./ReadPretty.mjs";
import { toArr, toFileList, toItem, toValue, useUploadProps } from "./shared.mjs";
import { useStyles } from "./style.mjs";
const Upload_Upload = connect((props)=>/*#__PURE__*/ jsx(Upload, {
        ...useUploadProps(props)
    }), mapProps({
    value: 'fileList'
}), mapReadPretty(ReadPretty.Upload));
Upload_Upload.Attachment = connect((props)=>{
    var _images_fileIndex, _images_, _images_1, _images_fileIndex1;
    const { disabled, multiple, value, onChange } = props;
    const [fileList, setFileList] = useState([]);
    const [sync, setSync] = useState(true);
    const app = useApp();
    const previewList = app.AttachmentPreviewManager.get();
    const images = fileList;
    const [fileIndex, setFileIndex] = useState(0);
    const [visible, setVisible] = useState(false);
    const { t } = useTranslation();
    const uploadProps = useUploadProps({
        ...props
    });
    const { wrapSSR, hashId, componentCls: prefixCls } = useStyles();
    const internalFileList = useRef([]);
    useEffect(()=>{
        if (sync) {
            const fileList = toFileList(value);
            setFileList(fileList);
            internalFileList.current = fileList;
        }
    }, [
        value,
        sync
    ]);
    return wrapSSR(/*#__PURE__*/ jsxs("div", {
        children: [
            /*#__PURE__*/ jsx("div", {
                className: classnames("".concat(prefixCls, "-wrapper"), "".concat(prefixCls, "-picture-card-wrapper"), 'tb-upload', hashId),
                children: /*#__PURE__*/ jsxs("div", {
                    className: classnames("".concat(prefixCls, "-list"), "".concat(prefixCls, "-list-picture-card")),
                    children: [
                        fileList.map((file, index)=>{
                            const fileProps = {
                                file,
                                prefixCls,
                                fileList,
                                setFileIndex,
                                setVisible,
                                disabled,
                                t,
                                setSync,
                                setFileList,
                                multiple,
                                onChange,
                                internalFileList,
                                preview: previewList[null == file ? void 0 : file.mimetype] || previewList['default']
                            };
                            return /*#__PURE__*/ createElement(UploadReadFile, {
                                ...fileProps,
                                key: index
                            });
                        }),
                        !disabled && (multiple || toArr(value).length < 1) && /*#__PURE__*/ jsx("div", {
                            className: classnames("".concat(prefixCls, "-list-picture-card-container"), "".concat(prefixCls, "-list-item-container")),
                            children: /*#__PURE__*/ jsx(Upload, {
                                ...uploadProps,
                                disabled: disabled,
                                multiple: multiple,
                                listType: 'picture-card',
                                fileList: fileList,
                                onChange: (info)=>{
                                    const list = updateFileList(info.file, internalFileList.current);
                                    internalFileList.current = list;
                                    setSync(false);
                                    if (multiple) {
                                        if ('done' === info.file.status) null == onChange || onChange(toValue(list));
                                        null == onChange || onChange(toValue(list));
                                        setFileList(list.map(toItem));
                                        setSync(true);
                                    } else {
                                        if ('done' === info.file.status) {
                                            var _info_file_response, _info_file;
                                            null == onChange || onChange(null);
                                            null == onChange || onChange(null == (_info_file = info.file) ? void 0 : null == (_info_file_response = _info_file.response) ? void 0 : _info_file_response.data);
                                        }
                                        setFileList([
                                            toItem(info.file)
                                        ]);
                                        setSync(true);
                                    }
                                },
                                showUploadList: false,
                                children: !disabled && (multiple || toArr(value).length < 1) && /*#__PURE__*/ jsxs("span", {
                                    children: [
                                        /*#__PURE__*/ jsx(PlusOutlined, {}),
                                        /*#__PURE__*/ jsx("br", {}),
                                        " ",
                                        t('Upload')
                                    ]
                                })
                            })
                        })
                    ]
                })
            }),
            visible && /*#__PURE__*/ jsx(Lightbox, {
                mainSrc: null == (_images_fileIndex = images[fileIndex]) ? void 0 : _images_fileIndex.imageUrl,
                nextSrc: null == (_images_ = images[(fileIndex + 1) % images.length]) ? void 0 : _images_.imageUrl,
                prevSrc: null == (_images_1 = images[(fileIndex + images.length - 1) % images.length]) ? void 0 : _images_1.imageUrl,
                mainFile: images[fileIndex],
                nextFile: images[(fileIndex + 1) % images.length],
                prevFile: images[(fileIndex + images.length - 1) % images.length],
                previewList: previewList,
                onCloseRequest: ()=>setVisible(false),
                onMovePrevRequest: ()=>setFileIndex((fileIndex + images.length - 1) % images.length),
                onMoveNextRequest: ()=>setFileIndex((fileIndex + 1) % images.length),
                imageTitle: null == (_images_fileIndex1 = images[fileIndex]) ? void 0 : _images_fileIndex1.title,
                toolbarButtons: [
                    /*#__PURE__*/ jsx("button", {
                        style: {
                            fontSize: 22,
                            background: 'none',
                            lineHeight: 1
                        },
                        type: "button",
                        "aria-label": "Zoom in",
                        title: "Zoom in",
                        className: "ril-zoom-in ril__toolbarItemChild ril__builtinButton",
                        onClick: (e)=>{
                            e.preventDefault();
                            const file = images[fileIndex];
                            saveAs(file.url, "".concat(file.title).concat(file.extname));
                        },
                        children: /*#__PURE__*/ jsx(DownloadOutlined, {})
                    }, 'preview-img')
                ]
            })
        ]
    }));
}, mapReadPretty(ReadPretty.File));
Upload_Upload.Dragger = connect((props)=>{
    const { tipContent } = props;
    const { wrapSSR, hashId, componentCls: prefixCls } = useStyles();
    return wrapSSR(/*#__PURE__*/ jsx("div", {
        className: classnames("".concat(prefixCls, "-dragger"), hashId),
        children: /*#__PURE__*/ jsxs(Upload.Dragger, {
            ...useUploadProps(props),
            children: [
                tipContent,
                props.children
            ]
        })
    }));
}, mapProps({
    value: 'fileList'
}));
Upload_Upload.DraggerV2 = withDynamicSchemaProps(connect((props)=>{
    const { t } = useTranslation();
    const defaultTitle = t('Click or drag file to this area to upload');
    const defaultSubTitle = t('Support for a single or bulk upload, file size should not exceed') + " 10MB";
    const { title = defaultTitle, subTitle = defaultSubTitle, ...extraProps } = useProps(props);
    const [loading, setLoading] = useState(false);
    const { wrapSSR, hashId, componentCls: prefixCls } = useStyles();
    const handleChange = function() {
        let fileList = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : [];
        const { onChange } = extraProps;
        null == onChange || onChange(fileList);
        fileList.some((file)=>'uploading' === file.status) ? setLoading(true) : setLoading(false);
    };
    return wrapSSR(/*#__PURE__*/ jsx("div", {
        className: classnames("".concat(prefixCls, "-dragger"), hashId),
        children: /*#__PURE__*/ jsxs(Upload.Dragger, {
            ...useUploadProps({
                ...props,
                ...extraProps,
                onChange: handleChange
            }),
            children: [
                /*#__PURE__*/ jsx("p", {
                    className: "".concat(prefixCls, "-drag-icon"),
                    children: loading ? /*#__PURE__*/ jsx(LoadingOutlined, {
                        style: {
                            fontSize: 36
                        },
                        spin: true
                    }) : /*#__PURE__*/ jsx(InboxOutlined, {})
                }),
                /*#__PURE__*/ jsx("p", {
                    className: "".concat(prefixCls, "-text"),
                    children: title
                }),
                /*#__PURE__*/ jsx("p", {
                    className: "".concat(prefixCls, "-hint"),
                    children: subTitle
                })
            ]
        })
    }));
}, mapProps({
    value: 'fileList'
})), {
    displayName: 'Upload.DraggerV2'
});
const upload_Upload = Upload_Upload;
function updateFileList(file, fileList) {
    const nextFileList = [
        ...fileList
    ];
    const fileIndex = nextFileList.findIndex((param)=>{
        let { uid } = param;
        return uid === file.uid;
    });
    if (-1 === fileIndex) nextFileList.push(file);
    else nextFileList[fileIndex] = file;
    return nextFileList;
}
const UploadReadFile = (props)=>{
    const { file, prefixCls, fileList, setFileIndex, setVisible, disabled, t, setSync, setFileList, multiple, onChange, internalFileList, preview } = props;
    const handleClick = (e)=>{
        e.preventDefault();
        e.stopPropagation();
        const index = fileList.indexOf(file);
        setVisible(true);
        setFileIndex(index);
    };
    const { viewComponet } = preview;
    return /*#__PURE__*/ jsx("div", {
        className: "".concat(prefixCls, "-list-picture-card-container ").concat(prefixCls, "-list-item-container"),
        children: /*#__PURE__*/ jsxs("div", {
            className: classnames("".concat(prefixCls, "-list-item"), "".concat(prefixCls, "-list-item-done"), "".concat(prefixCls, "-list-item-list-type-picture-card")),
            children: [
                /*#__PURE__*/ jsx("div", {
                    className: "".concat(prefixCls, "-list-item-info"),
                    children: /*#__PURE__*/ jsxs("span", {
                        className: "".concat(prefixCls, "-span"),
                        children: [
                            /*#__PURE__*/ jsx("a", {
                                className: "".concat(prefixCls, "-list-item-thumbnail"),
                                href: file.url,
                                target: "_blank",
                                rel: "noopener noreferrer",
                                onClick: handleClick,
                                style: {
                                    lineHeight: '100%'
                                },
                                children: viewComponet({
                                    prefixCls,
                                    file,
                                    setFileIndex,
                                    setVisible
                                })
                            }),
                            /*#__PURE__*/ jsx("a", {
                                target: "_blank",
                                rel: "noopener noreferrer",
                                className: "".concat(prefixCls, "-list-item-name"),
                                title: file.title,
                                href: file.url,
                                onClick: handleClick,
                                children: 'uploading' === file.status ? t('Uploading') : file.title
                            })
                        ]
                    })
                }),
                /*#__PURE__*/ jsx("span", {
                    className: "".concat(prefixCls, "-list-item-actions"),
                    children: /*#__PURE__*/ jsxs(Space, {
                        size: 3,
                        children: [
                            /*#__PURE__*/ jsx(Button, {
                                size: 'small',
                                type: 'text',
                                icon: /*#__PURE__*/ jsx(DownloadOutlined, {}),
                                onClick: ()=>{
                                    saveAs(file.url, "".concat(file.title).concat(file.extname));
                                }
                            }),
                            !disabled && /*#__PURE__*/ jsx(Button, {
                                size: 'small',
                                type: 'text',
                                icon: /*#__PURE__*/ jsx(DeleteOutlined, {}),
                                onClick: ()=>{
                                    setSync(false);
                                    setFileList((prevFileList)=>{
                                        if (!multiple) {
                                            null == onChange || onChange(null);
                                            setSync(true);
                                            return [];
                                        }
                                        const index = prevFileList.indexOf(file);
                                        prevFileList.splice(index, 1);
                                        internalFileList.current = internalFileList.current.filter((item)=>item.uid !== file.uid);
                                        null == onChange || onChange(toValue([
                                            ...prevFileList
                                        ]));
                                        return [
                                            ...prevFileList
                                        ];
                                    });
                                }
                            })
                        ]
                    })
                }),
                'uploading' === file.status && /*#__PURE__*/ jsx("div", {
                    className: "".concat(prefixCls, "-list-item-progress"),
                    children: /*#__PURE__*/ jsx(Progress, {
                        strokeWidth: 2,
                        type: 'line',
                        showInfo: false,
                        percent: file.percent
                    })
                })
            ]
        })
    }, file.uid || file.id);
};
export { Upload_Upload as Upload, UploadReadFile, upload_Upload as default };
