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

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

export default class Input extends React.Component {
  static propTypes = {
    onChange: PropTypes.func,
    size: PropTypes.oneOf(['lg', 'md', 'sm']),
    type: PropTypes.string,
    value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  };

  static defaultProps = {
    size: 'md',
    type: 'text',
  };

  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, size, type, onChange, value, ...attributes } = this.props;
    const InputClasses = ['Input', `Input_${size}`, className].filter(e => e).join(' ');
    return (
      <input {...attributes} className={InputClasses} onChange={this.onChange} type={type} value={this.state.value} />
    );
  }
}
