import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { styled } from "@mui/material";
import apollo_core from "@uipath/apollo-core";
import react from "react";
import { ApToolCall } from "../../../ap-tool-call/index.js";
import { useChatService } from "../../providers/chat-service.provider.js";
import { useChatState } from "../../providers/chat-state-provider.js";
import { useLocale } from "../../providers/locale-provider.js";
import { AGENTS_TOOL_CALL_RENDERER, APOLLO_CHAT_TREE_RENDERER, AutopilotChatEvent, AutopilotChatInternalEvent, AutopilotChatMode, AutopilotChatRole, CHAT_MESSAGE_MAX_PADDING, CHAT_WIDTH_KEY, CHAT_WIDTH_SIDE_BY_SIDE_MIN, DEFAULT_MESSAGE_RENDERER, StorageService } from "../../service/index.js";
import { calculateDynamicPadding } from "../../utils/dynamic-padding.js";
import { Attachments } from "../common/attachments.js";
import { AutopilotChatMessageActions } from "./actions/chat-actions.js";
import { AutopilotChatMarkdownRenderer } from "./markdown/markdown.js";
import { AutopilotChatSources } from "./sources/chat-sources.js";
import { ApolloChatTreeRenderer } from "./tree/tree-renderer.js";
const getApolloMessageRenderers = (locale)=>[
        {
            name: DEFAULT_MESSAGE_RENDERER,
            component: AutopilotChatMarkdownRenderer
        },
        {
            name: AGENTS_TOOL_CALL_RENDERER,
            component: ({ message })=>{
                if (!message.meta.span && !message.meta.input && !message.meta.toolName) return null;
                return /*#__PURE__*/ jsx(ApToolCall, {
                    span: message.meta.span,
                    toolName: message.meta.toolName,
                    input: message.meta.input,
                    output: message.meta.output,
                    isError: message.meta.isError,
                    startTime: message.meta.startTime,
                    endTime: message.meta.endTime,
                    displayMode: message.meta.displayMode,
                    locale: locale
                });
            }
        },
        {
            name: APOLLO_CHAT_TREE_RENDERER,
            component: ({ message })=>{
                if (!message.meta?.span) return null;
                return /*#__PURE__*/ jsx(ApolloChatTreeRenderer, {
                    span: message.meta.span
                });
            }
        }
    ];
