import React from "react";
import { Alert, Button, Card, Container, Form } from "react-bootstrap";
import { globalContext } from "../context";
import { apiClient } from "../utils/httpClients";
import { guard } from "../utils/routing";

export default class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            email: "",
            password: "",
            errorDisplayed: false,
        };

        this.attemptLogin = this.attemptLogin.bind(this);
    }

    static contextType = globalContext;

    async componentDidMount() {
        try {
            const getUserResponse = await apiClient.get("/user");
            guard(this.context.navigate, () => getUserResponse.status === 401, "/dashboard"); // If it's not 401, then we redirect to dashboard.
        } catch (error) {
            if (error.message !== "Request failed with status code 401") {
                throw error;
            }
        }
    }

    async attemptLogin(e) {
        e.preventDefault();
        const loginResponse = await apiClient.post("/user/login", {
            email: this.state.email,
            password: this.state.password,
        }, {
            validateStatus: function (status) {
                return status === 200 || status === 401 || status === 400;
            }
        });
        if (loginResponse.status === 200) {
            this.context.navigate("/dashboard", { replace: true });
        } else if (loginResponse.status === 401) {
            this.setState({ errorDisplayed: true });
        }
    }

    render() {
        let errorMsg = (
            <div></div>
        );
        if (this.state.errorDisplayed) {
            errorMsg = (
                < Alert variant="danger" onClose={() => this.setState({ errorDisplayed: false })} dismissible >
                    <Alert.Heading>Incorrect credentials</Alert.Heading>
                    <p>Double check your provided e-mail and password!</p>
                </Alert >
            );
        }

        return (
            <div className="d-flex justify-content-center align-items-center
            page-root">
                {errorMsg}
                <Container style={{ maxWidth: "35rem" }}>
                    <Card>
                        <Card.Body>
                            <Card.Title>Login</Card.Title>
                            <Card.Subtitle>Welcome back!</Card.Subtitle>
                            <Form onSubmit={this.attemptLogin}>
                                <Form.Group className="mb-3" controlId="loginEmail">
                                    <Form.Label>E-mail</Form.Label>
                                    <Form.Control type="email" placeholder="Ex. youremail@mail.com" onChange={(e) => {
                                        this.setState({ email: e.target.value });
                                    }} />
                                </Form.Group>
                                <Form.Group className="mb-3" controlId="loginPassword">
                                    <Form.Label>Password</Form.Label>
                                    <Form.Control type="password" placeholder="Enter password" onChange={(e) => {
                                        this.setState({ password: e.target.value });
                                    }} />
                                </Form.Group>
                                <Button variant="primary" type="submit">
                                    Submit
                                </Button>
                            </Form>
                        </Card.Body>
                    </Card>
                </Container>
            </div>
        );
    }
}