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

export default function ContenteditableSimple({editableRef, value, onChange, className, keyDown, disabled, autofocus, ...props}) {
    const [isEmpty, setIsEmpty] = useState(!value);
    const contentSetupRef = useRef(false);

    useEffect(() => {
        if (editableRef.current) {
            const currentText = editableRef.current.innerText;
            if (currentText !== value && !(currentText === '\n' && value === '')) {
                editableRef.current.innerText = value || '';
                setIsEmpty(!value);
            }
            if (!contentSetupRef.current) {
                setTimeout(() => {
                    // Autofocus
                    if (autofocus) {
                        fieldFocus(editableRef.current);
                    }
                }, 0);
                contentSetupRef.current = true;
            }
        }
    }, [value]);

    const handleInput = () => {
        let newValue = editableRef.current.innerText;
        if (newValue === '\n' || newValue === '') {
            newValue = '';
        }
        setIsEmpty(newValue === '');
        onChange(newValue);
    }

    const handlePaste = (e) => {
        e.preventDefault();
        const text = e.clipboardData.getData('text/plain');
        document.execCommand('insertText', false, text);
    }

    const handleKeyDown = (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            const newValue = editableRef.current.innerText;
            onChange(newValue === '\n' ? '' : newValue);
        }
        if (typeof keyDown === 'function') {
            keyDown(e);
        }
    }

    const handleFocus = () => {
    }

    const handleBlur = () => {
    }

    return (
        <div
            ref={editableRef}
            contentEditable={!disabled}
            onInput={handleInput}
            onPaste={handlePaste}
            onKeyDown={handleKeyDown}
            onFocus={handleFocus}
            onBlur={handleBlur}
            className={className}
            {...props}
        />
    );
}