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

// Style
/* istanbul ignore next */
if (typeof window !== 'undefined') require('./style.scss');

export default class TextArea extends React.Component {
  static propTypes = {
    onChange: PropTypes.func,
    resize: PropTypes.oneOf(['both', 'horizontal', 'none', 'vertical']),
    size: PropTypes.oneOf(['lg', 'md', 'sm']),
    value: PropTypes.string,
  };

  static defaultProps = {
    resize: 'vertical',
    size: 'md',
  };

  constructor(props) {
    super(props);
    this.state = {
      value: props.value,
    };
  }

  componentDidUpdate({ value: stateVal }) {
    const { value } = this.props;
    if (stateVal !== value) this.setState({ value });
  }

  onChange = event => {
    this.setState({ value: event.target.value });
    /* istanbul ignore else */
    if (typeof this.props.onChange === 'function') this.props.onChange(event);
  };

  render() {
    const { className, resize, onChange, size, value, ...attributes } = this.props;
    const TextAreaClasses = ['TextArea', `TextArea_${size}`, `TextArea_${resize}`, className].filter(e => e).join(' ');
    return <textarea {...attributes} className={TextAreaClasses} onChange={this.onChange} value={this.state.value} />;
  }
}
