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 EditProduct({ productID }) {
    if (typeof productID != "string") {
        return (
            <div>
            </div>
        )
    }
    let [form, setForm] = useState({ name: "", price: 0 });
    let [busy, setBusy] = useState(false);
    let [errors,setErrors] = useState([""]);

    const getInitialData = async() => {
        const client = new ProductClient();
        let data = await client.get(productID);
        setBusy(false);
        setForm(
            {
                name: data.name,
                price: data.price,
            }
        );
    }
    // Startup
    useEffect(() => {
        setBusy(true);
        if (productID) {
            getInitialData();
        }
    }, [productID]);

    const onFormChanged = (form) => {
        setForm(form);
    }
    
    const validate = () => {
        let errors: string[] = validateForm(form);
        setErrors(errors);
        return errors.length == 0;
    }
    const onSubmit = async () => {
        if (validate()) {
            setBusy(true);
            try {
                const client = new ProductClient();
                await client.put(productID, {
                    name: form.name,
                    price: form.price,
                })
                Swal.fire({
                    title: "Submitted!",
                    text: "Product is modified in database",
                })
            } catch (error) {

            } finally {
                setBusy(false);
            }
        }
    }

    return (
        <div className="container mx-auto">
            <h1>Edit 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 EditProductPage() {
    const router = useRouter();
    const id = router.query['id'];

    return (
        <Layout title="Edit product">
            <EditProduct productID={id}></EditProduct>
        </Layout>
    )
}