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

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

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

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

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

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

export default Input;
