import { jsx, jsxs } from "react/jsx-runtime";
import { useLingui } from "@lingui/react";
import { Box, Collapse, styled } from "@mui/material";
import apollo_core from "@uipath/apollo-core";
import { ApIcon } from "../../../../index.js";
import react, { useCallback, useEffect, useState } from "react";
import { ApTypography } from "../../../../ap-typography/index.js";
import { useIsStreamingMessage } from "../../../hooks/use-is-streaming-message.js";
import { useChatService } from "../../../providers/chat-service.provider.js";
import { useChatState } from "../../../providers/chat-state-provider.js";
import { AutopilotChatEvent, AutopilotChatPreHookAction } from "../../../service/index.js";
import { AutopilotChatTooltip } from "../../common/tooltip.js";
const getSources = (group)=>{
    const allCitations = group.flatMap((message)=>message.contentParts?.flatMap((part)=>part.citations) ?? []).filter((citation)=>void 0 !== citation);
    const seenIds = new Set();
    return allCitations.filter((citation)=>{
        if (seenIds.has(citation.id)) return false;
        seenIds.add(citation.id);
        return true;
    });
};
const COLLAPSED_ITEMS_COUNT = 2;
const StyledContainer = styled(Box)(()=>({
        marginTop: apollo_core.Spacing.SpacingXs,
        animation: 'fadeInUp 0.3s ease-out',
        '@keyframes fadeInUp': {
            '0%': {
                opacity: 0,
                transform: `translateY(${apollo_core.Spacing.SpacingM})`
            },
            '100%': {
                opacity: 1,
                transform: 'translateY(0)'
            }
        }
    }));
const StyledToggleButton = styled(Box)(()=>({
        display: 'inline-flex',
        alignItems: 'center',
        gap: apollo_core.Spacing.SpacingXs,
        cursor: 'pointer',
        padding: `${apollo_core.Spacing.SpacingXs} ${apollo_core.Spacing.SpacingBase} ${apollo_core.Spacing.SpacingXs} ${apollo_core.Spacing.SpacingXs}`,
        borderRadius: apollo_core.Border.BorderRadiusL,
        border: "1px solid var(--color-border-de-emp)",
        backgroundColor: 'var(--color-background)',
        '&:hover': {
            backgroundColor: 'var(--color-background-secondary)'
        },
        '&:active, &:focus': {
            outlineColor: 'var(--color-focus-indicator)'
        }
    }));
const StyledContentContainer = styled(Box)(()=>({
        borderRadius: apollo_core.Border.BorderRadiusL,
        marginTop: apollo_core.Spacing.SpacingXs,
        border: "1px solid var(--color-border-de-emp)",
        backgroundColor: 'var(--color-background)',
        position: 'relative',
        padding: `${apollo_core.Spacing.SpacingXs} 0`
    }));
const StyledSourcesListWrapper = styled('div')(({ isCollapsed })=>({
        position: 'relative',
        ...isCollapsed && {
            maxHeight: `calc((${apollo_core.Spacing.SpacingM} + ${apollo_core.Spacing.SpacingS}) * (${COLLAPSED_ITEMS_COUNT} + 0.6))`,
            overflow: 'hidden'
        }
    }));
const StyledSourcesList = styled(Box)(()=>({
        display: 'flex',
        flexDirection: 'column',
        gap: apollo_core.Spacing.SpacingS
    }));
const StyledSourceItem = styled(Box)(()=>({
        display: 'flex',
        alignItems: 'flex-start',
        gap: apollo_core.Spacing.SpacingXs,
        padding: `0 ${apollo_core.Spacing.SpacingBase}`,
        cursor: 'pointer',
        transition: 'background-color 0.2s',
        height: apollo_core.Spacing.SpacingM,
        '&:hover': {
            backgroundColor: 'var(--color-background-hover)'
        },
        '&:focus, &:active': {
            outlineColor: 'var(--color-focus-indicator)'
        }
    }));
const StyledSourceContent = styled(Box)(()=>({
        flex: 1,
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        '& .MuiTypography-root': {
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis'
        }
    }));
