'use client'

import { Box, Button, Typography, TextField } from '@mui/material';
import * as React from 'react';

export default function LoginPage() {

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

    const login = async () => {
        const res = await fetch('/api/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email, password }),
        });

        if (res.status === 200) {
            window.location.href = '/';
        } else if (res.status === 403) {
            alert('Compte désactivé');
        } else {
            alert('Identifiants incorrects');
        }
    }

    return (
        <Box sx={{margin: '20px'}}>
            <Typography variant='h5'>Connexion</Typography>
            <Box component='form'>
                <TextField id="email" label="Adresse e-mail" type="email" onChange={(e) => {setEmail(e.target.value)}} fullWidth /><br />
                <TextField id="password" label="Mot de passe" type="password" onChange={(e) => {setPassword(e.target.value)}} fullWidth />
                <Button variant='text' color='secondary'>Mot de passe oublié</Button>
                <Button color='primary' margin='dense' onClick={login} fullWidth>Se connecter</Button>
                <Button variant='text' color='default' onClick={() => {window.location.href = '/register'}} fullWidth>S&apos;inscrire</Button>
            </Box>
        </Box>
    );

}