import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { InputNumber , Icon } from 'amos-framework';

class EditableCellInputNum extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: this.props.value,
      editable: true,
      inital: this.props.inital,
      disabled: this.props.disabled ? true : false
    };
  }

  componentWillReceiveProps(nextProps) {
    const { value,inital } = nextProps;
    this.setState({ value,inital });
  }

  onKeyUpValidator = (value) => {
    console.log(value);
    value = value.replace(/[^\d]/g,'');
    console.log(value);
  }

  handleChange = value => {
    const { editable } = this.state;
    this.setState({ value });
    this.props.onChange(value,editable);
  };

  check = () => {
    const editable = false;
    this.setState({ editable, inital: false });
    if (this.props.onChange) {
      this.props.onChange(this.state.value,editable);
    }
  };

  edit = () => {
    this.setState({ editable: true });
  };

  render() {
    const { value, editable, inital, disabled } = this.state;
    return (
      <div className="editable-cell">
        {editable ? (
          <div className="editable-cell-input-wrapper">
            <InputNumber min={0} style={{ width: '82%' }} disabled={disabled} value={value} onChange={this.handleChange} onpressenter={this.check} onkeyup={value => this.onKeyUpValidator(value)} />
            <Icon hidden={disabled} icon="check" className="editable-cell-icon-check" onClick={this.check} />
          </div>
        ) : inital ? (
          <div className="editable-cell-input-wrapper">
            <InputNumber min={0} style={{ width: '82%' }} disabled={disabled} value={value} onChange={this.handleChange} onPressEnter={this.check} />
            <Icon hidden={disabled} icon="check" className="editable-cell-icon-check" onClick={this.check} />
          </div>
        ) : (
          <div className="editable-cell-text-wrapper">
            {value || ' '}
            <Icon  hidden={disabled} icon="edit" className="editable-cell-icon" onClick={this.edit} />
          </div>
        )}
      </div>
    );
  }
}

EditableCellInputNum.propTypes = {
  inital: PropTypes.bool,
  onChange: PropTypes.func,
  value: PropTypes.string,
  disabled: PropTypes.bool
};
export default EditableCellInputNum;
