import React, { Component } from 'react';
import './index.less';

export default class Input extends Component {
  constructor(props) {
    super(props);
    this.defaultValue = props.value;
    this.state = { value: props.value };
  }

  componentWillReceiveProps(nextProps) {
    if (this.defaultValue !== nextProps.value) {
      this.defaultValue = nextProps.value;
      this.setState({ value: nextProps.value });
    }
  }

  onChange(value) {
    this.setState({ value });
  }

  onSave(value) {
    const { onChange } = this.props;
    if (onChange) onChange(value);
  }

  render() {
    return (
      <input
        readOnly={this.props.readOnly}
        value={this.state.value}
        onChange={e => this.onChange(e.target.value)}
        onBlur={e => this.onSave(e.target.value)}
        onFocus={e => this.props.onFocus(e)}
      />
    );
  }
}
