var OrderBox = React.createClass({
    getInitialState: function () {
        return {
            data: [],
            customerdata: []
        };
    },

    loadMenuItemsFromServer: function () {
        $.ajax({
            url: '/getmenuitemslist/',
            dataType: 'json',
            cache: false,
            success: function (data) {
                this.setState({ data: data });
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(status, err.toString());
            }.bind(this)
        });
    },

    loadCustomerFromServer: function () {
        $.ajax({
            url: '/getloggedincustomer/',
            dataType: 'json',
            cache: false,
            success: function (data) {
                this.setState({ customerdata: data });
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(status, err.toString());
            }.bind(this)
        });
    },

    componentDidMount: function () {
        this.loadMenuItemsFromServer();
        this.loadCustomerFromServer();
    },

    handleOrderSubmit: function (orderinfo) {
        $.ajax({
            url: '/frontorder',
            dataType: 'json',
            type: 'POST',
            data: orderinfo,
            success: function (data) {
                if (data.error) {
                    alert(data.error);
                } else {
                    alert("Order submitted");
                    window.location.reload(true);
                }
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(status, err.toString());
                alert("Order error");
            }.bind(this)
        });
    },

    render: function () {
        return (
            <div>
                <h1>Simulated Pickup Order</h1>
                <p>Browse our available menu items below and submit your order.</p>
                <OrderForm
                    data={this.state.data}
                    customerdata={this.state.customerdata}
                    onOrderSubmit={this.handleOrderSubmit}
                />
            </div>
        );
    }
});

var OrderForm = React.createClass({
    getInitialState: function () {
        return {
            customerid: "",
            ordertype: "Pickup",
            orderstatus: "Open",
            menuitemid: "",
            quantity: "1",
            pickup: ""
        };
    },

    componentWillReceiveProps: function (nextProps) {
        if (nextProps.customerdata.length > 0) {
            this.setState({
                customerid: String(nextProps.customerdata[0].dbCustomerId)
            });
        }

        if (this.state.menuitemid === "" && nextProps.data.length > 0) {
            this.setState({
                menuitemid: String(nextProps.data[0].dbMenuItemId)
            });
        }
    },

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

        var customerid = this.state.customerid.trim();
        var ordertype = this.state.ordertype.trim();
        var orderstatus = this.state.orderstatus.trim();
        var menuitemid = this.state.menuitemid;
        var quantity = this.state.quantity.trim();
        var pickup = this.state.pickup.trim();

        if (!customerid) {
            alert("Please log in as a customer before placing an order.");
            return;
        }

        if (!menuitemid || !quantity || !pickup) {
            alert("All fields are required");
            return;
        }

        this.props.onOrderSubmit({
            customerid: customerid,
            ordertype: ordertype,
            orderstatus: orderstatus,
            menuitemid: menuitemid,
            quantity: quantity,
            pickup: pickup
        });
    },

    handleChange: function (event) {
        this.setState({
            [event.target.id]: event.target.value
        });
    },

    render: function () {
        if (this.state.customerid === "") {
            return (
                <div>
                    <h2>No Access</h2>
                    <p>Please log in from the Customer Login page first.</p>
                    <p><a href="customerlogin.html">Go to Customer Login</a></p>
                </div>
            );
        }

        return (
            <div>
                <div id="theform">
                    <form onSubmit={this.handleSubmit}>
                        <table>
                            <tbody>
                                <tr>
                                    <th>Customer ID</th>
                                    <td>
                                        <input type="text" name="customerid" id="customerid" value={this.state.customerid} readOnly />
                                    </td>
                                </tr>
                                <tr>
                                    <th>Order Type</th>
                                    <td>
                                        <input type="text" name="ordertype" id="ordertype" value={this.state.ordertype} readOnly />
                                    </td>
                                </tr>
                                <tr>
                                    <th>Order Status</th>
                                    <td>
                                        <input type="text" name="orderstatus" id="orderstatus" value={this.state.orderstatus} readOnly />
                                    </td>
                                </tr>
                                <tr>
                                    <th>Menu Item</th>
                                    <td>
                                        <SelectList
                                            data={this.props.data}
                                            selectedValue={this.state.menuitemid}
                                            onSelectChange={this.handleChange}
                                        />
                                    </td>
                                </tr>
                                <tr>
                                    <th>Quantity</th>
                                    <td>
                                        <input
                                            type="number"
                                            min="1"
                                            name="quantity"
                                            id="quantity"
                                            value={this.state.quantity}
                                            onChange={this.handleChange}
                                        />
                                    </td>
                                </tr>
                                <tr>
                                    <th>Pickup Time</th>
                                    <td>
                                        <input
                                            type="time"
                                            name="pickup"
                                            id="pickup"
                                            value={this.state.pickup}
                                            onChange={this.handleChange}
                                        />
                                    </td>
                                </tr>
                            </tbody>
                        </table><br />
                        <input type="submit" value="Submit Order" />
                    </form>
                </div>
            </div>
        );
    }
});

var SelectList = React.createClass({
    render: function () {
        var optionNodes = this.props.data.map(function (menuitem) {
            return (
                <option key={menuitem.dbMenuItemId} value={menuitem.dbMenuItemId}>
                    {menuitem.dbMenuName}
                </option>
            );
        });

        return (
            <select
                name="menuitemid"
                id="menuitemid"
                value={this.props.selectedValue}
                onChange={this.props.onSelectChange}
            >
                <option value=""></option>
                {optionNodes}
            </select>
        );
    }
});

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