import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useLingui } from "@lingui/react";
import { Box, styled } from "@mui/material";
import apollo_core from "@uipath/apollo-core";
import react from "react";
import { useAttachments } from "../../providers/attachements-provider.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 { useResourceData } from "../../providers/resource-data-provider.js";
import { useStreaming } from "../../providers/streaming-provider.js";
import { AutopilotChatEvent, AutopilotChatInternalEvent } from "../../service/index.js";
import { parseFiles } from "../../utils/file-reader.js";
import { fontByVariant } from "../../utils/font-by-variant.js";
import { AutopilotChatInputActions } from "./chat-input-actions.js";
import { AutopilotChatInputAttachments } from "./chat-input-attachments.js";
import { ChatInputEditor } from "./chat-input-editor.js";
import { AutopilotChatInputError } from "./chat-input-error.js";
import { AutopilotChatInputFooter } from "./chat-input-footer.js";
const InputContainer = styled('div')(({ primaryFontToken })=>({
        border: `${apollo_core.Border.BorderThickM} solid transparent`,
        boxShadow: `inset 0 0 0 ${apollo_core.Border.BorderThickS} var(--color-border)`,
        borderRadius: apollo_core.Border.BorderRadiusL,
        gap: apollo_core.Spacing.SpacingBase,
        marginBottom: apollo_core.Spacing.SpacingXs,
        '&:focus-within': {
            borderColor: 'var(--color-focus-indicator)',
            boxShadow: 'none'
        },
        '& .MuiTextField-root': {
            width: '100%',
            height: apollo_core.Spacing.SpacingM,
            verticalAlign: 'middle'
        },
        '& .autopilot-chat-input': {
            position: 'relative'
        },
        '& .autopilot-chat-input .tiptap-editor-container': {
            padding: `0 ${apollo_core.Spacing.SpacingBase}`,
            color: 'var(--color-foreground)',
            '&:focus': {
                boxShadow: 'none'
            },
            ...primaryFontToken && (()=>{
                const fontToken = fontByVariant(primaryFontToken);
                return fontToken ? {
                    fontSize: fontToken.fontSize,
                    fontFamily: fontToken.fontFamily,
                    lineHeight: fontToken.lineHeight,
                    fontWeight: fontToken.fontWeight
                } : {};
            })()
        }
    }));
const GradientContainer = styled('div')(()=>({
        position: 'absolute',
        zIndex: 1,
        bottom: '2px',
        left: apollo_core.Spacing.SpacingBase,
        width: `calc(100% - 2 * ${apollo_core.Spacing.SpacingBase})`,
        height: apollo_core.Spacing.SpacingXs,
        background: `linear-gradient(
        to bottom,
        var(--color-background)50 0%,
        var(--color-background)75 25%,
        var(--color-background) 50%
    )`
    }));