const MessageBoxComponent = styled('div')(({ isAssistant, isCustomWidget })=>{
    const chatService = useChatService();
    const { spacing } = useChatState();
    const chatInternalService = chatService.__internalService__;
    const [padding, setPadding] = react.useState(calculateDynamicPadding(parseInt(StorageService.Instance.get(CHAT_WIDTH_KEY) ?? CHAT_WIDTH_SIDE_BY_SIDE_MIN.toString(), 10)));
    react.useEffect(()=>{
        if (!chatInternalService || !chatService) return;
        const unsubscribeResize = chatInternalService.on(AutopilotChatInternalEvent.ChatResize, (width)=>{
            setPadding(calculateDynamicPadding(width));
        });
        const unsubscribeMode = chatService.on(AutopilotChatEvent.ModeChange, (mode)=>{
            if (mode === AutopilotChatMode.FullScreen) setPadding(CHAT_MESSAGE_MAX_PADDING);
            else {
                const defaultWidth = CHAT_WIDTH_SIDE_BY_SIDE_MIN.toString();
                const storedWidth = StorageService.Instance.get(CHAT_WIDTH_KEY) ?? defaultWidth;
                const width = parseInt(storedWidth, 10);
                setPadding(calculateDynamicPadding(width));
            }
        });
        return ()=>{
            unsubscribeResize();
            unsubscribeMode();
        };
    }, [
        chatInternalService,
        chatService
    ]);
    return {
        display: 'flex',
        padding: isAssistant ? 0 : apollo_core.Spacing.SpacingBase,
        paddingRight: isAssistant ? apollo_core.Spacing.SpacingXs : `calc(${apollo_core.Spacing.SpacingBase} + ${apollo_core.Spacing.SpacingXl})`,
        flexDirection: 'column',
        justifyContent: 'center',
        alignSelf: isAssistant ? 'flex-start' : 'flex-end',
        gap: spacing.messageGroupGap,
        borderRadius: apollo_core.Border.BorderRadiusL,
        backgroundColor: isAssistant ? 'unset' : "var(--custom-autopilot-chat-user-message-bg-color, var(--color-background-secondary))",
        marginLeft: isAssistant ? '0' : `${padding}px`,
        marginRight: isAssistant ? apollo_core.Spacing.SpacingXl : '0',
        whiteSpace: 'normal',
        overflowWrap: 'anywhere',
        position: 'relative',
        ...isCustomWidget && {
            width: '100%'
        }
    };
});
const MessageBox = /*#__PURE__*/ react.memo(MessageBoxComponent);
const WidgetContainer = /*#__PURE__*/ react.memo(({ message, isLastInGroup, containerRef })=>{
    const chatService = useChatService();
    const unsubscribeRef = react.useRef(()=>{});
    react.useEffect(()=>()=>{
            unsubscribeRef?.current?.();
        }, []);
    return /*#__PURE__*/ jsxs(MessageBox, {
        isAssistant: message.role === AutopilotChatRole.Assistant,
        isCustomWidget: true,
        children: [
            message.attachments && message.attachments.length > 0 && /*#__PURE__*/ jsx(Attachments, {
                attachments: message.attachments,
                removeSpacing: true,
                disableOverflow: true
            }),
            /*#__PURE__*/ jsx("div", {
                className: "chat-widget-container",
                ref: (el)=>{
                    if (el) {
                        const unsubscribe = chatService.renderMessage(el, message);
                        if (unsubscribe) unsubscribeRef.current = unsubscribe;
                    }
                }
            }),
            isLastInGroup && /*#__PURE__*/ jsxs(Fragment, {
                children: [
                    message.role === AutopilotChatRole.Assistant && /*#__PURE__*/ jsx(AutopilotChatSources, {
                        groupId: message.groupId ?? '',
                        message: message
                    }),
                    /*#__PURE__*/ jsx(AutopilotChatMessageActions, {
                        message: message,
                        containerElement: containerRef
                    })
                ]
            })
        ]
    });
});
function AutopilotChatMessageContentComponent({ message, isLastInGroup = true, disableActions = false, containerRef }) {
    const chatService = useChatService();
    const { locale } = useLocale();
    if (!message.content && !message.contentParts && !message.attachments) return null;
    if (!chatService.getMessageRenderer(message.widget)) {
        const APOLLO_MESSAGE_RENDERERS = getApolloMessageRenderers(locale);
        const ApolloMessageRenderer = APOLLO_MESSAGE_RENDERERS.find((renderer)=>renderer.name === message.widget)?.component;
        return /*#__PURE__*/ jsxs(MessageBox, {
            isAssistant: message.role === AutopilotChatRole.Assistant,
            id: message.id,
            children: [
                message.attachments && message.attachments.length > 0 && /*#__PURE__*/ jsx(Attachments, {
                    attachments: message.attachments,
                    removeSpacing: true,
                    disableOverflow: true
                }),
                ApolloMessageRenderer ? /*#__PURE__*/ jsx(ApolloMessageRenderer, {
                    message: message
                }) : /*#__PURE__*/ jsx(AutopilotChatMarkdownRenderer, {
                    message: message
                }),
                isLastInGroup && /*#__PURE__*/ jsxs(Fragment, {
                    children: [
                        message.role === AutopilotChatRole.Assistant && /*#__PURE__*/ jsx(AutopilotChatSources, {
                            groupId: message.groupId ?? '',
                            message: message
                        }),
                        !disableActions && /*#__PURE__*/ jsx(AutopilotChatMessageActions, {
                            message: message,
                            containerElement: containerRef
                        })
                    ]
                })
            ]
        }, message.id);
    }
    return /*#__PURE__*/ jsx(WidgetContainer, {
        message: message,
        isLastInGroup: isLastInGroup,
        containerRef: containerRef
    }, message.id);
}
const AutopilotChatMessageContent = /*#__PURE__*/ react.memo(AutopilotChatMessageContentComponent);
export { AutopilotChatMessageContent };
