import PageLayout from "../../components/PageLayout";
import Field from "../../components/Field";
import React, {FormEvent, useState} from "react";
import {useNavigate, useParams} from "react-router-dom";
import useAuthUser from "../../hooks/AuthUser";
import axios from "axios";

const Reset = () => {

    let {token} = useParams()
    const navigate = useNavigate()
    const {setAuthUser} = useAuthUser()
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [samePassword, setSamePassword] = useState('')

    const handleSubmit = async (event: FormEvent) => {
        event.preventDefault()
        try {
            await axios.get('/sanctum/csrf-cookie')
            const res = await axios.post('/api/reset', {email, token, password, samePassword})
            setAuthUser(res.data.user)
            navigate('/connexion')
        } catch (e) {
            console.error(e)
        }
    }

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

            <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)}>Mot de passe</Field>
            <Field type="password"
                   name="same_password"
                   placeholder="******"
                   value={samePassword}
                   onChange={event => setSamePassword(event.target.value)}>Confirmation du mot de passe</Field>
            <button type="submit" className="mt-5 btn-primary w-full block text-lg">Valider</button>
        </form>
    </div>
}

export default Reset