function AutopilotChatInputComponent() {
    const { _ } = useLingui();
    const chatService = useChatService();
    const initialPrompt = chatService?.getPrompt?.();
    const { disabledFeatures, overrideLabels, spacing } = useChatState();
    const { hasResources } = useResourceData();
    const [message, setMessage] = react.useState('string' == typeof initialPrompt ? initialPrompt : initialPrompt?.content ?? '');
    const editorRef = react.useRef(null);
    const inputContainerRef = react.useRef(null);
    const { waitingResponse, skeletonLoader } = useLoading();
    const { streaming } = useStreaming();
    const { attachments, clearAttachments, addAttachments, attachmentsLoading } = useAttachments();
    const editorLineHeight = react.useMemo(()=>{
        const fontToken = fontByVariant(spacing.primaryFontToken);
        return fontToken?.lineHeight;
    }, [
        spacing.primaryFontToken
    ]);
    react.useEffect(()=>{
        if (!chatService) return;
        const unsubscribeSetInputFocused = chatService.__internalService__.on(AutopilotChatInternalEvent.SetInputFocused, (value)=>{
            if (value) editorRef.current?.focus();
        });
        const unsubscribeSetPrompt = chatService.on(AutopilotChatEvent.SetPrompt, (prompt)=>{
            setMessage('string' == typeof prompt ? prompt : prompt.content);
        });
        return ()=>{
            unsubscribeSetInputFocused();
            unsubscribeSetPrompt();
        };
    }, [
        chatService
    ]);
    const handleChange = react.useCallback((value)=>{
        if (0 === value.trim().length) return void chatService.setPrompt('');
        chatService.setPrompt(value);
    }, [
        chatService
    ]);
    const handleSubmit = react.useCallback(()=>{
        if (waitingResponse || streaming) return void chatService.stopResponse();
        if (chatService.isSpeechToTextActive) chatService.publishSpeechToTextToggle();
        const serializedContent = editorRef.current?.getSerializedContent() ?? message;
        chatService.sendRequest({
            content: serializedContent,
            attachments
        });
        editorRef.current?.clear();
        setMessage('');
        clearAttachments();
    }, [
        message,
        attachments,
        clearAttachments,
        chatService,
        waitingResponse,
        streaming
    ]);
    const handleKeyDown = react.useCallback((event)=>{
        if ('Enter' !== event.key || event.shiftKey) return false;
        if (waitingResponse || streaming) {
            event.preventDefault();
            return true;
        }
        const editorContent = editorRef.current?.getSerializedContent() ?? message;
        if ((editorContent.trim().length > 0 || attachments.length > 0) && !skeletonLoader) {
            handleSubmit();
            return true;
        }
        return false;
    }, [
        message,
        handleSubmit,
        waitingResponse,
        streaming,
        skeletonLoader,
        attachments
    ]);
    const handlePaste = react.useCallback(async (event)=>{
        if (disabledFeatures?.attachments) return;
        const items = event.clipboardData?.items;
        if (!items) return;
        const allowedAttachments = Object.keys(chatService?.getConfig()?.allowedAttachments?.types ?? {});
        const attachmentsToAdd = [];
        let foundAllowedAttachment = false;
        for(let i = 0; i < items.length; i++)if (allowedAttachments.includes(items[i].type)) {
            const blob = items[i].getAsFile();
            if (blob) {
                attachmentsToAdd.push(blob);
                foundAllowedAttachment = true;
            }
        }
        if (foundAllowedAttachment) event.preventDefault();
        const parsedFiles = await parseFiles(attachmentsToAdd);
        addAttachments(parsedFiles);
    }, [
        chatService,
        addAttachments,
        disabledFeatures?.attachments
    ]);
    react.useEffect(()=>{
        const container = inputContainerRef.current;
        if (!container) return;
        container.addEventListener('paste', handlePaste);
        return ()=>{
            container.removeEventListener('paste', handlePaste);
        };
    }, [
        handlePaste
    ]);
    const hasLoadingAttachments = attachmentsLoading.filter((attachment)=>attachment.loading).length > 0;
    const isInputEmpty = 0 === message.trim().length && 0 === attachments.length;
    const handleResourceTriggerClick = react.useCallback(()=>{
        editorRef.current?.openResourcePicker();
    }, []);
    const [isVoiceInteractionActive, setIsVoiceInteractionActive] = react.useState(false);
    return /*#__PURE__*/ jsxs(Fragment, {
        children: [
            !isVoiceInteractionActive && /*#__PURE__*/ jsx(AutopilotChatInputError, {}),
            /*#__PURE__*/ jsxs(InputContainer, {
                primaryFontToken: spacing.primaryFontToken,
                onClick: isVoiceInteractionActive ? void 0 : ()=>editorRef?.current?.focus(),
                ref: inputContainerRef,
                sx: isVoiceInteractionActive ? {
                    borderColor: 'transparent',
                    boxShadow: 'none',
                    background: 'transparent'
                } : void 0,
                children: [
                    /*#__PURE__*/ jsx(AutopilotChatInputAttachments, {}),
                    /*#__PURE__*/ jsxs(Box, {
                        className: "autopilot-chat-input",
                        sx: {
                            padding: `${apollo_core.Spacing.SpacingS} 0 0 !important`,
                            ...isVoiceInteractionActive && {
                                visibility: 'hidden'
                            }
                        },
                        children: [
                            /*#__PURE__*/ jsx("div", {
                                className: "tiptap-editor-container",
                                children: /*#__PURE__*/ jsx(ChatInputEditor, {
                                    ref: editorRef,
                                    value: message,
                                    placeholder: overrideLabels?.inputPlaceholder ?? _({
                                        id: 'autopilot-chat.input.placeholder'
                                    }),
                                    onChange: handleChange,
                                    onKeyDown: handleKeyDown,
                                    minRows: spacing.promptBox.minRows,
                                    maxRows: spacing.promptBox.maxRows,
                                    lineHeight: editorLineHeight
                                })
                            }),
                            /*#__PURE__*/ jsx(GradientContainer, {})
                        ]
                    }),
                    /*#__PURE__*/ jsx(AutopilotChatInputActions, {
                        disableSubmit: isInputEmpty && !waitingResponse && !streaming || skeletonLoader && !waitingResponse && !streaming || hasLoadingAttachments,
                        isInputEmpty: isInputEmpty,
                        waitingResponse: waitingResponse || streaming,
                        handleSubmit: handleSubmit,
                        onResourceTriggerClick: hasResources ? handleResourceTriggerClick : void 0,
                        onVoiceInteractionChange: setIsVoiceInteractionActive,
                        isVoiceInteractionActive: isVoiceInteractionActive
                    })
                ]
            }),
            !disabledFeatures?.footer && /*#__PURE__*/ jsx(AutopilotChatInputFooter, {})
        ]
    });
}
const AutopilotChatInput = /*#__PURE__*/ react.memo(AutopilotChatInputComponent);
export { AutopilotChatInput };
