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

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

function ProfilePage() {
    const [user, setUser] = useState("Nic");
    const [pwdMsg, setPwdMsg] = useState("");
    const [password, setPassword] = useState("");
    const [newPassword, setNewPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");

    const [emailMsg, setEmailMsg] = useState("");
    const [emailPassword, setEmailPassword] = useState("");
    const [email, setEmail] = useState("");
    const [newEmail, setNewEmail] = useState("");
    const [confirmEmail, setConfirmEmail] = useState("");

    const navigate = useNavigate();
    const auth = useAuth();

    useEffect(() => {
        axiosGet("/users/me").then((res) => {
            setUser(res.data);
        }).catch((e) => {
            console.error(e);
        });
    }, []);

    const ITEMS = [
        {key: "name", display: "Jméno:"},
        {key: "email", display: "Email:"},
        {key: "role", display: "Role:"},
    ];

    const changePassword = () => {
        axiosPost("/changePassword", {
            password: password,
            newPassword: newPassword,
            confirmPassword: confirmPassword
        })
        .then((res) => {
            auth.logout(() => navigate("/"));
        })
        .catch((e) => {
            setPwdMsg(e.response.data.error);
        });
    }

    const checkPassword = () => {
        if (confirmPassword?.length < 4) {
            return false;
        }
        return true;
    }

    const changeEmail = () => {
        axiosPost("/changeEmail", {
            password: emailPassword,
            email: email,
            newEmail: newEmail,
            confirmEmail: confirmEmail
        })
        .then((res) => {
            auth.logout(() => navigate("/"));
        })
        .catch((e) => {
            setEmailMsg(e.response.data.error);
        });
    }

    return (<Grid container columns={{xs: 1, sm: 2, md: 3}} spacing={{xs: 2, sm: 5, md: 10}}>
        <Grid item xs={1}>
            <Paper elevation={2} sx={{padding: 2}}>
                <Typography variant={"h6"} textAlign="center">Přihlášený uživatel</Typography>
                {ITEMS.map((entry) => (
                    <Grid container columns={{xs: 3}} key={entry.key}>
                        <Grid item xs={1}>
                            <Typography>{entry.display}</Typography>
                        </Grid>

                        <Grid item xs={2}>
                            <Typography>{user[entry.key]}</Typography>
                        </Grid>
                    </Grid>
                ))}
            </Paper>
        </Grid>


        <Grid item xs={1}>
            <Paper elevation={2} sx={{padding: 2}}>
                <Typography variant={"h6"} textAlign="center">Změnit heslo</Typography>
                <Typography>{pwdMsg}</Typography>

                <TextField id="pwd-current"
                           label="Aktuální heslo"
                           type="password"
                           fullWidth
                           onChange={(e) => setPassword(e.target.value)}
                           sx={{paddingBottom: 2}}
                />

                <TextField id="pwd-new"
                           label="Nové heslo"
                           type="password"
                           fullWidth
                           color={checkPassword() ? "primary" : "warning"}
                           onChange={(e) => setNewPassword(e.target.value)}
                           sx={{paddingBottom: 2}}
                />

                <TextField id="pwd-new-confirm"
                           label="Potvrdit nové heslo"
                           type="password"
                           fullWidth
                           helperText={newPassword === confirmPassword ? "" : "Hesla nejsou stejná!"}
                           color={newPassword === confirmPassword ? "primary" : "warning"}
                           onChange={(e) => setConfirmPassword(e.target.value)}
                           sx={{paddingBottom: 2}}
                />

                <Button variant={"contained"}
                        fullWidth
                        disabled={!checkPassword() || newPassword !== confirmPassword}
                        onClick={changePassword}
                >
                    Změnit heslo
                </Button>
            </Paper>
        </Grid>

        <Grid item xs={1}>
            <Paper elevation={2} sx={{padding: 2}}>
                <Typography variant={"h6"} textAlign="center">Změnit email</Typography>
                <Typography>{emailMsg}</Typography>

                <TextField id="pwd-email"
                           label="Aktuální heslo"
                           type="password"
                           fullWidth
                           onChange={(e) => setEmailPassword(e.target.value)}
                           sx={{paddingBottom: 2}}
                />

                <TextField id="email-current"
                           label="Aktuální email"
                           type="email"
                           fullWidth
                           onChange={(e) => setEmail(e.target.value)}
                           sx={{paddingBottom: 2}}
                />

                <TextField id="email-new"
                           label="Nový email"
                           type="email"
                           fullWidth
                           onChange={(e) => setNewEmail(e.target.value)}
                           sx={{paddingBottom: 2}}
                />

                <TextField id="email-new-confirm"
                           label="Potvrdit nový email"
                           type="email"
                           fullWidth
                           helperText={newEmail === confirmEmail ? "" : "Emaily nejsou stejné!"}
                           color={newEmail === confirmEmail ? "primary" : "warning"}
                           onChange={(e) => setConfirmEmail(e.target.value)}
                           sx={{paddingBottom: 2}}
                />

                <Button variant={"contained"}
                        fullWidth
                        onClick={changeEmail}
                >
                    Změnit email
                </Button>
            </Paper>
        </Grid>

    </Grid>);
}


export default ProfilePage