import {useEffect, useRef, useState} from "@wordpress/element";

export default function ContentEditable({value, onChange, placeholder, className, disabled, autofocus, onEnter}) {
    const contentEditable = useRef(null);
    const [defaultValue, setDefaultValue] = useState(value);

    useEffect(() => {
        if (autofocus) {
            if (contentEditable.current) {
                contentEditable.current?.focus();

                // Move the cursor to the end
                const range = document.createRange();
                range.selectNodeContents(contentEditable.current);
                range.collapse(false);

                const selection = window.getSelection();
                selection.removeAllRanges();
                selection.addRange(range);
            }
        }
    }, []);

    const handleKeyDown = (e) => {
        if (e.key === 'Enter' && !disabled && onEnter) {
            e.preventDefault();
            onEnter(e);
        }
    }

    return (
        <div className={`lbaic-settings-contenteditable${className ? ' ' + className : ''}${value ? ' lbaic-settings-contenteditable-has-value' : ''}`}>
            <div className='lbaic-settings-contenteditable-holder'>
                <p ref={contentEditable} className='lbaic-settings-contenteditable-in' contentEditable={!disabled}
                   onInput={e => !disabled && onChange(e.currentTarget.textContent)}
                   onKeyDown={handleKeyDown}
                   tabIndex='-1'>
                    {defaultValue}
                    {/*This container's content is
                <div className='lbaic-settings-contenteditable-variable'>
                    <span className='lbaic-settings-contenteditable-variable-label'>very</span>
                    <button type='button' className='lbaic-settings-button-reset'>
                        <svg
                            className='lbaic-settings-contenteditable-variable-i'
                            xmlns='http://www.w3.org/2000/svg'
                            fill='none'
                            viewBox='0 0 24 24'
                        >
                            <use href='#lbaic-settings-close'/>
                        </svg>
                    </button>
                </div>
                editable*/}
                </p>
                {placeholder?.length > 0 &&
                    <div className="lbaic-settings-contenteditable-placeholder">
                        <div className="lbaic-settings-contenteditable-placeholder-in">
                            <span className="lbaic-settings-contenteditable-placeholder-desc">{placeholder}</span>
                        </div>
                    </div>}
            </div>
        </div>
    )
}