import { IReactComponent } from '@wowpic/xform-types';
import { Input as AntdInput } from 'antd';
import React, {
    FormEvent, FunctionComponent, useCallback, useEffect, useState
} from 'react';

const AntdTextArea = AntdInput.TextArea;

const TextArea: FunctionComponent<IReactComponent> = ({
    value,
    onChange: onChangeDefault,
    onBlur: onBlurDefault,
    ...restProps
}) => {
    const [inputValue, setInputValue] = useState(value);

    useEffect(() => {
        setInputValue(value);
    }, [value]);

    const onChange = useCallback((e: FormEvent<HTMLTextAreaElement>) => {
        const v = (e.target as HTMLTextAreaElement).value;
        setInputValue(v);
        onChangeDefault(v);
    }, [onChangeDefault]);

    const onBlur = useCallback((e: FormEvent<HTMLTextAreaElement>) => {
        const v = (e.target as HTMLTextAreaElement).value.trim();
        setInputValue(v);
        onChangeDefault(v);
        onBlurDefault(v);
    }, [onChangeDefault, onBlurDefault]);

    return (
        <AntdTextArea
            onChange={onChange}
            onBlur={onBlur}
            value={inputValue}
            {...restProps} />
    );
};

export default TextArea;
