import React from 'react'
import {Validation} from "./validate.js";
import {useShopStore} from "./shop_store";
import {ShowJSON} from "./ShowJSON";

// #!render_count
import {useRenderCount} from "@uidotdev/usehooks";
import {OrderOptions} from "./OrderOptions";


/**
 * Components that renders the form to request quote.
 */
export function OrderForm() {
    // #!render_count
    const renderCount = useRenderCount();

    const email = useShopStore((state) => state.email);
    const note = useShopStore((state) => state.note);
    const isProcessing = useShopStore((state) => state.isProcessing);
    const updateEmail = useShopStore((state) => state.updateEmail);
    const updateNote = useShopStore((state) => state.updateNote);
    const submitForm = useShopStore((state) => state.submitForm);
    const submitDisabled = useShopStore((state) => state.submitDisabled);
    const resetEmailValidation = useShopStore((state) => state.resetEmailValidation);

    // #!render_count
    console.log("OrderForm renders: ", renderCount)

    return (
        <div className="summary-form">

            <OrderOptions/>

            <form onSubmit={submitForm} noValidate>

                <input
                    className={`${email.error > 0 ? 'errorField' : ''}`}
                    type="email"
                    placeholder="Email"
                    onFocus={resetEmailValidation}
                    onChange={(event) => updateEmail(event.target.value)}
                    onBlur={(event) => updateEmail(event.target.value)}
                    value={email.value}/>

                {email.error === Validation.Empty ? (
                    <div className="error">
                        <small>Required</small>
                    </div>
                ) : null}

                {email.error === Validation.Invalid ? (
                    <div className="error">
                        <small>Your email is incomplete</small>
                    </div>
                ) : null}

                <textarea
                    onChange={(event) => updateNote(event.target.value)}
                    defaultValue={note.value}
                    rows="5"
                    placeholder="Additional notes"/>

                <div className="d-flex flex-column flex-sm-row justify-content-between">
                    <ShowJSON/>

                    <input className="btn btn-primary w-100 m-0 ms-sm-2 order-form-submit" type="button"
                           disabled={submitDisabled()}
                           onClick={submitForm}
                           value={`${isProcessing ? 'Processing ...' : 'Request quote'}`}/>
                </div>
                {/*This will open an email window. Send the email to make your request.*/}
            </form>

        </div>
    );

}