import { jsx, jsxs } from "react/jsx-runtime";
import { useLingui } from "@lingui/react";
import { styled } from "@mui/material";
import apollo_core from "@uipath/apollo-core";
import react from "react";
import { ApTypography } from "../../../ap-typography/index.js";
import { useChatService } from "../../providers/chat-service.provider.js";
import { useChatState } from "../../providers/chat-state-provider.js";
import { useLoading } from "../../providers/loading-provider.js";
import { AutopilotChatEvent, AutopilotChatPreHookAction } from "../../service/index.js";
import { AutopilotChatActionButton } from "../common/action-button.js";
const GroupItem = styled('div')(({ isActive, showRemoveIcon })=>({
        width: `calc(100% - 2 * ${apollo_core.Spacing.SpacingBase})`,
        padding: `0 calc(${apollo_core.Padding.PadL} + ${apollo_core.Spacing.SpacingBase})`,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        cursor: 'pointer',
        borderRadius: apollo_core.Border.BorderRadiusS,
        outlineColor: 'var(--color-focus-indicator)',
        outlineWidth: '1px',
        outlineOffset: '-1px',
        '&:hover, &:active': {
            backgroundColor: 'var(--color-background-hover)'
        },
        ...isActive && {
            backgroundColor: 'var(--color-background-selected)',
            borderLeft: "4px solid var(--color-selection-indicator)"
        },
        '& .delete-button-wrapper': {
            opacity: showRemoveIcon ? 1 : 0,
            position: 'relative',
            left: apollo_core.Spacing.SpacingXs,
            marginRight: apollo_core.Spacing.SpacingBase
        }
    }));
const GroupTitle = styled('div')(()=>({
        flex: 1,
        minWidth: 0,
        '& .MuiTypography-root': {
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap'
        }
    }));
const AutopilotChatHistoryItemComponent = ({ item, isHistoryOpen })=>{
    const { _ } = useLingui();
    const chatService = useChatService();
    const { spacing } = useChatState();
    const [isActive, setIsActive] = react.useState(chatService.activeConversationId === item.id);
    const { setWaitingResponse } = useLoading();
    const [isRemoveIconVisible, setIsRemoveIconVisible] = react.useState(false);
    const [isFocused, setIsFocused] = react.useState(false);
    const itemRef = react.useRef(null);
    const lastMousePosition = react.useRef({
        x: 0,
        y: 0
    });
    const focusButtonRef = react.useRef(null);
    react.useEffect(()=>{
        const handleMouseMove = (e)=>{
            if (isFocused) return;
            lastMousePosition.current = {
                x: e.clientX,
                y: e.clientY
            };
            if (itemRef.current) {
                const rect = itemRef.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
    ]);
    react.useEffect(()=>{
        if (!chatService) return;
        if (chatService.activeConversationId === item.id && !isActive) setIsActive(true);
        const unsubscribeOpenConversation = chatService.on(AutopilotChatEvent.OpenConversation, (id)=>{
            if (!isActive && item.id === id) setWaitingResponse(false);
            setIsActive(id === item.id);
        });
        const unsubscribeDeleteConversation = chatService.on(AutopilotChatEvent.DeleteConversation, (id)=>{
            if (isActive && id === item.id) chatService.newChat();
        });
        const unsubscribeNewChat = chatService.on(AutopilotChatEvent.NewChat, ()=>{
            setIsActive(false);
        });
        return ()=>{
            unsubscribeOpenConversation();
            unsubscribeDeleteConversation();
            unsubscribeNewChat();
        };
    }, [
        chatService,
        item.id,
        isActive,
        setWaitingResponse
    ]);
    const handleDelete = react.useCallback((ev, itemId)=>{
        ev.stopPropagation();
        setIsFocused(false);
        if (!chatService) return;
        chatService.getPreHook(AutopilotChatPreHookAction.DeleteConversation)({
            conversationId: itemId
        }).then((proceed)=>{
            if (!proceed) return;
            chatService.deleteConversation(itemId);
        });
    }, [
        chatService
    ]);
    const handleItemClick = react.useCallback((itemId)=>{
        if (isActive) return;
        chatService.openConversation(itemId);
        chatService.toggleHistory(false);
    }, [
        chatService,
        isActive
    ]);
    react.useEffect(()=>{
        if (isFocused) focusButtonRef.current?.focus();
    }, [
        isFocused
    ]);
    return /*#__PURE__*/ jsxs(GroupItem, {
        showRemoveIcon: isFocused || isRemoveIconVisible,
        ref: itemRef,
        tabIndex: isHistoryOpen ? 0 : -1,
        isActive: isActive,
        onClick: ()=>handleItemClick(item.id),
        onKeyDown: (ev)=>{
            if ('Enter' === ev.key || ' ' === ev.key) handleItemClick(item.id);
        },
        "aria-label": item.name,
        role: "button",
        "aria-pressed": isActive,
        children: [
            /*#__PURE__*/ jsx(GroupTitle, {
                children: /*#__PURE__*/ jsx(ApTypography, {
                    variant: spacing.primaryFontToken,
                    color: 'var(--color-foreground)',
                    children: item.name
                })
            }),
            /*#__PURE__*/ jsx("div", {
                className: "delete-button-wrapper",
                children: /*#__PURE__*/ jsx(AutopilotChatActionButton, {
                    disabled: !isHistoryOpen,
                    ref: focusButtonRef,
                    onClick: (ev)=>handleDelete(ev, item.id),
                    onFocus: ()=>{
                        setIsFocused(true);
                    },
                    onBlur: ()=>{
                        setIsFocused(false);
                    },
                    onKeyDown: (ev)=>{
                        if ('Escape' !== ev.key) ev.stopPropagation();
                        if ('Enter' === ev.key || ' ' === ev.key) handleDelete(ev, item.id);
                    },
                    iconName: "delete",
                    iconSize: "16px",
                    tooltip: (isRemoveIconVisible || isFocused) && isHistoryOpen ? _({
                        id: 'autopilot-chat.history.delete'
                    }) : '',
                    "data-testid": "autopilot-chat-history-delete",
                    ariaLabel: _({
                        id: 'autopilot-chat.history.delete'
                    })
                })
            })
        ]
    }, item.id);
};
const AutopilotChatHistoryItem = /*#__PURE__*/ react.memo(AutopilotChatHistoryItemComponent);
export { AutopilotChatHistoryItem };
