"use client";

import { useState, Suspense } from "react";
import { signIn } from "next-auth/react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { LogIn, Mail, Lock, ArrowRight, ShieldCheck, User } from "lucide-react";

function LoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get("callbackUrl") || null;
  const fromAdmin = searchParams.get("from") === "admin";

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");

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

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

    if (result?.error) {
      setError("Incorrect email or password. Please try again.");
      setIsLoading(false);
      return;
    }

    if (callbackUrl) {
      router.push(decodeURIComponent(callbackUrl));
    } else {
      const { getSession } = await import("next-auth/react");
      const session = await getSession();
      const role = (session?.user as any)?.role;
      router.push(role === "SUPER_ADMIN" || role === "ADMIN" ? "/admin" : "/dashboard");
    }
    router.refresh();
  };

  return (
    <div className="min-h-[100dvh] flex items-center justify-center p-6 relative overflow-hidden bg-[#030408] text-white font-sans">
      
      {/* ── Ambient Background Meshes ── */}
      <div className="absolute inset-0 pointer-events-none z-0">
        <div className="absolute top-[-10%] left-[-10%] w-[50%] h-[50%] bg-[#102d56]/20 rounded-full blur-[140px]" />
        <div className="absolute bottom-[-10%] right-[-10%] w-[50%] h-[50%] bg-[#dc2626]/15 rounded-full blur-[150px]" />
        <div className="absolute inset-0 opacity-[0.015]" style={{ backgroundImage: "linear-gradient(rgba(255,255,255,0.1) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,0.1) 1px,transparent 1px)", backgroundSize: "40px 40px" }} />
      </div>

      <motion.div 
        initial={{ opacity: 0, scale: 0.95, y: 20 }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
        transition={{ duration: 0.8, ease: [0.16, 1, 0.3, 1] }}
        className="w-full max-w-5xl z-10 flex flex-col md:flex-row rounded-[2rem] overflow-hidden shadow-[0_20px_50px_rgba(0,0,0,0.5)] border border-white/10 bg-[#0f111a]/60 backdrop-blur-3xl"
      >
        
        {/* Left Side (Branding / Visual) */}
        <div className="hidden md:flex flex-col justify-between w-1/2 p-12 relative overflow-hidden bg-gradient-to-br from-[#102d56]/30 to-transparent border-r border-white/5">
          <div className="absolute top-[-20%] right-[-20%] w-[80%] h-[80%] bg-[#dc2626]/10 rounded-full blur-[80px]" />
          
          <div className="relative z-10">
            <Link href="/" className="inline-flex items-center gap-3 group mb-12">
              <div className="w-12 h-12 bg-white/10 rounded-xl flex items-center justify-center border border-white/20 group-hover:bg-white/20 transition-colors">
                <img src="/logo-2.png" alt="Rima Logo" className="w-8 h-8 object-contain" />
              </div>
              <span className="font-bold text-xl tracking-wide group-hover:text-cyan-400 transition-colors">RIMA ACADEMY</span>
            </Link>
            
            <h2 className="text-4xl lg:text-5xl font-black mb-6 leading-[1.1] tracking-tight">
              {fromAdmin ? "System Access" : "Welcome back to your journey."}
            </h2>
            <p className="text-slate-400 text-lg leading-relaxed">
              {fromAdmin 
                ? "Authenticate securely to access the academy's management and operations dashboard." 
                : "Log in to access your active courses, join live sessions, and track your language fluency progress."}
            </p>
          </div>
          
          <div className="relative z-10 mt-12">
            <div className="p-6 bg-white/5 rounded-2xl border border-white/10 backdrop-blur-md">
              <div className="flex items-center gap-3 mb-3">
                <ShieldCheck className="w-5 h-5 text-green-400" />
                <span className="font-bold text-sm text-slate-300 uppercase tracking-widest">Secure Login</span>
              </div>
              <p className="text-sm text-slate-500 font-medium">Your connection is encrypted. If you forgot your password, please contact support.</p>
            </div>
          </div>
        </div>

        {/* Right Side (Form) */}
        <div className="w-full md:w-1/2 p-8 md:p-14 relative flex flex-col justify-center bg-[#030408]/40">
          
          <div className="md:hidden flex justify-center mb-10">
            <Link href="/">
              <img src="/logo-2.png" alt="RIMA Academy" className="h-14 w-auto" />
            </Link>
          </div>
          
          <div className="mb-10 text-center md:text-left">
            <h1 className="text-3xl font-black text-white mb-3">
              {fromAdmin ? "Admin Login" : "Sign In"}
            </h1>
            <p className="text-slate-400 text-sm font-medium">
              Enter your credentials to access your account.
            </p>
          </div>

          <form onSubmit={handleLogin} className="space-y-6">
            <AnimatePresence>
              {error && (
                <motion.div 
                  initial={{ opacity: 0, height: 0, mb: 0 }}
                  animate={{ opacity: 1, height: 'auto', mb: 24 }}
                  exit={{ opacity: 0, height: 0, mb: 0 }}
                  className="bg-[#dc2626]/10 border border-[#dc2626]/30 text-[#ff4b4b] p-4 rounded-2xl text-sm font-semibold flex items-center gap-3"
                >
                  <div className="w-1.5 h-1.5 rounded-full bg-[#dc2626] animate-pulse" />
                  {error}
                </motion.div>
              )}
            </AnimatePresence>

            <div className="space-y-5">
              <div className="relative group">
                <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                  <Mail className="h-5 w-5 text-slate-500 group-focus-within:text-cyan-400 transition-colors" />
                </div>
                <input 
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="Email Address"
                  className="w-full bg-[#030408]/50 border border-white/10 rounded-2xl pl-12 pr-4 py-4 text-white placeholder-slate-600 focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/50 transition-all"
                />
              </div>

              <div className="relative group">
                <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                  <Lock className="h-5 w-5 text-slate-500 group-focus-within:text-cyan-400 transition-colors" />
                </div>
                <input 
                  type="password"
                  required
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="Password"
                  className="w-full bg-[#030408]/50 border border-white/10 rounded-2xl pl-12 pr-4 py-4 text-white placeholder-slate-600 focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/50 transition-all"
                />
              </div>
            </div>

            <div className="flex items-center justify-between mt-2">
              <label className="flex items-center gap-2 cursor-pointer group">
                <input type="checkbox" className="w-4 h-4 rounded border-white/20 bg-white/5 text-cyan-500 focus:ring-cyan-500 focus:ring-offset-[#030408]" />
                <span className="text-sm text-slate-400 group-hover:text-slate-300 transition-colors">Remember me</span>
              </label>
              <a href="#" className="text-sm font-semibold text-cyan-400 hover:text-cyan-300 transition-colors">
                Forgot password?
              </a>
            </div>

            <button 
              type="submit" 
              disabled={isLoading}
              className="mt-8 group relative w-full flex items-center justify-center gap-3 bg-gradient-to-r from-[#102d56] to-cyan-700 text-white font-bold text-lg rounded-2xl py-4 overflow-hidden shadow-[0_10px_30px_rgba(16,45,86,0.5)] hover:shadow-[0_15px_40px_rgba(16,45,86,0.7)] transition-all duration-300 disabled:opacity-70"
            >
              <div className="absolute inset-0 bg-white/20 translate-y-full group-hover:translate-y-0 transition-transform duration-300 ease-in-out" />
              <span className="relative z-10 flex items-center gap-2">
                {isLoading ? "Authenticating..." : "Sign In"} 
                {!isLoading && <LogIn className="w-5 h-5 group-hover:translate-x-1 transition-transform" />}
              </span>
            </button>
          </form>

          {!fromAdmin && (
            <div className="mt-10 text-center">
              <p className="text-sm text-slate-400">
                Don't have an account?{" "}
                <Link href="/register" className="font-bold text-white hover:text-cyan-400 transition-colors underline decoration-white/30 underline-offset-4">
                  Create an account
                </Link>
              </p>
            </div>
          )}
        </div>
      </motion.div>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={<div className="min-h-screen flex items-center justify-center bg-[#030408]"><div className="w-8 h-8 rounded-full border-2 border-white/20 border-t-cyan-500 animate-spin" /></div>}>
      <LoginForm />
    </Suspense>
  );
}
