"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

import { AuthAPI } from "@/apis/AuthAPI";
import { useAuth } from "@/hooks/useAuth";

export default function LoginPage(): React.ReactElement {
  const router = useRouter();
  const { isAuthenticated, isVerifying } = useAuth();
  const [userName, setUserName] = useState("");
  const [rut] = useState("76062909-K");
  const [password, setPassword] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");

  useEffect(() => {
    if (!isVerifying && isAuthenticated) {
      router.replace("/main/home");
    }
  }, [isAuthenticated, isVerifying, router]);

  const handleLogin = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setErrorMessage("");

    if (!userName.trim() || !password.trim()) {
      setErrorMessage("Usuario y contraseña son obligatorios.");
      return;
    }

    try {
      setIsSubmitting(true);
      const response = await AuthAPI.login({
        user_name: userName.trim(),
        rut: rut.trim(),
        password,
      });

      if (!response?.status) {
        setErrorMessage(response?.data?.message || "No se pudo iniciar sesion.");
        return;
      }

      globalThis.window.location.assign("/main/home");
      return;
    } catch (error) {
      const apiMessage =
        (error as { response?: { data?: { data?: { message?: string }; message?: string } } })?.response
          ?.data?.data?.message ??
        (error as { response?: { data?: { message?: string } } })?.response?.data?.message;
      const message =
        apiMessage ||
        (error instanceof Error ? error.message : "No se pudo iniciar el flujo de autenticacion.");
      setErrorMessage(message);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <main className="min-h-screen flex items-center justify-center bg-slate-100 p-6">
      <div className="w-full max-w-md">

        {/* Card */}
        <div className="rounded-2xl overflow-hidden shadow-2xl shadow-indigo-200/60 border border-white/60">

          {/* Header con gradiente oscuro */}
          <div className="flex flex-col items-center gap-4 px-8 py-10" style={{ backgroundColor: "#1a2e6e" }}>
            <div className="w-24 h-24 rounded-2xl bg-white/10 backdrop-blur-sm border border-white/20 flex items-center justify-center shadow-lg">
              <img
                src="/images/logo_perfume.png"
                alt="Logo Parfums D' Parfums"
                className="w-16 h-16 object-contain drop-shadow-md"
              />
            </div>
            <div className="text-center">
              <h1 className="text-2xl font-bold text-white tracking-wide">
                Parfums D&apos; Parfums
              </h1>
              <p className="text-sm text-indigo-200 mt-1 tracking-wider uppercase">
                La esencia de la elegancia
              </p>
            </div>
          </div>

          {/* Formulario */}
          <form
            onSubmit={handleLogin}
            className="bg-white px-8 py-8 space-y-5"
          >
            <div className="space-y-1">
              <h2 className="text-lg font-semibold text-slate-800">Iniciar sesión</h2>
              <p className="text-sm text-slate-500">Ingresa con tus credenciales para continuar.</p>
            </div>

            <div className="space-y-3">
              <input
                type="text"
                value={userName}
                onChange={(e) => setUserName(e.target.value)}
                placeholder="Usuario"
                className="w-full rounded-lg border border-gray-200 bg-slate-50 px-4 py-2.5 text-sm outline-none transition focus:border-blue-400 focus:ring-2 focus:ring-blue-100 focus:bg-white"
              />
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="Contraseña"
                className="w-full rounded-lg border border-gray-200 bg-slate-50 px-4 py-2.5 text-sm outline-none transition focus:border-blue-400 focus:ring-2 focus:ring-blue-100 focus:bg-white"
              />
            </div>

            {errorMessage ? (
              <p className="text-sm text-red-600 bg-red-50 border border-red-100 rounded-lg px-3 py-2">
                {errorMessage}
              </p>
            ) : null}

            <button
              type="submit"
              disabled={isSubmitting || isVerifying}
              className="w-full rounded-lg py-2.5 text-sm font-semibold text-white transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
              style={{ backgroundColor: "#1a2e6e" }}
              onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = "#152459"; }}
              onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = "#1a2e6e"; }}
            >
              {isSubmitting ? "Ingresando..." : "Ingresar"}
            </button>
          </form>
        </div>

        <p className="text-center text-xs text-slate-400 mt-5">
          © {new Date().getFullYear()} Parfums D&apos; Parfums · Todos los derechos reservados
        </p>
      </div>
    </main>
  );
}
