'use client'

import * as React from 'react';
import { Box, Button, TextField, Typography, Stepper, Step, StepLabel, StepButton, ButtonGroup, Autocomplete, FormControlLabel, FormLabel, RadioGroup, Radio, Checkbox, FormGroup } from '@mui/material';

export default function RegisterPage() {

    const [name, setName] = React.useState('');
    const [email, setEmail] = React.useState('');
    const [password, setPassword] = React.useState('');

    const [emailValid, setEmailValid] = React.useState(false);
    const [passwordValid, setPasswordValid] = React.useState(false);
    const [nameValid, setNameValid] = React.useState(false);

    const register = () => {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        setNameValid(name === '');
        setPasswordValid(password === '');
        setEmailValid(!emailRegex.test(email));

        if (name === '' || password === '' || !emailRegex.test(email)) {
            return;
        }

        fetch('/api/register', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ username: name, email: email, password: password }),
        }).then((res) => {
            if (res.status === 200) {
                alert('Inscription réussie');
            } else {
                alert('Erreur lors de l\'inscription');
            }
        });
    }

    return (
        <Box>
            <Typography variant="h4">Inscription</Typography>
            <TextField label="Nom d'utilisateur" value={name} onChange={(e) => setName(e.target.value)} error={nameValid} fullWidth />
            <TextField label="Email" value={email} onChange={(e) => setEmail(e.target.value)} error={emailValid} fullWidth />
            <TextField label="Mot de passe" type="password" value={password} onChange={(e) => setPassword(e.target.value)} error={passwordValid} fullWidth />
            <Button onClick={register} margin='dense' fullWidth>S&apos;inscrire</Button>
        </Box>
    );
}