import React, { useState, useContext, useEffect } from 'react'
import axios from 'axios';
import { useNavigate } from "react-router-dom";
import { AuthContext } from "../helpers/AuthContext";
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import CssBaseline from '@mui/material/CssBaseline';
import TextField from '@mui/material/TextField';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import '../App.css'

export default function Login() {
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const [error, setError] = useState('');
    const { setAuthState } = useContext(AuthContext)
    let navigate = useNavigate();

    useEffect(() => {
        window.scrollTo(0, 0)
    }, [])

    const login = () => {
        let data = { username: username, password: password };
        axios.post(`/api/auth/signin`, data).then((response) => {
            localStorage.setItem("accessToken", response.data.accessToken);
            response.data.roles = response.data.roles.map(role => {
                return role.replace('ROLE_', '');
            });
            delete response.data.accessToken
            delete response.data.tokenType
            setAuthState({
                ...response.data,
                loggedIn: true
            });
            navigate(response.data.roles.includes("ADMIN") ? "/admin" : "/map");
        }).catch((error) => {
            setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");
        });
    };

    const theme = createTheme();

    return (
        <div >
            <ThemeProvider theme={theme}>
                <Container sx={{ minHeight: "100vh" }} component="main" maxWidth="xs">
                    <CssBaseline />
                    <main className="w-100 bg-white rounded-3 shadow-sm">
                        <Box
                            sx={{
                                p: 5,
                                marginTop: 8,
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                            }}
                            className='contentBox rounded-3'
                        >
                            <Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
                                <LockOutlinedIcon />
                            </Avatar>
                            <Typography component="h1" variant="h5">
                                Sign in
                            </Typography>
                            <Box noValidate sx={{ mt: 1 }}>
                                <TextField
                                    className="bg-light"
                                    margin="normal"
                                    required
                                    fullWidth
                                    id="username"
                                    label="Username"
                                    name="username"
                                    autoComplete="username"
                                    autoFocus
                                    onChange={(event) => {
                                        setUsername(event.target.value);
                                    }}
                                />
                                <TextField
                                    className="bg-light"
                                    margin="normal"
                                    required
                                    fullWidth
                                    name="password"
                                    label="Password"
                                    type="password"
                                    id="password"
                                    autoComplete="current-password"
                                    onChange={(event) => {
                                        setPassword(event.target.value);
                                    }}
                                />
                                <span className="text-danger">{error}</span>
                                <div className='d-flex justify-content-center'>
                                    <Button
                                        className='w-75'
                                        onClick={login}
                                        variant="contained"
                                        sx={{ mt: 3, mb: 2, bgcolor: "#EEB2A5" }}
                                    >
                                        Sign In
                                    </Button>
                                </div>

                                <Grid
                                    container sx={{
                                        display: 'flex',
                                        flexDirection: 'column',
                                        alignItems: 'center',
                                    }}>
                                    <Grid item>
                                        <Button
                                            size="small"
                                            onClick={
                                                () => {
                                                    navigate("/registration")
                                                }
                                            }
                                        >
                                            Don't have an account? Sign Up
                                        </Button>
                                    </Grid>
                                </Grid>
                            </Box>
                        </Box>
                    </main>
                </Container>
            </ThemeProvider>
        </div>
    )
}