import {useEffect, useRef, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import useClickOutside from "../../../../../hooks/use-click-outside";

export default function EditChatName({name, edit, close}) {
    const [value, setValue] = useState(name);
    const messageContainerRef = useRef(null);
    const inputRef = useRef(null);

    useClickOutside([messageContainerRef], () => edit(value));

    useEffect(() => {
        inputRef.current.focus();
    }, []);

    const onKeyDown = (e) => {
        if (e.key === "Enter") {
            if (value.trim().length) {
                edit(value);
            }
        } else if (e.key === "Escape") {
            close();
        }
    }

    return <div ref={messageContainerRef} className='lbaic-message'>
        <div className='lbaic-message-in'>
            <input
                ref={inputRef}
                className='lbaic-message-input'
                placeholder={__("Name", 'limb-chatbot')}
                value={value}
                onChange={e => setValue(e.target.value)}
                onKeyDown={onKeyDown}
                autoComplete="off"
            />
        </div>
    </div>
}