import React, {FormEvent, useState} from "react"
import Field from "../../components/Field"
import axios from "axios"
import {useNavigate} from "react-router-dom"
import Card from "../../components/Card"

const Register = () => {

    const navigate = useNavigate()
    const [name, setName] = useState('')
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')

    const handleSubmit = async (event: FormEvent) => {
        event.preventDefault()
        try {
            await axios.get('/sanctum/csrf-cookie')
            await axios.post('/api/register', {name, email, password})
            navigate('/')
        } catch (error) {
            console.error(error)
        }
    }

    return <div>
        <Card className="mx-auto mt-10 w-96 overflow-hidden p-2">
            <form onSubmit={handleSubmit}>
                <h1 className="-mx-2 -mt-1 mb-2 bg-blue-500 px-2 py-1 text-center text-lg font-bold">
                    S&apos;inscrire
                </h1>

                <Field placeholder="Nom"
                       name="name"
                       value={name}
                       onChange={event => setName(event.target.value)}
                       autoFocus>Nom</Field>
                <Field type="email"
                       name="email"
                       placeholder="Email"
                       value={email}
                       onChange={event => setEmail(event.target.value)}
                       autoFocus>Email</Field>
                <Field type="password"
                       name="password"
                       placeholder="******"
                       value={password}
                       onChange={event => setPassword(event.target.value)}
                       autoFocus>Mot de passe</Field>
                <button type="submit" className="btn-primary mt-5 block w-full text-lg">Valider</button>
            </form>
        </Card>
    </div>
}

export default Register
