import React, { ChangeEvent } from 'react';
import { withRouter, NextRouter, 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 { ProductDataProps, ProductFormState } from '../../../interfaces/product';

function Errors({ errors }) {
    return errors.map(x => (
        <li>{x}</li>
    ));
}
class EditProduct extends React.Component<ProductDataProps,ProductFormState> {
    constructor(props) {
        super(props)
        const id = props.productID;
        this.state = {
            form: {
                name: "",
                price: 0,
            },
            errors: [],
            busy: false,
        }
    }
    async componentDidMount() {
        const client = new ProductClient();
        await new Promise((resolve) => {
            this.setState({
                busy: true,
            }, () => resolve(undefined));
        })
        if (this.props.productID) {
            let data = await client.get(this.props.productID);
            await new Promise((resolve) => {
                this.setState({
                    busy: false,
                }, () => resolve(undefined));
            })
            this.setState({
                form: {
                    name: data.name,
                    price: data.price,
                }
            });
        }
    }
    onNameChanged(newName: string) {
        this.setState({
            form: {
                name: newName,
                price: this.state.form.price,
            }
        });
    }
    onPriceChanged(newPrice: number) {
        this.setState({
            form: {
                name: this.state.form.name,
                price: newPrice,
            }
        });
    }
    async validate() {
        let errors: string[] = [];
        if (!this.state.form.name) {
            errors.push("Name required");
        }
        if (!this.state.form.price) {
            errors.push("Email required");
        }
        await new Promise((resolve) => {
            this.setState({
                errors
            }, () => resolve(undefined));
        })
        return errors.length == 0;
    }
    async onSubmit() {
        if (await this.validate()) {
            await new Promise((resolve) => {
                this.setState({
                    busy: true,
                }, () => resolve(undefined));
            })
            try {
                const form = this.state.form;
                const client = new ProductClient();
                await client.put(this.props.productID, {
                    name: form.name,
                    price: form.price,
                })
                Swal.fire({
                    title: "Submitted!",
                    text: "Product is modified in database",
                })
            } catch (error) {

            } finally {
                await new Promise((resolve) => {
                    this.setState({
                        busy: false,
                    }, () => resolve(undefined));
                })

            }
        }
    }
    render() {
        if (typeof this.props.productID != "string") {
            return (
                <div>
                </div>
            )
        }
        return (
            <div className="container mx-auto">
                <h1>Edit Product</h1>
                <Link href="/product/">
                    <a>
                        <FontAwesomeIcon icon={faArrowLeft} /> Return to index
                    </a>
                </Link>
                <ProductForm
                    name={this.state.form.name}
                    price={this.state.form.price}
                    busy={this.state.busy}
                    onNameChange={this.onNameChanged.bind(this)}
                    onPriceChange={this.onPriceChanged.bind(this)}
                    onSubmit={this.onSubmit.bind(this)} />
                <ul>
                    <Errors errors={this.state.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>
    )
}