import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { Layout } from '../shared/Layout';
import { ProductClient } from '../../APIClient';
import Swal from 'sweetalert2';
import ProductForm from '../../components/ProductForm';
import Link from 'next/link';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faArrowLeft } from '@fortawesome/free-solid-svg-icons';
import { validateForm } from '../../lib/product';

function Errors({ errors }) {
    return errors.map(x => (
        <li>{x}</li>
    ));
}

function CreateProduct() {
    let [form, setForm] = useState({ name: "", price: 0 });
    let [busy, setBusy] = useState(false);
    let [errors, setErrors] = useState([""]);

    const onFormChanged = (form) => {
        setForm(form);
    }
    const onSubmit = async () => {
        setBusy(true);
        try {
            const client = new ProductClient();
            await client.post({
                name: form.name,
                price: form.price,
            })
            Swal.fire({
                title: "Submitted!",
                text: "Product is added in database",
            })
        } catch (error) {

        } finally {
            setBusy(false);
        }
    }

    return (
        <div className="container mx-auto">
            <h1>Create Product</h1>
            <Link href="/product/">
                <a>
                    <FontAwesomeIcon icon={faArrowLeft} /> Return to index
                    </a>
            </Link>
            <ProductForm
                name={form.name}
                price={form.price}
                busy={busy}
                onFormChange={onFormChanged}
                onSubmit={onSubmit} />
            <ul>
                <Errors errors={errors}></Errors>
            </ul>
        </div>
    );
}

export default function CreateProductPage() {
    return (
        <Layout title="Create product">
            <CreateProduct></CreateProduct>
        </Layout>
    )
}