import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef } from "react";
import "./style.scss";
import { IconButton, Loader } from "..";
const PromptField = ({ placeholderText = "Write here...", isDisabled = false, isLoading = false, isReadOnly = false, onSubmit, value, setValue = () => false, dataCy, }) => {
    const textareaRef = useRef(null);
    useEffect(() => {
        window.addEventListener("resize", handleAutoResize);
        return () => {
            window.removeEventListener("resize", handleAutoResize);
        };
    }, []);
    useEffect(() => {
        handleAutoResize();
        if (textareaRef.current) {
            textareaRef.current.focus();
        }
    }, [value]);
    const handleAutoResize = () => {
        if (textareaRef.current) {
            const prevHeight = textareaRef.current.style.height;
            textareaRef.current.style.height = "0px";
            const { scrollHeight } = textareaRef.current;
            if (scrollHeight < 115) {
                textareaRef.current.style.height = `${scrollHeight + 1}px`;
            }
            else if (parseInt(prevHeight, 10) < 115) {
                textareaRef.current.style.height = "114px";
            }
            else {
                textareaRef.current.style.height = prevHeight;
            }
        }
    };
    const handleKeyDown = (event) => {
        if (!isLoading && !isDisabled && !isReadOnly) {
            if (event.key === "Enter" && !event.shiftKey) {
                event.preventDefault();
                handleSubmit();
            }
        }
    };
    const handleSubmit = () => {
        if (typeof onSubmit === "function") {
            onSubmit(value);
        }
    };
    const onchange = (event) => {
        setValue(event.target.value);
    };
    return (_jsxs("form", { className: "promptField", onSubmit: (e) => e.preventDefault(), children: [_jsx("textarea", { ref: textareaRef, className: "promptFieldInput", readOnly: isReadOnly, placeholder: placeholderText, value: value, onChange: onchange, onKeyDown: handleKeyDown, "data-cy": `${dataCy}-input` }), isLoading ? (_jsx(Loader, { height: "24", width: "24", type: "threeDots" })) : (_jsx(IconButton, { isDisabled: isDisabled, iconType: "searchArrow", onClick: handleSubmit, sizeVariant: "sm", variant: "primary", color: "orange", "data-cy": `${dataCy}-submit` }))] }));
};
export default PromptField;
