import { DeleteOutlined } from "@ant-design/icons";
import { useEmotionCss } from "@ant-design/use-emotion-css";
import { Button, Image, Tooltip } from "antd";
import { useState } from "react";
import FileIcon from "../FileIcon";

const FileLink: React.FC<{
    fileExtName: string;
    fileName: string;
    fileSize?: number | string;
    url?: string;
    thumbUrl?: string;
    card?: boolean;
    fileId?: string;
    thumbFileId?: string;
    onDownload?: () => Promise<void>;
    onDelete?: () => Promise<void>;
}> = ({ fileExtName, fileName, fileSize, url, thumbUrl, card, fileId, thumbFileId, onDownload, onDelete }) => {
    const fileUrl = fileId ? `${AppConfig.fileViewRoot}?id=${fileId}` : url;
    const fileThumbUrl = (thumbFileId && thumbFileId !== '0') ? `${AppConfig.fileViewRoot}?id=${thumbFileId}` : thumbUrl;

    const [downloading, setDownloading] = useState(false);

    const className = useEmotionCss(({ token }) => {
        return {
            width: '100%',
            display: 'flex',
            flexDirection: 'row',
            alignItems: 'center',
            paddingInline: token.paddingXXS,
            borderRadius: token.borderRadiusSM,
            '&.card': {
                paddingBlock: token.paddingXXS,
                borderWidth: 1,
                borderColor: token.colorBorder,
                borderStyle: 'solid',
            },
            '& .ant-btn-link': {
                maxWidth: '100%',
                overflow: 'hidden',
            },
            '& .ant-btn-link > span:hover': {
                textDecoration: 'underline',
            },
            '& .size': {
                flex: 1,
                color: token.colorTextSecondary,
                textAlign: 'right',
                whiteSpace: 'nowrap',
                fontSize: token.fontSizeSM,
            },
            '&:hover': {
                backgroundColor: token.colorBgTextHover,
                '& .delete': {
                    opacity: 1,
                },
            },
            '& .delete': {
                opacity: 0.2,
                marginLeft: token.marginXS,
                color: token.colorTextSecondary,
                '&:hover': {
                    color: token.colorErrorActive,
                },
            },
            '& .thumb': {
                // marginLeft: token.marginXXS,
                flexShrink: 0,
                width: 48,
                height: 40,
                borderRadius: token.borderRadiusXS,
                objectFit: 'cover',
            },
        };
    });

    const fsize = parseFloat(`${fileSize ?? 0}`);
    let fsizeTxt = `${(fsize / 1024 / 1024).toFixed(2)} MB`;
    if (fsize < 1024 * 1024) {
        fsizeTxt = `${(fsize / 1024).toFixed(0)} KB`;
    }

    const handleClick = async () => {
        if (onDownload) {
            setDownloading(true);
            try {
                await onDownload();
            }
            catch { }
            finally {
                setDownloading(false);
            }
        } else if (fileUrl) {
            console.log(fileUrl)
            window.open(fileUrl);
        }
    }

    return (
        <div className={`${className} ${card ? 'card' : ''}`}>
            {!fileThumbUrl && <FileIcon type={fileExtName} />}
            {fileThumbUrl &&
                // <img className="thumb" src={fileThumbUrl} onClick={handleClick} />
                <Image
                    className="thumb"
                    src={fileThumbUrl}
                    preview={{
                        src: fileUrl,
                    }}
                // onClick={handleClick}
                />
            }
            <Button type="link" size="small" disabled={downloading} onClick={handleClick} style={{ maxWidth: '100%', overflow: 'hidden' }}>
                <Tooltip title={fileName}>
                    <div style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{fileName}</div>
                </Tooltip>
            </Button>
            <span className="size">{(fileSize && fileSize !== '0') ? fsizeTxt : null}</span>
            {onDelete &&
                <DeleteOutlined className="delete" onClick={async () => {
                    setDownloading(true);
                    try {
                        await onDelete?.();
                    }
                    catch { }
                    finally {
                        setDownloading(false);
                    }
                }} />
            }
        </div>
    );
}

export default FileLink;