import * as React from 'react';
import {useState} from 'react';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import {paths} from "../../path";
import TextField from "@mui/material/TextField";
import TelegramIcon from '@mui/icons-material/Telegram';
import IconButton from "@mui/material/IconButton";
import Button from "@mui/material/Button";
import CircularProgress from "@mui/material/CircularProgress";
import Box from "@mui/material/Box";
import {red} from "@mui/material/colors";
import {useAuth} from "../../hooks/useAuth";
import {authClient} from "../../lib/clients/AuthClient";

const emptyRequest = {
    byLogin: true,
    code: "",
    login: "",
    password: ""
}

export function SignInForm() {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [request, setRequest] = useState(emptyRequest);
    const [pass, setPass] = useState(true)
    const {checkSession} = useAuth();

    const buttonSx = {
        minWidth: "300px",
        ...(error && {
            bgcolor: red[500],
            '&:hover': {
                bgcolor: red[700],
            },
        }),
    };
    const handleButtonClick = async () => {
        await authClient.login(request, setLoading, setError, checkSession)
    }

    const renderByCode = () => {
        return (
            <Stack direction='row' mt={1}>
                <IconButton href={paths.auth.bot} target="_blank" color='primary'>
                    <TelegramIcon/>
                </IconButton>

                <TextField value={request.code}
                           onChange={(e) => setRequest((prevState) => ({
                               ...prevState,
                               code: e.target.value
                           }))}
                           sx={{minWidth: 300}} id="outlined-basic" label="Код подтверждения"
                           variant="outlined"/>
            </Stack>
        )
    }
    const renderByLogin = () => {
        return (
            <Stack mt={1} spacing={2}>
                <TextField value={request.login}
                           onChange={(e) => setRequest(prevState => ({
                               ...prevState,
                               login: e.target.value
                           }))}
                           sx={{minWidth: 300}} id="loginField" label="Логин"
                           variant="outlined"/>
                <TextField value={request.password}
                           onChange={(e) => setRequest((prevState) => ({
                               ...prevState,
                               password: e.target.value
                           }))}
                           sx={{minWidth: 300}} id="passwordField" label="Пароль" type="password"
                           autoComplete="current-password" variant="outlined"/>
            </Stack>
        )
    }

    return (
        <Stack spacing={4} sx={{marginBottom: '85%', marginTop: '45%'}}>
            <Stack spacing={1}>
                <Typography variant="h4">Авторизация</Typography>
                <Typography variant='body1' component="a" href='#'
                            onClick={() => {
                                setRequest((prevState) => ({
                                    ...prevState,
                                    byLogin: !pass
                                }))
                                setPass(!pass)
                            }}>
                    {pass ? "Вход по телеграмм-коду" : "Вход по логину и паролю"}
                </Typography>
                <Typography color="text.secondary" variant="body2">
                    {pass ? "Введите логин и пароль"
                        : "Для входа нужно всего лишь сказать об этом моему Telegram-боту, перейди по ссылке и набери \n/start"}
                </Typography>
                {pass ? renderByLogin() : renderByCode()}
                <Box sx={{display: 'flex', alignItems: 'center', ml: '40px', mt: 1}}>
                    <Stack>
                        {error && (
                            <Typography mb={1} color={'error'}>{error}</Typography>
                        )}
                        <Button
                            variant="contained"
                            sx={buttonSx}
                            disabled={loading}
                            onClick={handleButtonClick}
                        >
                            {loading ? (
                                <CircularProgress
                                    size={25}
                                />
                            ) : "Войти"}
                        </Button>
                    </Stack>
                </Box>
            </Stack>
        </Stack>
    );
}
