import React from 'react';
import PropTypes from 'prop-types';

export default class Input extends React.Component {
    static propTypes = {
        onChange: PropTypes.func,
        onEnterPressed: PropTypes.func,
        value: PropTypes.string,
    };

    state = {
        value: '',
        props: {},
    };

    onChange = e => {
        const { value } = e.target;
        this.setState({ value });
        if (this.props.onChange) {
            this.props.onChange(e, this);
        }
    };

    get value() {
        return this.state.value;
    }

    /*componentDidMount() {
        this.setState(Input.getDerivedStateFromProps(this.props, this.state));
    }

    componentWillReceiveProps(nextProps) {
        this.setState(Input.getDerivedStateFromProps(nextProps, this.state));
    }*/

    static getDerivedStateFromProps(nextProps, prevState) {
        if (nextProps.value !== prevState.props.value) {
            return {
                value: nextProps.value,
                props: nextProps,
            };
        }
        return null;
    }

    onKeyUp = e => {
        if (13 === e.keyCode && this.props.onEnterPressed) {
            this.props.onEnterPressed();
        }
    };

    getProps() {
        // eslint-disable-next-line no-unused-vars
        const { onEnterPressed, ...otherProps } = this.props;
        return otherProps;
    }

    render() {
        return (
            <input
                {...this.getProps()}
                value={this.state.value}
                onChange={this.onChange}
                ref={ref => (this.element = ref)}
                onKeyUp={this.onKeyUp}
            />
        );
    }
}
