var CustomerBox = React.createClass({
    getInitialState: function () {
        return { data: [] };
    },
    handleCustomerSubmit: function (customer) {
        $.ajax({
            url: '/frontcustomer',
            dataType: 'json',
            type: 'POST',
            data: customer,
            success: function (data) {
                this.setState({ data: data });
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(status, err.toString());
            }.bind(this)
        });
    },
    render: function () {
        return (
            <div className="CustomerBox">
                <h1>Customers</h1>
                <Customerform2 onCustomerSubmit={this.handleCustomerSubmit} />
            </div>
        );
    }
});

var Customerform2 = React.createClass({
    getInitialState: function () {
        return {
            customername: "",
            customeremail: "",
            customerphone: "",
            customerpw: "",
            selectedOption: ""
        };
    },

    handleOptionChange: function (e) {
        this.setState({
            selectedOption: e.target.value
        });
    },

    handleSubmit: function (e) {
        e.preventDefault();

        var customername = this.state.customername.trim();
        var customeremail = this.state.customeremail.trim();
        var customerphone = this.state.customerphone.trim();
        var customerpw = this.state.customerpw.trim();
        var customermailer = this.state.selectedOption;

        if (!this.validateEmail(customeremail)) {
            console.log("Bad Email");
            return;
        }

        if (!customername || !customeremail || !customerphone || !customerpw || customermailer === "") {
            console.log("Field Missing");
            return;
        }

        this.props.onCustomerSubmit({
            customername: customername,
            customeremail: customeremail,
            customerphone: customerphone,
            customerpw: customerpw,
            customermailer: customermailer
        });

        this.setState({
            customername: "",
            customeremail: "",
            customerphone: "",
            customerpw: "",
            selectedOption: ""
        });
    },

    validateEmail: function (value) {
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(value);
    },

    commonValidate: function () {
        return true;
    },

    setValue: function (field, event) {
        var object = {};
        object[field] = event.target.value;
        this.setState(object);
    },

    render: function () {
        return (
            <form onSubmit={this.handleSubmit}>
                <h2>Customers</h2>
                <table>
                    <tbody>
                        <tr>
                            <th>Customer Name</th>
                            <td>
                                <TextInput
                                    value={this.state.customername}
                                    uniqueName="customername"
                                    textArea={false}
                                    required={true}
                                    minCharacters={1}
                                    validate={this.commonValidate}
                                    onChange={this.setValue.bind(this, 'customername')}
                                    errorMessage="Customer Name is invalid"
                                    emptyMessage="Customer Name is required"
                                />
                            </td>
                        </tr>
                        <tr>
                            <th>Customer E-Mail</th>
                            <td>
                                <TextInput
                                    value={this.state.customeremail}
                                    uniqueName="customeremail"
                                    textArea={false}
                                    required={true}
                                    minCharacters={1}
                                    validate={this.validateEmail}
                                    onChange={this.setValue.bind(this, 'customeremail')}
                                    errorMessage="Invalid E-Mail Address"
                                    emptyMessage="E-Mail Address is Required"
                                />
                            </td>
                        </tr>
                        <tr>
                            <th>Customer Phone</th>
                            <td>
                                <TextInput
                                    value={this.state.customerphone}
                                    uniqueName="customerphone"
                                    textArea={false}
                                    required={true}
                                    minCharacters={1}
                                    validate={this.commonValidate}
                                    onChange={this.setValue.bind(this, 'customerphone')}
                                    errorMessage="Customer Phone is invalid"
                                    emptyMessage="Customer Phone is required"
                                />
                            </td>
                        </tr>
                        <tr>
                            <th>Customer Password</th>
                            <td>
                                <TextInput
                                    value={this.state.customerpw}
                                    uniqueName="customerpw"
                                    textArea={false}
                                    required={true}
                                    minCharacters={1}
                                    validate={this.commonValidate}
                                    onChange={this.setValue.bind(this, 'customerpw')}
                                    errorMessage="Customer Password is invalid"
                                    emptyMessage="Customer Password is required"
                                />
                            </td>
                        </tr>
                        <tr>
                            <th>Join Mailing List</th>
                            <td>
                                <input
                                    type="radio"
                                    name="custmailer"
                                    id="custmaileryes"
                                    value="1"
                                    checked={this.state.selectedOption === "1"}
                                    onChange={this.handleOptionChange}
                                /> YES

                                <input
                                    type="radio"
                                    name="custmailer"
                                    id="custmailerno"
                                    value="0"
                                    checked={this.state.selectedOption === "0"}
                                    onChange={this.handleOptionChange}
                                /> NO
                            </td>
                        </tr>
                    </tbody>
                </table>
                <input type="submit" value="Insert Customer" />
            </form>
        );
    }
});

var InputError = React.createClass({
    render: function () {
        return (
            <td>{this.props.errorMessage}</td>
        );
    }
});

var TextInput = React.createClass({
    getInitialState: function () {
        return {
            isEmpty: true,
            value: "",
            valid: false,
            errorMessage: "",
            errorVisible: false
        };
    },

    handleChange: function (event) {
        this.validation(event.target.value);

        if (this.props.onChange) {
            this.props.onChange(event);
        }
    },

    validation: function (value, valid) {
        if (typeof valid === 'undefined') {
            valid = true;
        }

        var message = "";
        var errorVisible = false;

        if (!valid) {
            message = this.props.errorMessage;
            valid = false;
            errorVisible = true;
        }
        else if (this.props.required && jQuery.isEmptyObject(value)) {
            message = this.props.emptyMessage;
            valid = false;
            errorVisible = true;
        }
        else if (this.props.minCharacters && value.length < this.props.minCharacters) {
            message = this.props.errorMessage;
            valid = false;
            errorVisible = true;
        }

        this.setState({
            value: value,
            isEmpty: jQuery.isEmptyObject(value),
            valid: valid,
            errorMessage: message,
            errorVisible: errorVisible
        });
    },

    handleBlur: function (event) {
        var valid = this.props.validate(event.target.value);
        this.validation(event.target.value, valid);
    },

    render: function () {
        if (this.props.textArea) {
            return (
                <div className={this.props.uniqueName}>
                    <textarea
                        placeholder={this.props.text}
                        className={'input input-' + this.props.uniqueName}
                        onChange={this.handleChange}
                        onBlur={this.handleBlur}
                        value={this.props.value}
                    />
                    <InputError
                        visible={this.state.errorVisible}
                        errorMessage={this.state.errorMessage}
                    />
                </div>
            );
        } else {
            return (
                <div className={this.props.uniqueName}>
                    <input
                        type={this.props.inputType || "text"}
                        name={this.props.uniqueName}
                        id={this.props.uniqueName}
                        placeholder={this.props.text}
                        className={'input input-' + this.props.uniqueName}
                        onChange={this.handleChange}
                        onBlur={this.handleBlur}
                        value={this.props.value}
                    />
                    <InputError
                        visible={this.state.errorVisible}
                        errorMessage={this.state.errorMessage}
                    />
                </div>
            );
        }
    }
});

ReactDOM.render(
    <CustomerBox />,
    document.getElementById('content')
);