import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useLingui } from "@lingui/react";
import { styled } from "@mui/material";
import apollo_core, { FontVariantToken } from "@uipath/apollo-core";
import react from "react";
import { ApTypography } from "../../../ap-typography/index.js";
import { useAttachments } from "../../providers/attachements-provider.js";
import { useChatService } from "../../providers/chat-service.provider.js";
import { useChatState } from "../../providers/chat-state-provider.js";
import { useError } from "../../providers/error-provider.js";
import { usePicker } from "../../providers/picker-provider.js";
import { AutopilotChatEvent } from "../../service/index.js";
import { parseFiles } from "../../utils/file-reader.js";
import { AutopilotChatActionButton } from "../common/action-button.js";
import { VisuallyHidden } from "../common/shared-controls.js";
import { AlwaysOnVoiceButton, VoiceButtonContainer } from "./always-on-voice-button.js";
import { AutopilotChatAgentModeSelector } from "./chat-input-agent-mode-selector.js";
import { AutopilotChatInputModelPicker } from "./chat-input-model-picker.js";
import { ResourceTriggerButton } from "./chat-input-resource-trigger.js";
const InputActionsContainer = styled('div')(()=>({
        display: 'flex',
        justifyContent: 'space-between',
        padding: `0 ${apollo_core.Spacing.SpacingXs} ${apollo_core.Spacing.SpacingXs}`
    }));
const InputActionsGroup = styled('div')(()=>({
        display: 'flex',
        gap: apollo_core.Spacing.SpacingMicro
    }));
const SubmitButtonContainer = styled('div')(()=>({
        '& .MuiIconButton-root': {
            borderRadius: apollo_core.Border.BorderRadiusM,
            backgroundColor: 'var(--color-background-disabled)',
            '&:not(.Mui-disabled)': {
                backgroundColor: "var(--color-foreground) !important",
                '&:hover, &:active, &:focus': {
                    backgroundColor: "var(--color-foreground-de-emp) !important"
                }
            }
        }
    }));
