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

const TextArea = Input.TextArea;

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

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

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

  handleChange = e => {
    const value = e.target.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 } = this.state;
    return (
      <div className="editable-cell">
        {editable ? (
          <div className="editable-cell-input-wrapper">
            <TextArea value={value} onChange={this.handleChange} onpressenter={this.check} onkeyup={value => this.onKeyUpValidator(value)} />
            <Icon icon="check" className="editable-cell-icon-check" onClick={this.check} />
          </div>
        ) : inital ? (
          <div className="editable-cell-input-wrapper">
            <TextArea value={value} onChange={this.handleChange} onPressEnter={this.check} />
            <Icon icon="check" className="editable-cell-icon-check" onClick={this.check} />
          </div>
        ) : (
          <div className="editable-cell-text-wrapper">
            {value || ' '}
            <Icon icon="edit" className="editable-cell-icon" onClick={this.edit} />
          </div>
        )}
      </div>
    );
  }
}

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