class BasicForm extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            forename: '',
            surname: '',
            email1: '',
            email2: '',
            address: '',
            city: '',
            postcode: '',
            tel: ''
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(e) {
        e.target.classList.add('active');
        this.setState({
            [e.target.name]: e.target.value
        });
        this.showInputError(e.target.name);

    }

    handleSubmit(e) {
        if(e.type === "click") {
            e.preventDefault();

            return !!this.showFormErrors();
        }
    }

    showFormErrors() {
        let isFormValid = true;
        for (let ref in this.refs) {
            let node = this.refs[ref];
            node.classList.add('active');
            const isInputValid = this.showInputError(ref);
            if (!isInputValid) {
                isFormValid = false;
                this.refs[ref].focus();
            }
        }
        return isFormValid;
    }

    showInputError(refName) {
        const val = this.refs[refName].validity;
        const errorOnRef = document.getElementById(`${refName}Error`);

        const isEmail = refName === "email1";
        const isEmailConfirm = refName === "email2";
        const isTel = refName === "tel";
        const isForm = refName === "form";

        if (isEmailConfirm) {
            if (this.refs.email1.value !== this.refs.email2.value) {
                this.refs.email2.setCustomValidity('Emails do not match');
            } else {
                this.refs.email2.setCustomValidity('');
            }
        }

        if (val.valueMissing) {
            this.refs[refName].setCustomValidity(`This field is required`);
            errorOnRef.textContent = `This field is required`;
            errorOnRef.style.display = 'block';
        } else if (isEmail && val.typeMismatch) {
            this.refs.email1.setCustomValidity(`Please enter a valid email address`);
            errorOnRef.textContent = `Please enter a valid email address`;
            errorOnRef.style.display = 'block';
        } else if (isTel && val.patternMismatch) {
            this.refs.tel.setCustomValidity(`Please provide the telephone number using digits`);
            errorOnRef.textContent = `Please provide the telephone number using digits`;
            errorOnRef.style.display = 'block';
        } else if (isEmailConfirm && val.customError) {
            errorOnRef.textContent = `Emails do not match`;
            errorOnRef.style.display = 'block';
        } else if (!isForm) {
            this.refs[refName].setCustomValidity('');
            errorOnRef.textContent = '';
            errorOnRef.style.display = 'none';
        }

        return this.refs[refName].checkValidity();
    }

    render() {
        return (
            <div className="container">
                <div>

                    <form id="instituteForm" name="instituteForm" className="search twelve columns bv-form"
                          action={window.countryCode + "/education/africa_order_successful"}
                          method="post">
                        <input type="hidden" name="form" id="form" ref="form" value="africa"/>
                        <div className="twelve columns">

                            <p><br/><br/>Please enter your account details and select the products you wish to purchase. A
                                customer service representative will be in touch to finalise your order.<br/>
                                (* Denotes a required field)<br/><br/>
                                Ordering on behalf of an institution means you will receive an invoice at your school or
                                college.</p>

                        </div>


                        <div className="form-group has-feedback">

                            <fieldset>
                                <legend className="heading-primary">Your details</legend>

                                <div className="six columns col-md-6 form-group">
                                    <label className="control-label">First name *</label>
                                    <input type="text" className="form-control" name="forename" value={this.state.forename}
                                           onChange={this.handleChange} ref="forename" id="forename" required="required"/>
                                    <small className=" help-block" id="forenameError" style={{display: 'none'}}/>
                                </div>

                                <div className="six columns col-md-6">
                                    <label className="control-label">Last name *</label>
                                    <input type="text" className="form-control" name="surname" id="surname"
                                           value={this.state.surname}
                                           onChange={this.handleChange} ref="surname"
                                           required="required"/>
                                    <small className=" help-block" id="surnameError" style={{display: 'none'}}/>
                                </div>
                                <br className="breaker"/>

                                <div className="six columns col-md-6">
                                    <label className="control-label">Your email *</label>
                                    <input type="email" className="form-control" name="email1" id="email1"
                                           value={this.state.email1}
                                           onChange={this.handleChange} ref="email1"
                                           required="required"/>
                                    <small className=" help-block" id="email1Error" style={{display: 'none'}}/>
                                </div>

                                <div className="six columns col-md-6">
                                    <label className="control-label">Re-enter your email *</label>
                                    <input type="email" className="form-control" name="email2" value={this.state.email2}
                                           onChange={this.handleChange} ref="email2" id="email2"
                                           required="required"/>
                                    <small className=" help-block" id="email2Error" style={{display: 'none'}}/>
                                </div>
                                <br className="breaker"/>

                                <div className="six columns col-md-6">
                                    <label className="control-label">Delivery address *</label>

                                    <input type="text" className="form-control" name="address" id="address"
                                           value={this.state.address} ref="address"
                                           onChange={this.handleChange} required="required"/>
                                    <small className=" help-block" id="addressError" style={{display: 'none'}}/>
                                </div>


                                <div className="six columns col-md-6">
                                    <label className="control-label">City *</label>

                                    <input type="text" className="form-control" name="city" id="city"
                                           value={this.state.city} ref="city"
                                           onChange={this.handleChange} required="required"/>
                                    <small className=" help-block" id="cityError" style={{display: 'none'}}/>
                                </div>
                                <br className="breaker"/>
                                <div className="six columns col-md-6">
                                    <label className="control-label">Post code *</label>
                                    <input type="text" className="form-control" name="postcode" id="postcode"
                                           value={this.state.postcode}
                                           onChange={this.handleChange} ref="postcode"
                                           required="required"/>
                                    <small className=" help-block" id="postcodeError" style={{display: 'none'}}/>
                                </div>


                                <div className="six columns col-md-6">
                                    <label className="control-label">Phone number *</label>
                                    <input type="text" className="form-control" name="tel" id="tel"
                                           value={this.state.tel}
                                           onChange={this.handleChange} ref="tel"
                                           pattern="^[0-9\- #]+$" required="required"/>
                                    <small className=" help-block" id="telError" style={{display: 'none'}}/>
                                </div>
                            </fieldset>
                            <button className="green large button" id="submitOrder"
                                    onClick={this.handleSubmit}  style={{display: 'none'}}>
                                <i className="fa fa-check-square-o">&nbsp;</i> Request Order
                            </button>
                            <input type="hidden" name="cartItemsPost" id="cartItemsPost"/>
                            <input type="hidden" name="cartTotalPricePost" id="cartTotalPricePost"/>
                        </div>
                    </form>
                </div>

                <div className="row confirm_order_container cart">
                    <div className="twelve columns">
                        <h1 className="subheader black">
                            Your order summary
                        </h1>

                        <h2 className="subheader black">You have selected the following items for purchase:</h2>
                    </div>

                    <div id="cartContainer">
                        <OrderRequestFormCartContainer handleSubmit={this.handleSubmit}/>
                    </div>
                </div>
            </div>

        );
    }
}

ReactDOM.render(<BasicForm/>, document.getElementById('app'));
