import React from 'react';
import classnames from 'classnames';

class CCNameInput extends React.Component {

  // If the page refreshes, make sure we update the parent state
  componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.props.value) this.props.onStateUpdate({name: nextProps.value});
  }

  /**
   * onChange event handler
   */
  _handleOnChange(e) {
    const value = e.target.value;
    this.props.onStateUpdate({name: value});
  }

  render() {
    const { disabled, error, value } = this.props;
    const fieldClasses = classnames('checkout-field', 'ccname', {error: error});
    return (
      <div className={fieldClasses}>
        <label className="checkout-field__label">FULL NAME</label>
        <input className="checkout-field__input"
          ref="ccNameInput"
          type="text"
          value={value}
          onChange={(e) => this._handleOnChange(e)}
          disabled={disabled}
        />
        {error ? (<div className="checkout-field__error">{error}</div>) : null}
      </div>
    );
  }
}

CCNameInput.propTypes = {
  onStateUpdate: React.PropTypes.func,
  error: React.PropTypes.string,
  disabled: React.PropTypes.bool,
  value: React.PropTypes.string
};

export default CCNameInput;
