import { faChevronUp } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React, { useState } from "react";
import { validateForm } from "../lib/product";
import Errors from "./Errors";


export default function ProductForm({ name, price, onFormChange, onSubmit, busy }) {
    let [form, setForm] = useState({
        name: "",
        value: "",
    });
    let [errors, setErrors] = useState({
        name: new Array<string>(),
        price: new Array<string>(),
    });

    let nameChanged = (e: React.ChangeEvent<HTMLInputElement>) => {
        name = e.target.value;
        setErrors(validateForm({name,price}));
        onFormChange({ name, price });
    }
    let priceChanged = (e: React.ChangeEvent<HTMLInputElement>) => {
        price = e.target.value;
        setErrors(validateForm({name,price}));
        onFormChange({ name, price });
    }
    let isValid = (prop) => {
        if(errors[prop].length > 0) {
            return "form-control is-invalid";
        } else {
            return "form-control is-valid";
        }
    }
    let submit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        let currentErrors = validateForm({ name, price});
        if (currentErrors.name.length === 0 && currentErrors.price.length === 0) {
            onSubmit();
        }
    }

    return (
        <div>

            <form onSubmit={submit}>
                <fieldset disabled={busy}>
                    <div>
                        <label htmlFor="name">Name</label>
                        <input className={isValid("name")} id="name" value={name} onChange={nameChanged}></input>
                    </div>
                    <div className="mb-3">
                        <Errors errors={errors.name} />
                    </div>

                    <div>
                        <label htmlFor="price">Price</label>
                        <input type="number" className={isValid("price")} id="price" value={price} onChange={priceChanged}></input>
                    </div>
                    <div className="mb-3">
                        <Errors errors={errors.price} />
                    </div>
                    <div className="mb-3">
                        <button type="submit" className="btn btn-primary">
                            <FontAwesomeIcon icon={faChevronUp} /> Submit
                    </button>
                    </div>
                </fieldset>
            </form>
        </div>
    );
}