import React, { Component } from 'react';
import Formous from 'formous';

class ErrorText extends Component {
  render() {
    return <div style={{ color: '#f00' }}>
      {this.props.errorText}
    </div>
  }
}

class MyComponent extends Component {
  componentWillReceiveProps(nextProps) {
    // Set default form values (might be appropriate in a different method
    this.props.setDefaultValues({
      age: 33,
      name: 'Sir Fluffalot',
    });
  }

  handleSubmit(formStatus, fields) { // 4 -> handle Formouse arguments passed to handler
    if (!formStatus.touched) {
      alert('Please fill out the form.');
      return;
    }

    if (!formStatus.valid) {
      alert('Please address the errors in the form.');
      return;
    }

    // All good! Do something with fields.name.value and fields.age.value
    console.log(formStatus, fields);
  }

  render() {
    const {
      fields: { age, name },
      formSubmit, // 2 -> Export Formous validation function to current scope
    } = this.props;

    return <div> 
      <form onSubmit={formSubmit(this.handleSubmit)}> // 3 -> wrap form event handler with Formous vailidation function
        <div>
          <input
            placeholder="Name"
            type="text"
            value={name.value}
            { ...name.events }
          />
          <ErrorText { ...name.failProps } />
        </div>
        <div>
          <input
            placeholder="Age"
            type="text"
            value={age.value}
            { ...age.events }
          />
          <ErrorText { ...age.failProps } />
        </div>
        <div>
          <button type="submit">Submit</button>
        </div>
      </form>
    </div>
  }
}

const fields = {
  name: {
    tests: [
      {
        critical: true,
        failProps: {
          errorText: 'Name is required.',
        },
        test(value) {
          return value !== '';
        },
      }
    ],
  },

  age: {
    tests: [
      {
        critical: true,
        failProps: {
          errorText: 'Age should be a number.',
        },
        test(value) {
          return /^\d*$/.test(value);
        },
      },
      {
        critical: false,
        failProps: {
          errorText: 'Are you sure you\'re that old? :o',
        },
        test(value) {
          return +value < 120;
        },
      },
    ],
  },
};

export default Formous(fields)(MyComponent)  // 1 - wrap target component