import { store } from '../redux';
import { useState } from "react";
import { useHistory, useParams, useLocation } from "react-router-dom";
import { actionFullLogin } from "../redux/action";
import { ExampleModal } from './modal';

import { Paper, Box, Typography, Button, Stack, OutlinedInput, IconButton, InputLabel, InputAdornment, FormControl, TextField } from "@mui/material";

import { Visibility, VisibilityOff } from '@mui/icons-material';


// поля ввода и кнопки
function LoginForm() {
    const history = useHistory();

    // отслеживаем введение данных в полях логин/пароль
    const [data, setData] = useState({ login: '', pass: '' })

    // включаем,выклюаем отображение пароля
    const [showPassword, setShowPassword] = useState(false);
    const handleClickShowPassword = () => setShowPassword((show) => !show);
    const handleMouseDownPassword = (event) => {
        event.preventDefault();
    };

    async function fullLogin() {
        const answer = await store.dispatch(actionFullLogin(data.login, data.pass))

        console.log('answer: ', answer)
        if (answer == null) {
            console.log('nul')
            return (
                <ExampleModal />
            )
        }

        if (store.getState()?.auth?.token) {
            history.push('/')
        }
    }

    return (
        <Box sx={{ width: '100%' }}>
            <form>
                <Stack spacing={2}>
                    <TextField
                        fullWidth
                        variant='outlined'
                        id='login'
                        label='Логин'
                        size='normal'
                        value={data.login}
                        onChange={e => setData({ ...data, login: e.target.value })}
                    />

                    <FormControl variant="outlined">
                        <InputLabel htmlFor="outlined-adornment-password">Пароль</InputLabel>
                        <OutlinedInput
                            fullWidth
                            id="password"
                            label="Пароль"
                            size="normal"
                            type={showPassword ? 'text' : 'password'}
                            value={data.pass}
                            onChange={e => setData({ ...data, pass: e.target.value })}

                            endAdornment={
                                <InputAdornment position="end">
                                    <IconButton
                                        aria-label="visibility"
                                        onClick={handleClickShowPassword}
                                        onMouseDown={handleMouseDownPassword}
                                        edge="end"
                                    >
                                        {showPassword ? <VisibilityOff /> : <Visibility />}
                                    </IconButton>
                                </InputAdornment>
                            }
                        />
                    </FormControl>

                    <Button
                        size="large"
                        variant="contained"
                        disabled={((data.login == '') || (data.pass == '')) || false}
                        onClick={fullLogin}
                    >
                        Войти
                    </Button>
                </Stack>
            </form>
        </Box>
    )
}


function RegistrationLink() {
    const history = useHistory()

    function goToRegistration() {
        history.push('/registration')
    }

    return (
        <Typography
            variant="subtitle1"
            sx={{
                display: 'grid',
                alignSelf: 'end',
                justifyContent: 'center',
                cursor: 'pointer'
            }}
            onClick={goToRegistration}
        >
            Зарегистрироваться
        </Typography>
    )
}


function AuthReg() {

    let location = useLocation();
    console.log('location: ', location.pathname)

    return (
        <Box sx={{
            display: 'grid',
            height: '80vh',
            justifyContent: 'center',
            alignItems: 'center'
        }}>

            <Paper elevation={3}
                sx={{
                    padding: '5px',
                    width: '400px',
                    height: '500px',
                    display: 'grid',
                    justifyContent: 'center',
                    alignItems: 'center'
                }}>
                <Typography
                    variant="h4"
                    noWrap
                    sx={{
                        display: 'grid',
                        fontFamily: 'monospace',
                        fontWeight: 700,
                        letterSpacing: '.3rem',
                        color: 'inherit',
                        textDecoration: 'none',
                        flexGrow: '1',
                        marginTop: '20px',
                        justifyContent: 'center'
                    }} >
                    Hipstagram
                </Typography>

                <Box
                    sx={{
                        display: 'grid',
                        alignSelf: 'start'
                    }}>
                    <LoginForm />
                </Box>

                {(location.pathname === '/') && <RegistrationLink />}
            </Paper>
        </Box >
    )
}




function Registration2() {
    let location = useLocation();
    console.log('location: ', location.pathname)


    return (
        <div> тут будет регистрация, которая из авторизации</div>
    )
}






// function AuthReg() {

//     let location = useLocation();
//     console.log('location: ', location.pathname)


//     return (
//         <>
//             {(location.pathname === '/') ? <Authorization /> : <Registration2 />}
//         </>
//     )

// }
function Authorization() {
    return (
        <></>
    )
}


export { Authorization, Registration2, AuthReg }