const StyledGradientOverlay = styled(Box)(()=>({
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        height: apollo_core.Spacing.SpacingM,
        background: "linear-gradient(to bottom, transparent 0%, var(--color-background) 70%)",
        pointerEvents: 'none'
    }));
const StyledActionContainer = styled(Box)(()=>({
        display: 'flex',
        position: 'relative',
        marginTop: apollo_core.Spacing.SpacingXs
    }));
const StyledActionButton = styled(Box)(()=>({
        display: 'inline-flex',
        alignItems: 'center',
        gap: apollo_core.Spacing.SpacingXs,
        cursor: 'pointer',
        padding: `${apollo_core.Spacing.SpacingXs} ${apollo_core.Spacing.SpacingBase}`,
        borderRadius: apollo_core.Border.BorderRadiusM,
        backgroundColor: 'transparent',
        transition: 'all 0.2s',
        border: 'none',
        '&:hover': {
            backgroundColor: 'var(--color-background-hover)'
        },
        '&:focus, &:active': {
            outlineColor: 'var(--color-focus-indicator)'
        }
    }));
function AutopilotChatSourcesComponent({ groupId, message }) {
    const { _ } = useLingui();
    const chatService = useChatService();
    const { spacing } = useChatState();
    const [sources, setSources] = useState(getSources(chatService?.getMessagesInGroup(groupId) ?? []));
    const { isStreaming } = useIsStreamingMessage(message);
    const [isWaitingForMoreMessages, setIsWaitingForMoreMessages] = useState(false);
    const [isExpanded, setIsExpanded] = useState(false);
    const [showFullList, setShowFullList] = useState(false);
    useEffect(()=>{
        if (!chatService) return;
        const unsubscribeResponse = chatService.on(AutopilotChatEvent.Response, (response)=>{
            if (response.groupId === groupId || response.id === message.id) {
                setSources(getSources(chatService.getMessagesInGroup(groupId)));
                setIsWaitingForMoreMessages(!!response.shouldWaitForMoreMessages);
            }
        });
        const unsubscribeChunk = chatService.on(AutopilotChatEvent.SendChunk, (chunk)=>{
            if (chunk.groupId === groupId || chunk.id === message.id) setSources(getSources(chatService.getMessagesInGroup(groupId)));
        });
        const unsubscribeStopResponse = chatService.on(AutopilotChatEvent.StopResponse, ()=>{
            setSources(getSources(chatService.getMessagesInGroup(groupId)));
        });
        return ()=>{
            unsubscribeResponse();
            unsubscribeChunk();
            unsubscribeStopResponse();
        };
    }, [
        chatService,
        message.id,
        groupId
    ]);
    const handleToggleExpand = useCallback(()=>{
        setIsExpanded(!isExpanded);
    }, [
        isExpanded
    ]);
    const handleShowMore = useCallback(()=>{
        setShowFullList(true);
    }, []);
    const handleShowLess = useCallback(()=>{
        setShowFullList(false);
    }, []);
    const handleSourceClick = useCallback((source)=>{
        if (!chatService) return;
        chatService?.getPreHook(AutopilotChatPreHookAction.CitationClick)({
            citation: source
        }).then((proceed)=>{
            if (!proceed) return;
            const url = 'url' in source ? source.url : `${source.download_url}${source.page_number ? `#page=${source.page_number}` : ''}`;
            if (url) window.open(url, '_blank', 'noopener,noreferrer');
        });
    }, [
        chatService
    ]);
    if (isWaitingForMoreMessages || isStreaming || 0 === sources.length) return null;
    const hasMoreItems = sources.length > COLLAPSED_ITEMS_COUNT;
    return /*#__PURE__*/ jsxs(StyledContainer, {
        children: [
            /*#__PURE__*/ jsxs(StyledToggleButton, {
                component: "button",
                title: _({
                    id: 'autopilot-chat.message.sources'
                }),
                onClick: handleToggleExpand,
                children: [
                    /*#__PURE__*/ jsx(ApIcon, {
                        variant: "outlined",
                        name: "link",
                        size: spacing.compactMode ? apollo_core.Icon.IconS : apollo_core.Icon.IconM,
                        color: 'var(--color-foreground)'
                    }),
                    /*#__PURE__*/ jsx(ApTypography, {
                        variant: spacing.primaryFontToken,
                        color: 'var(--color-foreground)',
                        children: _({
                            id: 'autopilot-chat.message.sources'
                        })
                    })
                ]
            }),
            /*#__PURE__*/ jsx(Collapse, {
                in: isExpanded,
                timeout: 300,
                children: /*#__PURE__*/ jsxs(StyledContentContainer, {
                    children: [
                        /*#__PURE__*/ jsxs(StyledSourcesListWrapper, {
                            isCollapsed: !showFullList && hasMoreItems,
                            children: [
                                /*#__PURE__*/ jsx(StyledSourcesList, {
                                    children: sources.map((source, index)=>{
                                        const isUrl = 'url' in source;
                                        const isPdf = 'download_url' in source;
                                        const pageNumber = isPdf && source.page_number ? source.page_number : 0;
                                        const pageText = isPdf && source.page_number ? ` (${_({
                                            id: 'autopilot-chat.message.page-number',
                                            values: {
                                                pageNumber: pageNumber
                                            }
                                        })})` : '';
                                        const text = `[${source.id}] ${source.title}${pageText}`;
                                        return /*#__PURE__*/ jsx(AutopilotChatTooltip, {
                                            title: text,
                                            children: /*#__PURE__*/ jsxs(StyledSourceItem, {
                                                role: "button",
                                                onClick: ()=>handleSourceClick(source),
                                                tabIndex: !showFullList && index > COLLAPSED_ITEMS_COUNT - 1 ? -1 : 0,
                                                children: [
                                                    /*#__PURE__*/ jsx(ApIcon, {
                                                        variant: isUrl ? 'custom' : 'outlined',
                                                        name: isUrl ? 'website' : 'file_open',
                                                        size: apollo_core.Icon.IconXs,
                                                        color: 'var(--color-primary)'
                                                    }),
                                                    /*#__PURE__*/ jsx(StyledSourceContent, {
                                                        children: /*#__PURE__*/ jsx(ApTypography, {
                                                            variant: spacing.primaryBoldFontToken,
                                                            color: 'var(--color-foreground-de-emp)',
                                                            children: text
                                                        })
                                                    })
                                                ]
                                            })
                                        }, `${source.id}-${index}`);
                                    })
                                }),
                                !showFullList && hasMoreItems && /*#__PURE__*/ jsx(StyledGradientOverlay, {})
                            ]
                        }),
                        hasMoreItems && /*#__PURE__*/ jsx(StyledActionContainer, {
                            children: /*#__PURE__*/ jsxs(StyledActionButton, {
                                component: "button",
                                title: showFullList ? _({
                                    id: 'autopilot-chat.message.show-less'
                                }) : _({
                                    id: 'autopilot-chat.message.show-more'
                                }),
                                onClick: showFullList ? handleShowLess : handleShowMore,
                                children: [
                                    /*#__PURE__*/ jsx(ApTypography, {
                                        variant: spacing.primaryBoldFontToken,
                                        color: 'var(--color-primary)',
                                        children: showFullList ? _({
                                            id: 'autopilot-chat.message.show-less'
                                        }) : _({
                                            id: 'autopilot-chat.message.show-more'
                                        })
                                    }),
                                    /*#__PURE__*/ jsx(ApIcon, {
                                        name: showFullList ? 'expand_less' : 'expand_more',
                                        variant: "outlined",
                                        size: apollo_core.Icon.IconXs,
                                        color: 'var(--color-primary)'
                                    })
                                ]
                            })
                        })
                    ]
                })
            })
        ]
    });
}
const AutopilotChatSources = /*#__PURE__*/ react.memo(AutopilotChatSourcesComponent);
export { AutopilotChatSources };