function AutopilotChatInputActionsComponent({ handleSubmit, disableSubmit, isInputEmpty, waitingResponse, onResourceTriggerClick, onVoiceInteractionChange, isVoiceInteractionActive }) {
    const { _ } = useLingui();
    const chatService = useChatService();
    const { addAttachments } = useAttachments();
    const { setError } = useError();
    const { disabledFeatures, allowedAttachments } = useChatState();
    const { models, agentModes } = usePicker();
    const [isSpeechToTextActive, setIsSpeechToTextActive] = react.useState(()=>chatService?.isSpeechToTextActive ?? false);
    react.useEffect(()=>{
        if (!chatService) return;
        setIsSpeechToTextActive(chatService.isSpeechToTextActive);
        return chatService.on(AutopilotChatEvent.SetSpeechToTextState, (isActive)=>{
            setIsSpeechToTextActive(isActive);
        });
    }, [
        chatService
    ]);
    const handleSpeechToTextClick = react.useCallback(()=>{
        chatService?.publishSpeechToTextToggle();
    }, [
        chatService
    ]);
    const fileInputRef = react.useRef(null);
    const handleFileButtonClick = ()=>{
        if (fileInputRef.current) {
            fileInputRef.current.value = '';
            fileInputRef.current.click();
        }
    };
    const handleAttachment = react.useCallback(async (event)=>{
        try {
            const parsedFiles = await parseFiles(Array.from(event.target.files ?? []));
            const oversizedFiles = parsedFiles.filter((file)=>file.size > allowedAttachments.maxSize);
            if (oversizedFiles.length > 0) {
                const errorMessages = oversizedFiles.map((file)=>{
                    const fileSizeMB = Math.round(file.size / 1024 / 1024);
                    const fileName = file.name;
                    const fileSize = fileSizeMB;
                    const maxSize = allowedAttachments.maxSize / 1024 / 1024;
                    return _({
                        id: 'autopilot-chat.input.actions.error.file-too-large',
                        values: {
                            fileName: fileName,
                            fileSize: fileSize,
                            maxSize: maxSize
                        }
                    });
                });
                setError(errorMessages.join('\n'));
            } else setError(void 0);
            addAttachments(parsedFiles.filter((file)=>file.size <= allowedAttachments.maxSize));
        } catch (err) {
            setError(err);
        }
    }, [
        addAttachments,
        setError,
        allowedAttachments.maxSize,
        _
    ]);
    const acceptedExtensions = react.useMemo(()=>Object.values(allowedAttachments.types).flat().join(','), [
        allowedAttachments
    ]);
    const attachmentDescription = react.useMemo(()=>{
        const parts = [];
        const maxCount = allowedAttachments.maxCount;
        const maxSize = allowedAttachments.maxSize / 1024 / 1024;
        const fileTypes = acceptedExtensions.split(',').join(', ');
        if (allowedAttachments.maxCount && allowedAttachments.maxCount > 1 && allowedAttachments.multiple) parts.push(_({
            id: 'autopilot-chat.input.actions.attachments.max-count',
            values: {
                maxCount: maxCount
            }
        }));
        parts.push(_({
            id: 'autopilot-chat.input.actions.attachments.max-size',
            values: {
                maxSize: maxSize
            }
        }), _({
            id: 'autopilot-chat.input.actions.attachments.allowed-types',
            values: {
                fileTypes: fileTypes
            }
        }));
        return parts.join('. ');
    }, [
        allowedAttachments,
        acceptedExtensions,
        _
    ]);
    const showVoice = false === disabledFeatures.audioStreaming && (isVoiceInteractionActive || !!isInputEmpty && !waitingResponse);
    const hasMultipleFeatures = [
        !disabledFeatures.attachments,
        models.length > 0,
        (agentModes?.length ?? 0) > 0
    ].filter(Boolean).length > 1;
    return /*#__PURE__*/ jsxs(InputActionsContainer, {
        children: [
            /*#__PURE__*/ jsxs(InputActionsGroup, {
                style: isVoiceInteractionActive ? {
                    visibility: 'hidden'
                } : void 0,
                children: [
                    !disabledFeatures.attachments && /*#__PURE__*/ jsxs(Fragment, {
                        children: [
                            /*#__PURE__*/ jsx("input", {
                                type: "file",
                                ref: fileInputRef,
                                style: {
                                    display: 'none'
                                },
                                accept: acceptedExtensions,
                                multiple: allowedAttachments.multiple,
                                onChange: handleAttachment
                            }),
                            /*#__PURE__*/ jsx(VisuallyHidden, {
                                id: "autopilot-chat-attach-file-description",
                                children: attachmentDescription
                            }),
                            /*#__PURE__*/ jsx(AutopilotChatActionButton, {
                                iconName: "attach_file",
                                onClick: handleFileButtonClick,
                                tooltipPlacement: "top",
                                "data-testid": "autopilot-chat-attach-file-button",
                                ariaLabel: _({
                                    id: 'autopilot-chat.input.actions.attach-file'
                                }),
                                ariaDescribedby: "autopilot-chat-attach-file-description",
                                tooltip: /*#__PURE__*/ jsxs(Fragment, {
                                    children: [
                                        /*#__PURE__*/ jsx(ApTypography, {
                                            color: 'var(--color-foreground-inverse)',
                                            variant: FontVariantToken.fontSizeM,
                                            children: _({
                                                id: 'autopilot-chat.input.actions.attach-file'
                                            })
                                        }),
                                        allowedAttachments.maxCount && allowedAttachments.maxCount > 1 && allowedAttachments.multiple && (()=>{
                                            const maxCount = allowedAttachments.maxCount;
                                            return /*#__PURE__*/ jsx(ApTypography, {
                                                color: 'var(--color-foreground-inverse)',
                                                variant: FontVariantToken.fontSizeXs,
                                                children: _({
                                                    id: 'autopilot-chat.input.actions.attachments.max-count',
                                                    values: {
                                                        maxCount: maxCount
                                                    }
                                                })
                                            });
                                        })(),
                                        (()=>{
                                            const maxSize = allowedAttachments.maxSize / 1024 / 1024;
                                            return /*#__PURE__*/ jsx(ApTypography, {
                                                color: 'var(--color-foreground-inverse)',
                                                variant: FontVariantToken.fontSizeXs,
                                                children: _({
                                                    id: 'autopilot-chat.input.actions.attachments.max-size',
                                                    values: {
                                                        maxSize: maxSize
                                                    }
                                                })
                                            });
                                        })(),
                                        (()=>{
                                            const fileTypes = acceptedExtensions.split(',').join(', ');
                                            return /*#__PURE__*/ jsx(ApTypography, {
                                                color: 'var(--color-foreground-inverse)',
                                                variant: FontVariantToken.fontSizeXs,
                                                children: _({
                                                    id: 'autopilot-chat.input.actions.attachments.allowed-types',
                                                    values: {
                                                        fileTypes: fileTypes
                                                    }
                                                })
                                            });
                                        })()
                                    ]
                                })
                            })
                        ]
                    }),
                    onResourceTriggerClick && /*#__PURE__*/ jsx(ResourceTriggerButton, {
                        onClick: onResourceTriggerClick
                    }),
                    models.length > 0 && /*#__PURE__*/ jsx(AutopilotChatInputModelPicker, {
                        useIcon: hasMultipleFeatures
                    }),
                    agentModes.length > 0 && /*#__PURE__*/ jsx(AutopilotChatAgentModeSelector, {
                        useIcon: false
                    })
                ]
            }),
            /*#__PURE__*/ jsxs(InputActionsGroup, {
                children: [
                    !isVoiceInteractionActive && !disabledFeatures.audio && /*#__PURE__*/ jsx(VoiceButtonContainer, {
                        active: isSpeechToTextActive,
                        children: /*#__PURE__*/ jsx(AutopilotChatActionButton, {
                            iconName: "mic",
                            onClick: handleSpeechToTextClick,
                            tooltipPlacement: "top",
                            tooltip: _({
                                id: 'autopilot-chat.input.actions.dictate'
                            }),
                            overrideColor: isSpeechToTextActive ? 'var(--color-background)' : void 0,
                            "data-testid": "autopilot-chat-stt-button",
                            ariaLabel: _({
                                id: 'autopilot-chat.input.actions.dictate'
                            }),
                            ariaPressed: isSpeechToTextActive
                        })
                    }),
                    showVoice && /*#__PURE__*/ jsx(AlwaysOnVoiceButton, {
                        disabled: isSpeechToTextActive,
                        onActiveChange: onVoiceInteractionChange
                    }),
                    !showVoice && /*#__PURE__*/ jsx(SubmitButtonContainer, {
                        children: /*#__PURE__*/ jsx(AutopilotChatActionButton, {
                            iconName: waitingResponse ? 'stop' : 'arrow_upward',
                            tooltip: waitingResponse ? _({
                                id: 'autopilot-chat.input.actions.stop'
                            }) : _({
                                id: 'autopilot-chat.input.actions.send'
                            }),
                            overrideColor: disableSubmit ? 'var(--color-foreground-disable)' : 'var(--color-background)',
                            variant: waitingResponse ? 'normal' : 'outlined',
                            preventHover: true,
                            disabled: disableSubmit,
                            onClick: handleSubmit,
                            "data-testid": "autopilot-chat-submit-button",
                            ariaLabel: waitingResponse ? _({
                                id: 'autopilot-chat.input.actions.stop'
                            }) : _({
                                id: 'autopilot-chat.input.actions.send'
                            })
                        })
                    })
                ]
            })
        ]
    });
}
const AutopilotChatInputActions = /*#__PURE__*/ react.memo(AutopilotChatInputActionsComponent);
export { AutopilotChatInputActions };
