import React, {PureComponent} from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import omit from 'lodash.omit';
import humanize from 'underscore.string/humanize';
import {required as requiredValidator} from 'shared/constants/validators';
import {validateValue} from 'shared/utils/validation';

import './form_field.scss';

const FormFieldDecorator = WrappedComponent =>
  class FormField extends PureComponent {
    static displayName = 'FormField';

    static propTypes = {
      defaultValue: PropTypes.any,
      value: PropTypes.any,
      onChange: PropTypes.func,
      validators: PropTypes.array,
      required: PropTypes.bool,
      name: PropTypes.string,
      label: PropTypes.string,
      wrapperClassName: PropTypes.string,
      showErrorWhenInvalid: PropTypes.bool
    };

    static defaultProps = {
      validators: [],
      showErrorWhenInvalid: true
    };

    constructor(props) {
      super(props);

      this.state = {
        value: props.defaultValue
      };
    }

    isControlled() {
      return typeof this.props.value !== 'undefined';
    }

    getValue() {
      return this.isControlled() ? this.props.value : this.state.value;
    }

    onChange = value => {
      if (!this.isControlled()) this.setState({value});
      if (this.props.onChange) this.props.onChange(value);
    };

    validate() {
      const {required, label, name} = this.props;
      const validators = required
        ? [requiredValidator, ...this.props.validators]
        : this.props.validators;

      return validateValue(
        this.getValue(),
        validators,
        label || humanize(name)
      );
    }

    isValid() {
      return this.validate().isValid;
    }

    getValidationMessage() {
      return this.validate().message;
    }

    focus() {
      if (this.element && this.element.focus) this.element.focus();
    }

    render() {
      const {showErrorWhenInvalid, wrapperClassName} = this.props;

      return (
        <div className={classNames('mo-web-form-field', wrapperClassName)}>
          <WrappedComponent
            {...omit(
              this.props,
              'defaultValue',
              'value',
              'onChange',
              'validators',
              'label',
              'showErrorWhenInvalid',
              'wrapperClassName'
            )}
            ref={element => (this.element = element)}
            value={this.getValue()}
            isValid={this.isValid() || !showErrorWhenInvalid}
            onChange={this.onChange}
          />
          {!this.isValid() && showErrorWhenInvalid && (
            <div className="mo-web-form-field-error">
              {this.getValidationMessage()}
            </div>
          )}
        </div>
      );
    }
  };

export default FormFieldDecorator;
