import React, {SyntheticEvent, useEffect, useRef, useState} from 'react';
import { useOnClickOutside }                       from '../../util/useOnClickOutside';
import { Input }                                   from '../input/input.component';
import { EditableAreaRoot }                        from './styles';

interface Props {
    value: string;
    onChange: (value: string) => void;
  // eslint-disable-next-line react/require-default-props
    doubleClickMode?: boolean;
  // eslint-disable-next-line react/require-default-props
    disabled?: boolean;
    onError?: () => void
    errorMessage?: string
}

export const EditableArea = (props: Props) => {
    const [ isEditing, setIsEditing ] = useState(false);
    const [ value, setValue ] = useState(props.value);
    const rootRef = useRef();

    useEffect(() => {
        setValue(props.value)
    }, [props.value])

    const onSave = () => {
        if (!value && props.onError){
            props.onError()
        } else if (value !== props.value) {
            props.onChange(value);
        }
    }

    const closeAndSave = () => {
        if (!props.disabled && isEditing) {
            setIsEditing(false);
            onSave()
        }
    };

    // @ts-ignore
    useOnClickOutside(rootRef, closeAndSave);

    const handleKeyDown = (
        e: SyntheticEvent<HTMLInputElement, KeyboardEvent>
    ) => {
        if (e.nativeEvent.key === 'Enter') {
            closeAndSave();
        }
    };

    const enableEditing = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (!props.disabled && !isEditing) {
            e.preventDefault();
            e.stopPropagation();
            setIsEditing(true);
        }
    };

    return (
    // @ts-ignore
        <EditableAreaRoot
            ref={ rootRef }
            // onClick={ props.doubleClickMode ? undefined : enableEditing }
            onClick={ (e) => {
                if (isEditing) {
                    e.preventDefault();
                    e.stopPropagation();
                }
            } }
            onDoubleClick={ props.doubleClickMode ? enableEditing : undefined }
        >
            { isEditing ? (
                <Input value={ value } onChange={ (e) => setValue(e.target.value) } onKeyDown={ handleKeyDown } autoFocus />
            ) : (
                <>{ value }</>
            ) }
        </EditableAreaRoot>
    );
};
