import { jsx, jsxs } from "react/jsx-runtime";
import { useLingui } from "@lingui/react";
import { CircularProgress, styled } from "@mui/material";
import apollo_core from "@uipath/apollo-core";
import react from "react";
import { ApTypography } from "../../../index.js";
import { useChatState } from "../../providers/chat-state-provider.js";
import { AutopilotChatFileType } from "../../service/index.js";
import { fileToIcon } from "../../utils/file-to-icon.js";
import { AutopilotChatActionButton } from "./action-button.js";
import { AutopilotChatTooltip } from "./tooltip.js";
const AttachmentIcon = styled('span')(({ fileType, width, height })=>({
        width: width ?? apollo_core.Spacing.SpacingM,
        height: height ?? apollo_core.Spacing.SpacingM,
        boxSizing: 'border-box',
        flexShrink: 0,
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: apollo_core.Border.BorderRadiusM,
        lineHeight: 0,
        ...fileType === AutopilotChatFileType.File ? {
            backgroundColor: '#078E9E'
        } : {
            backgroundColor: 'var(--color-background-secondary)'
        },
        '& svg': {
            transform: 'scale(0.8)',
            display: 'block'
        }
    }));
const AttachmentsContainer = styled('div')(({ removeSpacing, disableOverflow })=>({
        display: 'flex',
        flexWrap: 'wrap',
        padding: removeSpacing ? 0 : `0 ${apollo_core.Spacing.SpacingBase}`,
        marginTop: removeSpacing ? 0 : apollo_core.Spacing.SpacingMicro,
        gap: `0 ${apollo_core.Spacing.SpacingXs}`,
        boxSizing: 'border-box',
        ...disableOverflow ? {
            overflow: 'hidden',
            maxWidth: '100%',
            width: '100%'
        } : {
            overflowY: 'auto',
            maxHeight: '190px'
        }
    }));
const StyledAttachment = styled('div')(({ showRemoveIcon, isFullWidth })=>({
        display: 'flex',
        alignItems: 'center',
        gap: apollo_core.Spacing.SpacingXs,
        padding: apollo_core.Spacing.SpacingMicro,
        margin: `${apollo_core.Spacing.SpacingMicro} 0`,
        boxSizing: 'border-box',
        borderRadius: apollo_core.Border.BorderRadiusL,
        border: `${apollo_core.Border.BorderThickS} solid var(--color-border-de-emp)`,
        position: 'relative',
        maxWidth: isFullWidth ? '100%' : `calc(50% - ${apollo_core.Spacing.SpacingXs} / 2)`,
        outlineColor: 'var(--color-focus-indicator)',
        backgroundColor: 'var(--color-background)',
        '& .attachment-name': {
            textOverflow: 'ellipsis',
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            color: 'var(--color-foreground)'
        },
        '& .attachment-remove': {
            opacity: showRemoveIcon ? 1 : 0,
            marginLeft: 'auto',
            position: 'absolute',
            right: apollo_core.Spacing.SpacingMicro,
            backgroundColor: 'var(--color-background)',
            height: apollo_core.Spacing.SpacingM,
            display: 'flex',
            '& .MuiButtonBase-root': {
                height: apollo_core.Spacing.SpacingM,
                width: apollo_core.Spacing.SpacingM,
                padding: 0
            }
        }
    }));
