"use client";

import { useState, useEffect } from "react";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
import { User, Lock, Eye, EyeOff, FileText, Shield } from "lucide-react";

export default function LoginPage() {
  const router = useRouter();
  const [formData, setFormData] = useState({
    username: "",
    password: "",
  });
  const [loading, setLoading] = useState(false);
  const [checkingUsers, setCheckingUsers] = useState(true);
  const [error, setError] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [focusedField, setFocusedField] = useState<string | null>(null);

  useEffect(() => {
    const checkUsers = async () => {
      try {
        const response = await fetch("/api/auth/check-users");
        const data = await response.json();

        if (data.success && !data.hasUsers) {
          router.push("/initial-setup");
        } else {
          setCheckingUsers(false);
        }
      } catch (error) {
        console.error("Error al verificar usuarios:", error);
        setCheckingUsers(false);
      }
    };

    checkUsers();
  }, [router]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setLoading(true);

    try {
      const result = await signIn("credentials", {
        username: formData.username,
        password: formData.password,
        redirect: false,
      });

      if (result?.error) {
        setError("Usuario o contraseña incorrectos. Por favor, intenta de nuevo.");
        setLoading(false);
      } else if (result?.ok) {
        await new Promise((resolve) => setTimeout(resolve, 1000));
        window.location.href = "/dashboard";
      } else {
        setError("Error desconocido. Por favor, intenta de nuevo.");
        setLoading(false);
      }
    } catch (error) {
      console.error("💥 [LOGIN FORM] Error en catch:", error);
      setError("Error de conexión. Por favor, intenta nuevamente.");
      setLoading(false);
    }
  };

  if (checkingUsers) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background-subtle">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div>
          <p className="mt-4 text-text-muted">Verificando configuración...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
      <div className="max-w-md w-full">
        {/* Header */}
        <div className="text-center mb-10 animate-fade-in">
          <div className="inline-flex items-center justify-center w-20 h-20 bg-linear-to-br from-primary to-primary-active rounded-2xl mb-5 shadow-2xl shadow-primary/30">
            <FileText className="h-10 w-10 text-primary-foreground" />
          </div>
          <h1 className="text-3xl font-bold text-text mb-2">OCR Pro</h1>
          <p className="text-text-muted">
            Sistema de Digitalización de Documentos
          </p>
        </div>

        {/* Login Form Card */}
        <div className="bg-background/80 backdrop-blur-sm rounded-3xl p-8 shadow-xl shadow-black/5 animate-scale-in border border-border-subtle">
          <h2 className="text-2xl font-bold text-text mb-6 text-center">
            Iniciar Sesión
          </h2>

          <form onSubmit={handleSubmit} className="space-y-5">
            {error && (
              <div
                className="bg-destructive-background border border-destructive-border text-destructive-foreground px-4 py-3.5 rounded-xl text-sm flex items-start gap-3 animate-slide-down"
                role="alert"
              >
                <svg className="w-5 h-5 shrink-0 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                </svg>
                <span>{error}</span>
              </div>
            )}

            {/* Username Field */}
            <div>
              <label
                htmlFor="username"
                className="block text-sm font-medium text-text mb-2"
              >
                Usuario
              </label>
              <div className="relative">
                <div className={`absolute left-3.5 top-1/2 -translate-y-1/2 transition-colors ${
                  focusedField === 'username' ? 'text-primary' : 'text-text-subtle'
                }`}>
                  <User className="h-5 w-5" />
                </div>
                <input
                  id="username"
                  type="text"
                  value={formData.username}
                  onChange={(e) =>
                    setFormData({ ...formData, username: e.target.value })
                  }
                  onFocus={() => setFocusedField('username')}
                  onBlur={() => setFocusedField(null)}
                  className="w-full pl-11 pr-4 py-3.5 border border-border rounded-xl focus:ring-2 focus:ring-primary focus:border-primary bg-background text-text placeholder-text-subtle transition-all outline-none"
                  placeholder="Ingresa tu usuario"
                  required
                  autoComplete="username"
                  aria-required="true"
                />
              </div>
            </div>

            {/* Password Field */}
            <div>
              <label
                htmlFor="password"
                className="block text-sm font-medium text-text mb-2"
              >
                Contraseña
              </label>
              <div className="relative">
                <div className={`absolute left-3.5 top-1/2 -translate-y-1/2 transition-colors ${
                  focusedField === 'password' ? 'text-primary' : 'text-text-subtle'
                }`}>
                  <Lock className="h-5 w-5" />
                </div>
                <input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  value={formData.password}
                  onChange={(e) =>
                    setFormData({ ...formData, password: e.target.value })
                  }
                  onFocus={() => setFocusedField('password')}
                  onBlur={() => setFocusedField(null)}
                  className="w-full pl-11 pr-12 py-3.5 border border-border rounded-xl focus:ring-2 focus:ring-primary focus:border-primary bg-background text-text placeholder-text-subtle transition-all outline-none"
                  placeholder="••••••••"
                  required
                  autoComplete="current-password"
                  aria-required="true"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-text-subtle hover:text-text transition-colors p-1 outline-none focus:ring-2 focus:ring-primary rounded"
                  aria-label={showPassword ? "Ocultar contraseña" : "Mostrar contraseña"}
                >
                  {showPassword ? (
                    <EyeOff className="h-5 w-5" />
                  ) : (
                    <Eye className="h-5 w-5" />
                  )}
                </button>
              </div>
            </div>

            {/* Submit Button */}
            <button
              type="submit"
              disabled={loading}
              className="w-full py-3.5 px-4 bg-primary text-primary-foreground font-semibold rounded-xl hover:bg-primary-hover focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 shadow-lg hover:shadow-xl"
            >
              {loading ? (
                <div className="flex items-center justify-center gap-2">
                  <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-primary-foreground"></div>
                  Iniciando sesión...
                </div>
              ) : (
                "Ingresar"
              )}
            </button>
          </form>

          {/* Footer */}
          <div className="mt-6 pt-6">
            <p className="text-xs text-text-muted text-center flex items-center justify-center gap-1.5">
              <Shield className="h-4 w-4" />
              Sistema seguro de gestión documental
            </p>
          </div>
        </div>

        {/* Additional Info */}
        <p className="text-center text-xs text-text-subtle mt-6">
          © {new Date().getFullYear()} OCR Pro. Todos los derechos reservados.
        </p>
      </div>
    </div>
  );
}
