"use client";

import Form from "#/components/form/form"
import { loginSchema } from "#/schema/loginSchema"
import { useMutation } from "@tanstack/react-query"
import { signIn } from "next-auth/react"
import { useRouter } from "next/navigation";

export default function LoginPage() {
    const router = useRouter()

    const mutation = useMutation({
        mutationKey: ['login'],
        mutationFn: async (data: { email: string; password: string }) => {
            try {
                const result = await signIn("credentials", {
                    email: data.email,
                    password: data.password,
                    redirect: false,
                })
                
                if (result?.error) {
                    const errorMessage = result.error.includes("CredentialsSignin") 
                        ? "Email ou mot de passe incorrect" 
                        : result.error;
                    console.error(errorMessage)
                    throw new Error(result.error)
                }
                return result
            } catch (error: any) {
                if (error.message.includes("Network Error")) {
                    console.error("Problème de connexion au serveur");
                }
                console.error("Autre = ", error);
            }
            

        },
        onSuccess: () => {
            router.push('/admin/home')
        },
        onError: (error: Error) => {
            console.error(error.message)
        },
    })

    return(
        <div>
            <Form
                title="Connexion"
                className="bg-white p-10 shadow-2xl w-3/4 lg:w-lg"
                fields={[
                    {
                        label: "Email",
                        name: "email",
                        type: "email",
                        placeholder: "Entrer votre email"
                    },
                    {
                        label: "Password",
                        name: "password", 
                        type: "password",
                        placeholder: "Enter votre mot de passe",
                        showPasswordToggle: true
                    }
                ]}
                submit={mutation.mutate} 
                schema={loginSchema}
                child={<button type="submit" className="btn-auth">Connexion</button>}
             />
        </div>
    )
}