const Attachment = /*#__PURE__*/ react.memo(({ attachment, onRemove, shouldFocus, isFullWidth, loading })=>{
    const { _ } = useLingui();
    const { spacing } = useChatState();
    const removeButtonRef = react.useRef(null);
    const [isRemoveIconVisible, setIsRemoveIconVisible] = react.useState(false);
    const [isFocused, setIsFocused] = react.useState(false);
    const attachmentRef = react.useRef(null);
    const lastMousePosition = react.useRef({
        x: 0,
        y: 0
    });
    react.useEffect(()=>{
        if (shouldFocus && removeButtonRef.current) removeButtonRef.current.focus();
    }, [
        shouldFocus
    ]);
    react.useEffect(()=>{
        if (!onRemove) return;
        const handleMouseMove = (e)=>{
            if (isFocused) return;
            lastMousePosition.current = {
                x: e.clientX,
                y: e.clientY
            };
            if (attachmentRef.current) {
                const rect = attachmentRef.current.getBoundingClientRect();
                const isInside = e.clientX >= rect.left && e.clientX <= rect.right && e.clientY >= rect.top && e.clientY <= rect.bottom;
                setIsRemoveIconVisible(isInside);
            }
        };
        document.addEventListener('mousemove', handleMouseMove);
        return ()=>document.removeEventListener('mousemove', handleMouseMove);
    }, [
        isFocused,
        onRemove
    ]);
    const [IconComponent, friendlyType] = react.useMemo(()=>{
        const { icon: IconComp, friendlyType: fileType } = fileToIcon(attachment.name);
        return [
            IconComp,
            fileType
        ];
    }, [
        attachment
    ]);
    return /*#__PURE__*/ jsxs(StyledAttachment, {
        ref: attachmentRef,
        id: attachment.name,
        showRemoveIcon: (isRemoveIconVisible || isFocused) && !!onRemove,
        isFullWidth: isFullWidth,
        tabIndex: 0,
        onFocus: ()=>setIsFocused(true),
        onBlur: ()=>setIsFocused(false),
        children: [
            /*#__PURE__*/ jsx(AttachmentIcon, {
                fileType: friendlyType,
                children: /*#__PURE__*/ jsx(IconComponent, {})
            }),
            /*#__PURE__*/ jsx(AutopilotChatTooltip, {
                title: attachment.name,
                placement: "top",
                disableInteractive: true,
                children: /*#__PURE__*/ jsx(ApTypography, {
                    variant: spacing.primaryFontToken,
                    className: "attachment-name",
                    children: attachment.name
                })
            }),
            onRemove && !loading && /*#__PURE__*/ jsx("div", {
                className: "attachment-remove",
                children: /*#__PURE__*/ jsx(AutopilotChatActionButton, {
                    ref: removeButtonRef,
                    onFocus: ()=>setIsFocused(true),
                    onBlur: ()=>setIsFocused(false),
                    iconSize: apollo_core.Icon.IconS,
                    iconName: "close",
                    tooltip: _({
                        id: 'autopilot-chat.common.attachments.remove-file'
                    }),
                    ariaLabel: _({
                        id: 'autopilot-chat.common.attachments.remove-file-name',
                        values: {
                            0: attachment.name
                        }
                    }),
                    onClick: ()=>{
                        if (onRemove) onRemove(attachment.name);
                        requestAnimationFrame(()=>{
                            const event = new MouseEvent('mousemove', {
                                clientX: lastMousePosition.current.x,
                                clientY: lastMousePosition.current.y
                            });
                            document.dispatchEvent(event);
                        });
                    },
                    "data-testid": "autopilot-chat-attachment-remove"
                })
            }),
            loading && /*#__PURE__*/ jsx("div", {
                className: "attachment-loading",
                children: /*#__PURE__*/ jsx(CircularProgress, {
                    size: 16,
                    color: "primary"
                })
            })
        ]
    });
});
const Attachments = /*#__PURE__*/ react.memo(({ attachments, attachmentsLoading, onRemove, removeSpacing, disableOverflow })=>{
    const [focusedAttachmentIndex, setFocusedAttachmentIndex] = react.useState(null);
    const prevAttachmentsLength = react.useRef(attachments.length);
    react.useEffect(()=>{
        const currentLength = attachments.length;
        const prevLength = prevAttachmentsLength.current;
        if (currentLength < prevLength && null !== focusedAttachmentIndex) {
            if (focusedAttachmentIndex >= currentLength) 0 === currentLength ? setFocusedAttachmentIndex(null) : setFocusedAttachmentIndex(currentLength - 1);
        }
        prevAttachmentsLength.current = currentLength;
    }, [
        attachments.length,
        focusedAttachmentIndex
    ]);
    const handleRemoveAttachment = react.useCallback((name, index)=>{
        if (onRemove) {
            setFocusedAttachmentIndex(index);
            onRemove(name, index);
        }
    }, [
        onRemove
    ]);
    const hasOddNumberOfAttachments = attachments.length % 2 !== 0;
    return /*#__PURE__*/ jsx(AttachmentsContainer, {
        removeSpacing: removeSpacing,
        disableOverflow: disableOverflow,
        children: attachments.map((attachment, index)=>/*#__PURE__*/ jsx(Attachment, {
                attachment: attachment,
                loading: attachmentsLoading?.find((a)=>a.name === attachment.name && a.size === attachment.size)?.loading,
                onRemove: onRemove ? (name)=>handleRemoveAttachment(name, index) : void 0,
                shouldFocus: index === focusedAttachmentIndex,
                isFullWidth: hasOddNumberOfAttachments && index === attachments.length - 1
            }, attachment.name + attachment.size))
    });
});
export { Attachment, Attachments };
