import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Checkbox from '@mui/material/Checkbox';
import CssBaseline from '@mui/material/CssBaseline';
import FormControlLabel from '@mui/material/FormControlLabel';
import Divider from '@mui/material/Divider';
import FormLabel from '@mui/material/FormLabel';
import FormControl from '@mui/material/FormControl';
import Link from '@mui/material/Link';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import Stack from '@mui/material/Stack';
import { useTheme } from '@mui/material/styles';
import GroupAddIcon from '@mui/icons-material/GroupAdd';
import ForgotPassword from './ForgotPassword';
import Card from './Card';

const SignIn = () => {
    const [email, setEmail] = React.useState('');
    const [emailError, setEmailError] = React.useState(false);
    const [emailErrorMessage, setEmailErrorMessage] = React.useState('');
    const [group, setGroup] = React.useState('');
    const [groupError, setGroupError] = React.useState(false);
    const [groupErrorMessage, setGroupErrorMessage] = React.useState('');
    const [open, setOpen] = React.useState(false);

    const theme = useTheme();

    const handleClickOpen = () => {
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
    };

    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        if (emailError || groupError) {
            event.preventDefault();
            return;
        }

        console.log({
            email: email,
            groupcode: group,
        });
    };

    const validateEmail = (): boolean => {
        let isValid = true;
        if (email !== '' && !/\S+@\S+\.\S+/.test(email)) {
            setEmailError(true);
            setEmailErrorMessage('Bitte gib eine gültige E-Mail Adresse ein.');
            isValid = false;
        } else {
            setEmailError(false);
            setEmailErrorMessage('');
        }
        return isValid;
    };

    const validateGroup = (): boolean => {
        let isValid = true;
        if (group !== '' && !/\S+@\S+\.\S+/.test(email)) {
            setEmailError(true);
            setEmailErrorMessage('Bitte gib eine gültige E-Mail Adresse ein.');
            isValid = false;
        } else {
            setEmailError(false);
            setEmailErrorMessage('');
        }
        return isValid;
    };

    const validateInputs = () => {
        validateEmail();
        validateGroup();
    };

    return (
        <div style={{
            backgroundImage: 'radial-gradient(at 50% 50%, hsla(210, 100%, 16%, 0.5), hsl(220, 30%, 5%))',
            backgroundRepeat: 'no-repeat',
        }}>
            <CssBaseline enableColorScheme />
            <Stack direction="column" justifyContent="space-between"
                sx={{
                    height: 'calc((1 - var(--template-frame-height, 0)) * 100dvh)',
                    minHeight: '100%',
                    padding: theme.spacing(2),
                    [theme.breakpoints.up('sm')]: {
                        padding: theme.spacing(4),
                    },
                }}
            >
                <Card variant="outlined">
                    <Typography
                        component="h1"
                        variant="h4"
                        sx={{ width: '100%', fontSize: 'clamp(2rem, 10vw, 2.15rem)' }}
                    >
                        {'Gruppe beitreten'}
                    </Typography>

                    <Box
                        component="form"
                        onSubmit={handleSubmit}
                        noValidate
                        sx={{
                            display: 'flex',
                            flexDirection: 'column',
                            width: '100%',
                            gap: 2,
                        }}
                    >
                        <FormControl>
                            <FormLabel htmlFor="email">E-Mail</FormLabel>

                            <TextField
                                error={emailError}
                                helperText={emailErrorMessage}
                                id="email"
                                type="email"
                                name="email"
                                placeholder="ren@tier.de"
                                autoComplete="email"
                                autoFocus
                                required
                                fullWidth
                                variant="outlined"
                                onBlur={validateEmail}
                                onChange={event => setEmail(event.target.value)}
                                color={emailError ? 'error' : 'primary'} />
                        </FormControl>
                        <FormControl>
                            <FormLabel htmlFor="password">{'Gruppencode'}</FormLabel>
                            <TextField
                                error={groupError}
                                helperText={groupErrorMessage}
                                name="groupcode"
                                placeholder="Gruppe123"
                                type="text"
                                id="groupcode"
                                autoComplete="current-groupcode"
                                required
                                fullWidth
                                variant="outlined"
                                onBlur={validateGroup}
                                onChange={event => setGroup(event.target.value)}
                                color={groupError ? 'error' : 'primary'} />
                        </FormControl>

                        <FormControlLabel
                            control={<Checkbox value="remember" color="primary" />}
                            label="Anmeldedaten speichern" />

                        <ForgotPassword open={open} handleClose={handleClose} />

                        <Button
                            type="submit"
                            fullWidth
                            variant="contained"
                            onClick={validateInputs}
                        >
                            {'Beitreten'}
                        </Button>

                        <Link
                            component="button"
                            type="button"
                            onClick={handleClickOpen}
                            variant="body2"
                            sx={{ alignSelf: 'center' }}
                        >
                            {'Gruppencode vergessen?'}
                        </Link>
                    </Box>

                    <Divider>oder</Divider>

                    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                        <Button
                            fullWidth
                            variant="outlined"
                            onClick={() => alert('Sign in with Google')}
                            startIcon={<GroupAddIcon />}
                        >
                            {'Neue Gruppe erstellen'}
                        </Button>
                    </Box>
                </Card>
            </Stack>
        </div>
    );
};

export default SignIn;