import React, { ChangeEvent } from 'react';
import { withRouter, NextRouter } from 'next/router';
import { Layout } from '../../shared/Layout';
import { CustomerClient } from '../../../APIClient';
import Swal from 'sweetalert2';

function Errors({ errors }) {
    return errors.map(x => (
        <li>{x}</li>
    ));
}
class EditCustomer extends React.Component<{
    router: NextRouter,
}, {
    form: {
        name: string,
        email: string,
    },
    errors: string[],
    busy: boolean,
}> {
    constructor(props) {
        super(props)
        const router = props.router;
        const { id } = router.query!;
        this.state = {
            form: {
                name: "",
                email: "",
            },
            errors: [],
            busy: false,
        }
    }
    async componentDidMount() {
        const client = new CustomerClient();
        console.log(this.props.router)
        if (this.props.router.query['id']) {
            let data = await client.get(this.props.router.query['id']);
            this.setState({
                form: {
                    name: data.name,
                    email: data.email,
                }
            });
        }
    }
    onNameChanged(e: ChangeEvent<HTMLInputElement>) {
        this.setState({
            form: {
                name: e.target.value,
                email: this.state.form.email,
            }
        });
    }
    onEmailChanged(e: ChangeEvent<HTMLInputElement>) {
        this.setState({
            form: {
                name: this.state.form.name,
                email: e.target.value
            }
        });
    }
    async validate() {
        let errors: string[] = [];
        if (!this.state.form.name) {
            errors.push("Name required");
        }
        if (!this.state.form.email) {
            errors.push("Email required");
        }
        await new Promise((resolve) => {
            this.setState({
                errors
            }, () => resolve(undefined));
        })
        return errors.length == 0;
    }
    async onSubmit(e) {
        e.preventDefault();
        if (await this.validate()) {
            await new Promise((resolve) => {
                this.setState({
                    busy: true,
                }, () => resolve(undefined));
            })
            try {
                const form = this.state.form;
                const client = new CustomerClient();
                await client.put(this.props.router.query.id, {
                    name: form.name,
                    email: form.email,
                })
                Swal.fire({
                    title: "Submitted!",
                    text: "Customer is now in database",
                })
            } catch (error) {

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

            }
        }
    }
    render() {
        return (
            <form>
                <fieldset disabled={this.state.busy}>
                    <div className="mb-3">
                        <label htmlFor="name">Name</label>
                        <input className="form-control" id="name" value={this.state.form.name} onChange={this.onNameChanged.bind(this)}></input>
                    </div>
                    <div className="mb-3">
                        <label htmlFor="email">Email</label>
                        <input className="form-control" id="email" value={this.state.form.email} onChange={this.onEmailChanged.bind(this)}></input>
                    </div>
                    <div className="mb-3">
                        <button type="submit" className="btn btn-primary" onClick={this.onSubmit.bind(this)}>Edit</button>
                    </div>
                    <li>
                        <Errors errors={this.state.errors}></Errors>
                    </li>
                </fieldset>
            </form>
        )
    }
}

export default function EditCustomerPage() {
    let EditCustomerMain = withRouter(EditCustomer);
    return (
        <Layout title="Edit customer">
            <EditCustomerMain></EditCustomerMain>
        </Layout>
    )
}