var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import React from 'react';
import { TextArea } from '@patternfly/react-core';
// Import Chatbot components
import SendButton from './SendButton';
import MicrophoneButton from './MicrophoneButton';
import { AttachButton } from './AttachButton';
import AttachMenu from '../AttachMenu';
import StopButton from './StopButton';
export const MessageBar = (_a) => {
    var { onSendMessage, className, alwayShowSendButton, hasAttachButton = true, hasMicrophoneButton, handleAttach, attachMenuProps, isSendButtonDisabled, handleStopButton, hasStopButton, buttonProps, onChange, displayMode, value } = _a, props = __rest(_a, ["onSendMessage", "className", "alwayShowSendButton", "hasAttachButton", "hasMicrophoneButton", "handleAttach", "attachMenuProps", "isSendButtonDisabled", "handleStopButton", "hasStopButton", "buttonProps", "onChange", "displayMode", "value"]);
    // Text Input
    // --------------------------------------------------------------------------
    const [message, setMessage] = React.useState(value !== null && value !== void 0 ? value : '');
    const [isListeningMessage, setIsListeningMessage] = React.useState(false);
    const [hasSentMessage, setHasSentMessage] = React.useState(false);
    const textareaRef = React.useRef(null);
    const attachButtonRef = React.useRef(null);
    const setInitialLineHeight = (field) => {
        field.style.setProperty('line-height', '1rem');
        const parent = field.parentElement;
        if (parent) {
            parent.style.setProperty('margin-top', `1rem`);
            parent.style.setProperty('margin-bottom', `0rem`);
            parent.style.setProperty('height', 'inherit');
            const grandparent = parent.parentElement;
            if (grandparent) {
                grandparent.style.setProperty('flex-basis', 'auto');
            }
        }
    };
    const setAutoHeight = (field) => {
        const parent = field.parentElement;
        if (parent) {
            parent.style.setProperty('height', 'inherit');
            const computed = window.getComputedStyle(field);
            // Calculate the height
            const height = parseInt(computed.getPropertyValue('border-top-width')) +
                parseInt(computed.getPropertyValue('padding-top')) +
                field.scrollHeight +
                parseInt(computed.getPropertyValue('padding-bottom')) +
                parseInt(computed.getPropertyValue('border-bottom-width'));
            parent.style.setProperty('height', `${height}px`);
            if (height > 32 || window.innerWidth <= 507) {
                parent.style.setProperty('margin-bottom', `1rem`);
                parent.style.setProperty('margin-top', `1rem`);
            }
        }
    };
    const textIsLongerThan2Lines = (field) => {
        const lineHeight = parseFloat(window.getComputedStyle(field).lineHeight);
        const lines = field.scrollHeight / lineHeight;
        return lines > 2;
    };
    const setAutoWidth = React.useCallback((field) => {
        const parent = field.parentElement;
        if (parent) {
            const grandparent = parent.parentElement;
            if (textIsLongerThan2Lines(field) && grandparent) {
                grandparent.style.setProperty('flex-basis', `100%`);
            }
        }
    }, []);
    const handleNewLine = (field) => {
        const parent = field.parentElement;
        if (parent) {
            parent.style.setProperty('margin-bottom', `1rem`);
            parent.style.setProperty('margin-top', `1rem`);
        }
    };
    React.useEffect(() => {
        const field = textareaRef.current;
        if (field) {
            if (field.value === '') {
                if (window.innerWidth > 507) {
                    setInitialLineHeight(field);
                }
            }
            else {
                setAutoHeight(field);
                setAutoWidth(field);
            }
        }
        const resetHeight = () => {
            if (field) {
                if (field.value === '') {
                    if (window.innerWidth > 507) {
                        setInitialLineHeight(field);
                    }
                }
                else {
                    setAutoHeight(field);
                    setAutoWidth(field);
                }
            }
        };
        window.addEventListener('resize', resetHeight);
        return () => {
            window.removeEventListener('resize', resetHeight);
        };
    }, [setAutoWidth]);
    React.useEffect(() => {
        const field = textareaRef.current;
        if (field) {
            if (field.value === '') {
                setInitialLineHeight(textareaRef.current);
            }
            else {
                setAutoHeight(textareaRef.current);
                setAutoWidth(field);
            }
        }
    }, [displayMode, message, setAutoWidth]);
    React.useEffect(() => {
        const field = textareaRef.current;
        if (field) {
            setInitialLineHeight(field);
            setHasSentMessage(false);
        }
    }, [hasSentMessage]);
    const handleChange = React.useCallback((event) => {
        onChange && onChange(event, event.target.value);
        if (textareaRef.current) {
            if (event.target.value === '') {
                setInitialLineHeight(textareaRef.current);
            }
            else {
                setAutoHeight(textareaRef.current);
            }
        }
        setMessage(event.target.value);
    }, [onChange]);
    // Handle sending message
    const handleSend = React.useCallback((newMessage) => {
        onSendMessage(newMessage);
        setHasSentMessage(true);
        setMessage('');
    }, [onSendMessage]);
    const handleKeyDown = React.useCallback((event) => {
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault();
            if (!isSendButtonDisabled && !hasStopButton) {
                handleSend(message);
            }
        }
        if (event.key === 'Enter' && event.shiftKey) {
            if (textareaRef.current) {
                handleNewLine(textareaRef.current);
            }
        }
    }, [isSendButtonDisabled, hasStopButton, handleSend, message]);
    const handleAttachMenuToggle = () => {
        (attachMenuProps === null || attachMenuProps === void 0 ? void 0 : attachMenuProps.setIsAttachMenuOpen) && (attachMenuProps === null || attachMenuProps === void 0 ? void 0 : attachMenuProps.setIsAttachMenuOpen(!(attachMenuProps === null || attachMenuProps === void 0 ? void 0 : attachMenuProps.isAttachMenuOpen)));
        attachMenuProps === null || attachMenuProps === void 0 ? void 0 : attachMenuProps.onAttachMenuToggleClick();
    };
    const handleSpeechRecognition = (message) => {
        setMessage(message);
        onChange && onChange({}, message);
    };
    const renderButtons = () => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
        if (hasStopButton && handleStopButton) {
            return (React.createElement(StopButton, Object.assign({ onClick: handleStopButton, tooltipContent: (_a = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.stop) === null || _a === void 0 ? void 0 : _a.tooltipContent }, (_b = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.stop) === null || _b === void 0 ? void 0 : _b.props)));
        }
        return (React.createElement(React.Fragment, null,
            attachMenuProps && (React.createElement(AttachButton, Object.assign({ ref: attachButtonRef, onClick: handleAttachMenuToggle, isDisabled: isListeningMessage, tooltipContent: (_c = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _c === void 0 ? void 0 : _c.tooltipContent }, (_d = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _d === void 0 ? void 0 : _d.props))),
            !attachMenuProps && hasAttachButton && (React.createElement(AttachButton, Object.assign({ onAttachAccepted: handleAttach, isDisabled: isListeningMessage, tooltipContent: (_e = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _e === void 0 ? void 0 : _e.tooltipContent, inputTestId: (_f = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _f === void 0 ? void 0 : _f.inputTestId }, (_g = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _g === void 0 ? void 0 : _g.props))),
            hasMicrophoneButton && (React.createElement(MicrophoneButton, Object.assign({ isListening: isListeningMessage, onIsListeningChange: setIsListeningMessage, onSpeechRecognition: handleSpeechRecognition, tooltipContent: (_h = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.microphone) === null || _h === void 0 ? void 0 : _h.tooltipContent, language: (_j = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.microphone) === null || _j === void 0 ? void 0 : _j.language }, (_k = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.microphone) === null || _k === void 0 ? void 0 : _k.props))),
            (alwayShowSendButton || message) && (React.createElement(SendButton, Object.assign({ value: message, onClick: () => handleSend(message), isDisabled: isSendButtonDisabled, tooltipContent: (_l = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.send) === null || _l === void 0 ? void 0 : _l.tooltipContent }, (_m = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.send) === null || _m === void 0 ? void 0 : _m.props)))));
    };
    const messageBarContents = (React.createElement(React.Fragment, null,
        React.createElement("div", { className: "pf-chatbot__message-bar-input" },
            React.createElement(TextArea, Object.assign({ className: "pf-chatbot__message-textarea", value: message, onChange: handleChange, "aria-label": isListeningMessage ? 'Listening' : 'Send a message...', placeholder: isListeningMessage ? 'Listening' : 'Send a message...', ref: textareaRef, onKeyDown: handleKeyDown }, props))),
        React.createElement("div", { className: "pf-chatbot__message-bar-actions" }, renderButtons())));
    if (attachMenuProps) {
        return (React.createElement(AttachMenu, Object.assign({ toggle: (toggleRef) => (React.createElement("div", { ref: toggleRef, className: `pf-chatbot__message-bar ${className !== null && className !== void 0 ? className : ''}` }, messageBarContents)), filteredItems: attachMenuProps === null || attachMenuProps === void 0 ? void 0 : attachMenuProps.attachMenuItems }, (attachMenuProps && { isOpen: attachMenuProps.isAttachMenuOpen }), { onOpenChange: (isAttachMenuOpen) => {
                var _a;
                (_a = attachButtonRef.current) === null || _a === void 0 ? void 0 : _a.focus();
                attachMenuProps === null || attachMenuProps === void 0 ? void 0 : attachMenuProps.setIsAttachMenuOpen(isAttachMenuOpen);
                (attachMenuProps === null || attachMenuProps === void 0 ? void 0 : attachMenuProps.onAttachMenuOpenChange) && (attachMenuProps === null || attachMenuProps === void 0 ? void 0 : attachMenuProps.onAttachMenuOpenChange(isAttachMenuOpen));
            }, onOpenChangeKeys: attachMenuProps === null || attachMenuProps === void 0 ? void 0 : attachMenuProps.onAttachMenuOnOpenChangeKeys, onSelect: attachMenuProps === null || attachMenuProps === void 0 ? void 0 : attachMenuProps.onAttachMenuSelect }, (attachMenuProps && { handleTextInputChange: attachMenuProps.onAttachMenuInputChange }), { popperProps: { direction: 'up', distance: '8' }, searchInputPlaceholder: attachMenuProps === null || attachMenuProps === void 0 ? void 0 : attachMenuProps.attachMenuInputPlaceholder })));
    }
    return React.createElement("div", { className: `pf-chatbot__message-bar ${className !== null && className !== void 0 ? className : ''}` }, messageBarContents);
};
export default MessageBar;
