import React, {FormEvent, useState} from "react"
import Field from "../../components/Field"
import useAxiosTools from "../../hooks/AxiosTools"

const ForgotPassword = () => {

    const [email, setEmail] = useState('')
    const [message, setMessage] = useState(false)
    const {errorCatch, errorLabel, cleanErrors, axiosGet, axiosPost} = useAxiosTools()

    const handleSubmit = async (event: FormEvent) => {
        event.preventDefault()
        try {
            cleanErrors()
            await axiosGet('/sanctum/csrf-cookie')
            await axiosPost('/api/forgot', {email})
            setMessage(true)
        } catch (error) {
            errorCatch(error)
        }
    }

    return <div>
        <form onSubmit={handleSubmit} className="mx-auto mt-10 w-96 border p-3 shadow">
            <h1 className="text-center">Mot de passe oublié</h1>

            {message && <p className="bg-green-600">Un email vous a été envoyé pour modifier le mot de passe.</p>}

            {errorLabel()}

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

export default ForgotPassword
