import { FormEvent, useState } from "react"
import { Failure } from "../app/Failure.ts"
import "../style/form.css"
import { Link, useLocation, useNavigate } from "react-router-dom"
import { useAppFetcher } from "../App.tsx"
import { Authentication } from "../app/Fetcher.ts"

export interface LoginAppProps {
    onSuccess: (auth: Authentication) => void
}

export default function LoginApp({ onSuccess }: LoginAppProps) {
    const [errors, setErrors] = useState<Failure[]>([])

    const fetcher = useAppFetcher()
    const navigate = useNavigate()
    const location = useLocation()

    async function handleSubmit(e: FormEvent) {
        e.preventDefault()

        const { email, password } = Object.fromEntries(
            new FormData(e.target as HTMLFormElement),
        )

        const response = await fetcher.fetchAPI(
            "auth/token",
            { email, password },
            "POST",
        )

        if (response.ok) {
            const { token, expirationDate } = await response.json()
            const auth = { token, expirationDate: new Date(expirationDate) }
            onSuccess(auth)
            navigate(location.state?.from || "/")
            return
        }

        // if unauthorized :
        if (response.status === 401) {
            setErrors([
                {
                    type: "Non autorisé",
                    messages: [
                        "L'adresse email ou le mot de passe sont invalides.",
                    ],
                },
            ])
            return
        }

        try {
            const failures = await response.json()
            setErrors(
                Object.entries<string[]>(failures).map(([type, messages]) => ({
                    type,
                    messages,
                })),
            )
        } catch (e) {
            setErrors([
                {
                    type: "internal error",
                    messages: ["an internal error occurred."],
                },
            ])
        }
    }

    return (
        <div className="container">
            <center>
                <h2>Se connecter</h2>
            </center>

            {errors.map(({ type, messages }) =>
                messages.map((message) => (
                    <p key={type} style={{ color: "red" }}>
                        {type} : {message}
                    </p>
                )),
            )}

            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <label htmlFor="email">Email :</label>
                    <input
                        className="text-input"
                        type="text"
                        id="email"
                        name="email"
                        required
                    />

                    <label htmlFor="password">Mot de passe :</label>
                    <input
                        className="password-input"
                        type="password"
                        id="password"
                        name="password"
                        required
                    />

                    <Link to={"/register"} className="inscr">
                        Vous n'avez pas de compte ?
                    </Link>
                    <br />
                    <br />
                    <div id="buttons">
                        <input
                            className="button"
                            type="submit"
                            value="Se connecter"
                        />
                    </div>
                </div>
            </form>
        </div>
    )
}
