"use client";

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

export default function LoginPage() {
  const router = useRouter()
  const params = useSearchParams().get("redirect_to");

  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)
        } else {
          if (params) {
            router.push(params);
          } else {
            router.push('/admin/home')
          }
        }
        return result
      } catch (error: unknown) {
        if (error instanceof Error && error.message.includes("Network Error")) {
          console.error("Problème de connexion au serveur");
        }
        console.error("Autre = ", error);
      }


    },
    onError: (error: Error) => {
      console.error(error.message)
    },
  })

  return (
    <div className="d-flex flex-column bg-bluegray h-100 align-items-center">
      <div className="login-main d-flex justify-content-center align-items-center position-relative">
        <Form
          title="Connexion"
          formClassName="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={<div className="d-flex justify-content-center w-100"> <button disabled={mutation.isPending} type="submit" className={`${mutation.isPending ? "btn-auth-loading" : "btn-auth"} cta  modal-cta`}>{mutation.isPending ? "Chargement..." : "Connexion"}</button></div>}
        />
      </div>
      <div className="version">
        <p className="fw-bold" >Version 0.0.1</p>
      </div>

    </div>
  )
}