import * as React from 'react';
import toast, { Toaster } from 'react-hot-toast';
import { useNavigate } from 'react-router-dom'
import jwt_decode from "jwt-decode";

import {
    Paper, Box, Grid, Typography,
    TextField, Button, Avatar,
    Backdrop, CircularProgress,
} from '@mui/material'

import { createTheme, ThemeProvider } from '@mui/material/styles';

import PersonIcon from '@mui/icons-material/Person';
// import { useNavigate } from 'react-router-dom'
import { Copyright } from '../Components/Footer.js'
// import { Link } from 'react-router-dom'
import useAuth from '../Auth/useAuth';

import { useFormik } from 'formik';
import * as Yup from 'yup';

import { Service } from '../Utils/HTTP.js'

const LoginSchema = Yup.object().shape({
    email: Yup
        .string()
        .email('El correo debe ser válido')
        .required('El correo o usuario es requerido'),
    password: Yup
        .string()
        .required('El campo contraseña es requerido')
        .min(5, 'La contraseña debe contener mínimo 5 caracteres')
})

const theme = createTheme();

export function LoginCs() {

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

    const [open, setOpen] = React.useState(false);
    const handleClose = () => false

    const formik = useFormik({
        initialValues: {
            email: '',
            password: '',
        },
        validationSchema: LoginSchema,
        onSubmit: async (values) => {

            let { email, password } = values
            setOpen(true)

            let request = new Service(`/user?user=${email}&password=${password}&typeusr=iscandidato`)
            request
                .post({})
                .then(response => {

                    console.log("Service Response :: ", response)
                    let { token, nombre, apelidos, empresa } = response;
                    toast.success(`Bienvenido ${nombre} ${apelidos}!!`)
                    token = token.replace("Bearer ", "")
                    console.log(token);

                    // let { exp } = jwt_decode(token);
                    let body_token = jwt_decode(token);
                    console.log("BODY TOKEN: ", body_token)
                    // let timestamp = exp * 1000;
                    // let restante = timestamp - Date.now();

                    // setTimeout(() => alert("Token Expirado"), restante)
                    auth.setProfile(empresa)
                    auth.setRole(body_token)

                    setTimeout(() => {
                        setOpen(false)
                        auth.login(token)
                    }, 2000)

                })
                .catch(err => {
                    setOpen(false)
                    toast.error("Ups! usuario o contraseña incorrectos")
                    console.log("ERROR ", err)
                })

        },
    });

    
    React.useEffect(() => {
        if(auth.isLogged()){
            return navigate('/user')
        }
    }, [auth,navigate])

    return (
        <ThemeProvider theme={theme}>
            <Grid container component="main" sx={{ height: '100vh' }}>
                <Grid item xs={12} sm={12} md={12} component={Paper} elevation={6} square>

                    <Box
                        sx={{
                            my: 8,
                            mx: 4,
                            marginTop:25,
                            display: 'flex',
                            flexDirection: 'column',
                            // alignItems:true?'flex-start': 'center',
                            alignItems:'center'
                        }}
                    >
                        <Avatar sx={{ m: 1, bgcolor: '#fd4b4b' }}>
                            <PersonIcon />
                        </Avatar>
                        <Typography component="h1" variant="h5">
                            Ingresar
                        </Typography>

                        <Box component="form" noValidate onSubmit={formik.handleSubmit} sx={{ mt: 1 }}>
                            <TextField
                                value={formik.values.email}
                                onChange={formik.handleChange}
                                error={formik.touched.email && Boolean(formik.errors.email)}
                                helperText={formik.touched.email && formik.errors.email}
                                margin="normal"
                                required
                                fullWidth
                                id="email"
                                name="email"
                                label="Correo Electrónico"
                                autoComplete="email"
                                autoFocus
                            />
                            <TextField
                                value={formik.values.password}
                                onChange={formik.handleChange}
                                error={formik.touched.password && Boolean(formik.errors.password)}
                                helperText={formik.touched.password && formik.errors.password}
                                margin="normal"
                                required
                                fullWidth
                                label="Contraseña"
                                name="password"
                                type="password"
                                id="password"
                                autoComplete="current-password"
                            />
                            <Button
                                id="login_btn_fn"
                                type="submit"
                                fullWidth
                                variant="contained"
                                sx={{ mt: 3, mb: 2, bgcolor: 'var(--main)' }}
                            >
                                Ingresar
                            </Button>
                            <Copyright sx={{ mt: 5 }} />
                        </Box>
                    </Box>
                </Grid>
            </Grid>
            <Toaster
                position="top-left"
                reverseOrder={false}
            />
            <Backdrop
                sx={{ color: '#fd4b4b', zIndex: (theme) => theme.zIndex.drawer + 1 }}
                open={open}
                onClick={handleClose}
            >
                <CircularProgress color="inherit" />
            </Backdrop>

        </ThemeProvider>

    );
}
