import React from "react";
import { Alert, Button, Card, Container, Form } from "react-bootstrap";
import { Link } from "react-router-dom";
import validator from "validator";
import { apiClient } from "../utils/httpClients";

export default class Signup extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            user: {
                email: null,
                firstName: null,
                lastName: null,
                phone: null,
                password: null
            },
            alert: {
                show: false,
                variant: null,
                headerMsg: null,
                content: null
            }
        };

        this.registerUser = this.registerUser.bind(this);
        this.setUserState = this.setUserState.bind(this);
    }


    async registerUser(event) {
        event.preventDefault(); // We need this so that the page doesn't refresh.
        let formIssues = this.validateCurrentForm();
        if (formIssues.length > 0) {
            this.notifyUser("Oops there were issue(s)", (
                <ul>
                    {formIssues.map((issue) => {
                        return (
                            <li key={issue}>{issue}</li>
                        );
                    })}
                </ul>
            ), "danger");
            return;
        }

        const res = await apiClient.post("/user", this.state.user);
        console.log(res.data);
        if (res.status === 201) {
            this.notifyUser("Success!", <div>You are successfully signed up! You <Link to="/login">can now go log in</Link>.</div>, "success");
        } else if (res.status === 409) {
            this.notifyUser("User exists!", <div>This user already exists. Try <Link to="/login">logging in</Link> instead.</div>, "danger");
        } else if (res.status === 400) {
            this.notifyUser("There were errors in the submitted info.", <div>Double check to see if everything is inputted is valid.</div>, "danger");
        } else {
            this.notifyUser("Error", <div>Internal server error. Please try again later.</div>, "danger");
        }
    }

    validateCurrentForm() {
        console.log(this.state);
        let formIssues = [];
        if (!validator.isEmail(this.state.user.email)) {
            formIssues.push("The email submitted is invalid.");
        }

        if (this.state.user.password.length < 8) {
            formIssues.push("The password submitted must have a minimum length of 8 characters.");
        }

        return formIssues;
    }

    setUserState(event) {
        this.setState((state) => {
            state.user[event.target.id] = event.target.value;
            return state;
        });
    }

    notifyUser(headerMsg, content, key) {
        this.setState((state) => {
            state.alert.show = true;
            state.alert.headerMsg = headerMsg;
            state.alert.content = content;
            state.alert.key = key;
            return state;
        });
    }

    componentDidMount() {
        if (this.context.user) {
            this.context.navigate("/dashboard");
        }
    }

    render() {
        return (
            <div className="page-root pt-3">
                <Container>
                    <Alert show={this.state.alert.show} variant="warning" onClose={() => this.setState((state) => { state.alert.show = false; return state; })} dismissible>
                        <Alert.Heading>{this.state.alert.headerMsg}</Alert.Heading>
                        {this.state.alert.content}
                    </Alert>
                    <Card style={{ width: "35rem" }}>
                        <Card.Body>
                            <Card.Title>Login</Card.Title>
                            <Card.Subtitle>Welcome to Sports Matcher!</Card.Subtitle>
                            <Form onSubmit={this.registerUser}>
                                <Form.Group className="mb-3" controlId="firstName">
                                    <Form.Label>First name</Form.Label>
                                    <Form.Control type="text" placeholder="Ex. John" onChange={this.setUserState} required />
                                </Form.Group>
                                <Form.Group className="mb-3" controlId="lastName">
                                    <Form.Label>Last name</Form.Label>
                                    <Form.Control type="text" placeholder="Ex. Smith" onChange={this.setUserState} required />
                                </Form.Group>
                                <Form.Group className="mb-3" controlId="email">
                                    <Form.Label>E-mail</Form.Label>
                                    <Form.Control type="email" placeholder="Ex. youremail@mail.com" onChange={this.setUserState} required />
                                </Form.Group>
                                <Form.Group className="mb-3" controlId="phone">
                                    <Form.Label>Phone number</Form.Label>
                                    <Form.Control type="text" placeholder="Ex. (123) 456-7890" onChange={this.setUserState} />
                                </Form.Group>
                                <Form.Group className="mb-3" controlId="password">
                                    <Form.Label>Password</Form.Label>
                                    <Form.Control type="password" placeholder="Enter password" onChange={this.setUserState} required />
                                </Form.Group>
                                <Button variant="primary" type="submit">
                                    Register!
                                </Button>
                            </Form>
                        </Card.Body>
                    </Card>
                </Container>
            </div >
        );
    }
}
