"use client";

import { useEffect, useState } from "react";
import { signIn, useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import Link from "next/link";
import { getDepartmentHomeRoute } from "@/lib/access-control";
import type { DepartmentKey } from "@/lib/types";

export default function LoginPage() {
  const router = useRouter();
  const { status, data: session } = useSession();
  const [email, setEmail] = useState("owner@casabenell.com");
  const [password, setPassword] = useState("");
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [verificationNotice, setVerificationNotice] = useState<string | null>(null);

  useEffect(() => {
    if (status === "authenticated") {
      const role = session?.user?.role;
      const department = (session?.user?.department as DepartmentKey | null | undefined) ?? null;
      const nextPath = role === "owner" ? "/dashboard" : getDepartmentHomeRoute(department);
      router.replace(nextPath);
    }
  }, [router, session?.user?.department, session?.user?.role, status]);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const verified = params.get("verified");
    const reset = params.get("reset");

    if (reset === "1") {
      setVerificationNotice("Contrasena actualizada. Ya puedes iniciar sesion.");
      return;
    }

    if (verified === "1") {
      setVerificationNotice("Correo verificado. Ya puedes iniciar sesión.");
      return;
    }

    if (verified === "0") {
      setVerificationNotice("No se pudo verificar el correo. Solicita un nuevo registro.");
      return;
    }

    setVerificationNotice(null);
  }, []);

  return (
    <main className="grid min-h-screen grid-cols-1 bg-benell-bg md:grid-cols-2">
      <section className="flex items-center justify-center p-6 md:p-12">
        <div className="w-full max-w-md">
          <Image
            src="/brand/logo.webp"
            alt="Casa Benell"
            width={110}
            height={76}
            className="h-20 w-auto rounded-lg border border-benell-stroke object-contain object-center"
            priority
          />
          <h1 className="text-display mt-8 text-benell-text">
            Bienvenido
          </h1>
          <div className="mt-7 rounded-benell border border-benell-stroke bg-benell-surface p-5 shadow-benell md:p-7">
            <form
              onSubmit={async (event) => {
                event.preventDefault();
                setErrorMessage(null);
                setIsSubmitting(true);

                const result = await signIn("credentials", {
                  redirect: false,
                  email,
                  password,
                });

                setIsSubmitting(false);

                if (result?.error) {
                  setErrorMessage("Credenciales inválidas, cuenta inactiva o correo no verificado.");
                  return;
                }
              }}
              className="space-y-6"
            >
              <label className="block space-y-1.5">
                <span className="text-label font-semibold">Correo electrónico</span>
                <input
                  type="email"
                  value={email}
                  onChange={(event) => setEmail(event.target.value)}
                  className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
                  required
                />
              </label>

              <label className="block space-y-1.5">
                <span className="text-label font-semibold">Contraseña</span>
                <input
                  type="password"
                  value={password}
                  onChange={(event) => setPassword(event.target.value)}
                  className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
                  required
                />
              </label>

              {errorMessage ? <p className="text-label text-benell-red">{errorMessage}</p> : null}
              {verificationNotice ? <p className="text-label text-benell-green">{verificationNotice}</p> : null}

              <button
                type="submit"
                disabled={isSubmitting}
                className="text-body w-full rounded-pill bg-benell-brown py-3 font-semibold text-white outline-none transition hover:bg-black focus-visible:ring-2 focus-visible:ring-benell-brown focus-visible:ring-offset-2"
              >
                {isSubmitting ? "Ingresando..." : "Entrar"}
              </button>
            </form>
            <Link href="/forgot-password" className="text-label mt-3 inline-flex text-benell-text-soft hover:underline">
              Olvidé mi contraseña
            </Link>
            <p className="text-label mt-3 text-benell-text-soft">
              El acceso es por invitación. Revisa tu correo para activar tu cuenta.
            </p>
          </div>
        </div>
      </section>
      <section className="relative hidden overflow-hidden bg-[#f2ece0] md:block">
        <Image
          src="/brand/mascot.png"
          alt="Mascota Casa Benell"
          width={500}
          height={500}
          className="absolute bottom-8 right-8 h-72 w-72 rounded-benell border border-benell-stroke object-contain object-bottom"
        />
      </section>
    </main>
  );
}
