/**
 * @file Login.js
 * @author Radim Buráň (xburan03@stud.fit.vutbr.cz)
 */

import React, {useState} from 'react'
import {useLocation, useNavigate} from "react-router-dom";
import {Button, Grid, Paper, TextField, Typography} from "@mui/material";
import {useAuth} from "../../services/AuthMiddleware";

const Login = () => {
    const [email, setEmail] = useState();
    const [password, setPassword] = useState();
    const [msg, setMsg] = useState('');
    const navigate = useNavigate();
    const auth = useAuth();
    const from = useLocation().state?.from?.pathname || "/";

    const loginUser = async (e) => {
        e.preventDefault();
        try {
            auth.login({
                "password": password,
                "email": email
            }, () => {
                navigate(from);
            }, () => {
                setMsg("Špatné údaje");
            });
        }
        catch (e) {
            setMsg(e.response.data.error);
        }
    }

    return (
        <div className={"Center"}>
            <Paper elevation={5} sx={{ padding: 2, maxWidth: "300px" }}>
                <p>{msg}</p>
                <form onSubmit={loginUser}>
                    <Grid container rowSpacing="10" columns={{xs: 2}} justifyContent="center" alignItems="center" alignContent="center" textAlign="center">
                        <Grid item xs={2}>
                            <Typography variant={"h4"} textAlign="center">Přihlášení</Typography>
                        </Grid>
                        <Grid item xs={2}>
                            <TextField
                                id="email"
                                label="Email"
                                type="email"
                                onChange={(e) => setEmail(e.target.value)}
                                fullWidth
                            />
                        </Grid>
                        <Grid item xs={2}>
                            <TextField
                                id="password"
                                label="Heslo"
                                type="password"
                                onChange={(e) => setPassword(e.target.value)}
                                fullWidth
                            />
                        </Grid>


                        <Grid item xs={1}>
                            <Button onClick={() => navigate("/register")}>Nový účet</Button>
                        </Grid>

                        <Grid item xs={1}>
                            <Button type="submit" variant="contained">Přihlásit se</Button>
                        </Grid>
                    </Grid>
                </form>
            </Paper>
        </div>
    );

}

export default Login
