
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 Link from '@mui/material/Link';
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 { lightGreen } from '@mui/material/colors';
import { categoriesApi, useGetLoginMutation } from '../../store/categoriesApi';
import { useDispatch, useSelector } from 'react-redux';
import { setCredentials } from '../../store/authSlice';
import { Navigate, Link as RoterLink, useNavigate, useLocation } from 'react-router-dom';
import { Alert, Snackbar } from '@mui/material';
import { useState } from 'react';



function jwtDecode(token) {
    let result;
    try {
        let secondPartToken = token.split('.')[1];
        result = JSON.parse(atob(secondPartToken));
    } catch (e) {
    }

    return result;
}

const theme = createTheme();

export default function SignIn() {
    const navigate = useNavigate()
    const location = useLocation()
    const fromPage = location.state?.from?.pathname || '/'
    console.log(fromPage)

    const [open, setOpen] = useState(false);

    const handleClose = (event, reason) => {
        if (reason === 'clickaway') {
            return;
        }
        setOpen(false);
    };

    const userAuth = useSelector((state) => state.auth.user)
    const dispatch = useDispatch()

    const [loginQuery, { isLoading }] = useGetLoginMutation()

    const handleSubmit = async (event) => {
        event.preventDefault();
        const dataForm = new FormData(event.currentTarget);

        const { data } = await loginQuery({
            login: dataForm.get('email'),
            password: dataForm.get('password')
        })
        if (data) {
            const token = data.login
            const user = jwtDecode(token)

            if (user) {
                dispatch(setCredentials({ user, token }))
                console.log(user.sub.id)
                dispatch( categoriesApi.endpoints.getUserById.initiate(user.sub.id))
                navigate(fromPage, {replace: true})
            }
            else {
                setOpen(true)
            }
        }
    };

    return (
        <>
            {userAuth ? <Navigate replace to="/profile" /> :
                <>
                    <Snackbar
                        open={open}
                        autoHideDuration={2000}
                        onClose={handleClose}
                        message="Note archived"
                    >
                        <Alert severity="error">Вы ввели неправильный логин или пароль!</Alert>
                    </Snackbar>

                    <ThemeProvider theme={theme}>
                        <Container component="main" maxWidth="xs">
                            <CssBaseline />
                            <Box
                                sx={{
                                    marginTop: 3,
                                    display: 'flex',
                                    flexDirection: 'column',
                                    alignItems: 'center',
                                    marginBottom: 3,
                                }}
                            >
                                <Avatar sx={{ m: 1, bgcolor: lightGreen[800] }}>
                                    <LockOutlinedIcon />
                                </Avatar>
                                <Typography component="h1" variant="h5">
                                    Войти
                                </Typography>
                                <Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
                                    <TextField
                                        margin="normal"
                                        required
                                        fullWidth
                                        id="email"
                                        label="Email или имя профиля"
                                        name="email"
                                        autoComplete="email"
                                        autoFocus
                                    />
                                    <TextField
                                        margin="normal"
                                        required
                                        fullWidth
                                        name="password"
                                        label="Пароль"
                                        type="password"
                                        id="password"
                                        autoComplete="current-password"
                                    />
                                    <FormControlLabel
                                        control={<Checkbox value="remember" color="primary" />}
                                        label="Запомнить меня"
                                    />
                                    <Button
                                        type="submit"
                                        fullWidth
                                        variant="contained"
                                        sx={{ mt: 3, mb: 2 }}
                                    >
                                        Войти
                                    </Button>
                                    <Grid container>
                                        <Grid item xs>
                                            <Link href="#" variant="body2">
                                                Забыли пароль?
                                            </Link>
                                        </Grid>
                                        <Grid item>
                                            <Link to="/registration" variant="body2" component={RoterLink}>
                                                {"У Вас нет аккаунта? Зарегистрироваться"}
                                            </Link>
                                        </Grid>
                                    </Grid>
                                </Box>
                            </Box>
                        </Container>
                    </ThemeProvider>
                </>
            }
        </>
    );
}