import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { styled } from "@mui/material";
import apollo_core from "@uipath/apollo-core";
import react, { useMemo } from "react";
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, AutopilotChatInterceptableEvent, AutopilotChatInternalEvent, AutopilotChatRole } from "../../service/index.js";
import { SkeletonLoader } from "../common/skeleton-loader.js";
import { AutopilotChatMessageContent } from "./chat-message-content.js";
import { AutopilotChatFRE } from "./first-run-experience/chat-fre.js";
import { AutopilotChatLoading } from "./loader/chat-loading.js";
import { AutopilotChatLoadingMessages } from "./loader/chat-loading-messages.js";
import { stripResourceTokens } from "./markdown/parsers/resource-token-parser.js";
import { AutopilotChatSuggestions } from "./suggestions/chat-suggestions.js";
const MessageContainer = styled('div')(({ isOverflow, isContainerWide, gap })=>({
        display: 'flex',
        flexDirection: 'column',
        gap: `${gap}px`,
        height: '100%',
        ...isOverflow && isContainerWide && {
            position: 'relative',
            left: apollo_core.Spacing.SpacingXs
        }
    }));
const removeFakeStream = (messages)=>messages.map(({ fakeStream: _fakeStream, ...rest })=>rest);
const MessageGroupContainer = styled('div')(({ isAssistant, disableActions, isLastGroup })=>{
    if (disableActions) return isLastGroup ? {
        marginBottom: '14px'
    } : {
        marginBottom: '-16px'
    };
    if (isAssistant) return {
        marginBottom: '30px'
    };
    return {
        marginBottom: '14px'
    };
});
const MessageGroup = /*#__PURE__*/ react.memo(({ messages, isLastGroup })=>{
    const [groupRef, setGroupRef] = react.useState(null);
    const disableActions = 1 === messages.length && !!messages[0]?.disableActions;
    return /*#__PURE__*/ jsx(MessageGroupContainer, {
        isAssistant: messages[0]?.role === AutopilotChatRole.Assistant,
        disableActions: disableActions,
        isLastGroup: isLastGroup,
        ref: setGroupRef,
        children: messages.map((message, index)=>/*#__PURE__*/ jsx(AutopilotChatMessageContent, {
                message: message,
                disableActions: disableActions,
                isLastInGroup: index === messages.length - 1,
                containerRef: groupRef
            }, message.id))
    });
});
function AutopilotChatMessagesComponent({ isOverflow, isContainerWide }) {
    const chatService = useChatService();
    const [messages, setMessages] = react.useState(removeFakeStream(chatService?.getConversation?.() ?? []));
    const { isLoadingMoreMessages, skeletonLoader } = useLoading();
    const { firstRunExperience, setHasMessages, spacing } = useChatState();
    const [suggestions, setSuggestions] = react.useState([]);
    const [sendOnClick, setSendOnClick] = react.useState(false);
    const updateMessages = react.useCallback((message)=>{
        setMessages((prev)=>{
            if (prev.some((m)=>m.id === message.id)) return prev.map((m)=>m.id === message.id ? message : m);
            return [
                ...prev,
                message
            ];
        });
    }, []);
    const sendFeedback = react.useCallback(({ message, action })=>{
        if (!chatService) return;
        if (message.role === AutopilotChatRole.Assistant) chatService.sendResponse({
            ...message,
            ...message.fakeStream ? {
                fakeStream: false
            } : {},
            ...message.stream ? {
                stream: false,
                done: true
            } : {},
            feedback: {
                isPositive: !!action.details?.isPositive
            }
        });
    }, [
        chatService
    ]);
    const onCopy = react.useCallback(({ group, message })=>{
        let finalString = '';
        finalString = 0 === group.length ? message.toCopy ?? message.content : group.map((msg)=>msg.toCopy ?? msg.content).join('\n');
        finalString = stripResourceTokens(finalString);
        if (navigator.clipboard && finalString) navigator.clipboard.writeText(finalString).catch(()=>{});
    }, []);
    react.useEffect(()=>{
        if (!chatService) return;
        const unsubscribeRequest = chatService.intercept(AutopilotChatInterceptableEvent.Request, updateMessages);
        const unsubscribeResponse = chatService.on(AutopilotChatEvent.Response, updateMessages);
        const unsubscribeNewChat = chatService.on(AutopilotChatEvent.NewChat, ()=>setMessages([]));
        const unsubscribeFeedback = chatService.on(AutopilotChatEvent.Feedback, sendFeedback);
        const unsubscribeCopy = chatService.on(AutopilotChatEvent.Copy, onCopy);
        const unsubscribeConversation = chatService.on(AutopilotChatEvent.SetConversation, (msg)=>{
            setMessages(removeFakeStream(msg));
        });
        const unsubscribeSetSuggestions = chatService.__internalService__.on(AutopilotChatInternalEvent.SetSuggestions, ({ suggestions: suggestionsToSet, sendOnClick: sendOnClickToSet })=>{
            setSuggestions(suggestionsToSet);
            setSendOnClick(sendOnClickToSet);
        });
        return ()=>{
            unsubscribeRequest();
            unsubscribeResponse();
            unsubscribeConversation();
            unsubscribeNewChat();
            unsubscribeFeedback();
            unsubscribeCopy();
            unsubscribeSetSuggestions();
        };
    }, [
        chatService,
        updateMessages,
        sendFeedback,
        onCopy
    ]);
    const messageGroups = useMemo(()=>messages.reduce((acc, message, index)=>{
            if (message.groupId) if (index > 0 && messages[index - 1]?.groupId === message.groupId) acc[acc.length - 1].push(message);
            else acc.push([
                message
            ]);
            else acc.push([
                message
            ]);
            return acc;
        }, []), [
        messages
    ]);
    react.useEffect(()=>{
        setHasMessages(messages.length > 0);
    }, [
        messages,
        setHasMessages
    ]);
    return /*#__PURE__*/ jsx(MessageContainer, {
        gap: spacing.messageSpacing,
        isOverflow: isOverflow,
        isContainerWide: isContainerWide,
        children: skeletonLoader ? /*#__PURE__*/ jsx(SkeletonLoader, {}) : /*#__PURE__*/ jsxs(Fragment, {
            children: [
                isLoadingMoreMessages && /*#__PURE__*/ jsx(AutopilotChatLoadingMessages, {}),
                0 === messages.length && /*#__PURE__*/ jsx(AutopilotChatFRE, {}),
                messageGroups.map((group, idx)=>/*#__PURE__*/ jsx(MessageGroup, {
                        messages: group,
                        isLastGroup: idx === messageGroups.length - 1
                    }, group[0]?.id)),
                messages.length > 0 && suggestions.length > 0 && /*#__PURE__*/ jsx(AutopilotChatSuggestions, {
                    suggestions: suggestions,
                    sendOnClick: sendOnClick ?? firstRunExperience?.sendOnClick ?? false,
                    includeTitle: true
                }),
                /*#__PURE__*/ jsx(AutopilotChatLoading, {})
            ]
        })
    });
}
const AutopilotChatMessages = /*#__PURE__*/ react.memo(AutopilotChatMessagesComponent);
export { AutopilotChatMessages };
