"use client";

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

function RegisterForm() {
  const router = useRouter();
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");

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

    try {
      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ firstName, lastName, email, password }),
      });

      const data = await res.json();

      if (!res.ok) {
        setError(data.error || "An unknown error occurred.");
        setIsLoading(false);
        return;
      }

      // Automatically log the user in after registration
      const result = await signIn("credentials", {
        email,
        password,
        redirect: false,
      });

      if (result?.error) {
        setError("Account created, but auto-login failed. Please sign in manually.");
        setIsLoading(false);
        return;
      }

      router.push("/dashboard");
      router.refresh();
    } catch (err) {
      setError("Connection failed. Please check your network.");
      setIsLoading(false);
    }
  };

  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%] right-[-10%] w-[50%] h-[50%] bg-[#dc2626]/20 rounded-full blur-[140px]" />
        <div className="absolute bottom-[-10%] left-[-10%] w-[50%] h-[50%] bg-[#102d56]/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-bl from-[#dc2626]/20 to-transparent border-r border-white/5">
          <div className="absolute top-[-20%] left-[-20%] w-[80%] h-[80%] bg-[#102d56]/20 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-[#ff4b4b] transition-colors">RIMA ACADEMY</span>
            </Link>
            
            <h2 className="text-4xl lg:text-5xl font-black mb-6 leading-[1.1] tracking-tight">
              Begin your <span className="text-transparent bg-clip-text bg-gradient-to-r from-[#ff4b4b] to-[#dc2626]">Journey</span>
            </h2>
            <p className="text-slate-400 text-lg leading-relaxed">
              Create an account to unlock full access to our premium language courses, corporate training, and interactive learning platform.
            </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 flex items-center gap-4">
              <div className="w-12 h-12 rounded-full bg-[#dc2626]/20 flex items-center justify-center shrink-0 border border-[#dc2626]/20 shadow-inner">
                <span className="text-2xl">🌍</span>
              </div>
              <p className="text-sm text-slate-300 font-medium">Join over <span className="text-white font-bold">5,000+</span> students globally mastering a new language.</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">Create Account</h1>
            <p className="text-slate-400 text-sm font-medium">Enter your details to get started.</p>
          </div>

          <form onSubmit={handleRegister} className="space-y-5">
            <AnimatePresence>
              {error && (
                <motion.div 
                  initial={{ opacity: 0, height: 0, mb: 0 }}
                  animate={{ opacity: 1, height: 'auto', mb: 20 }}
                  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="grid grid-cols-2 gap-4">
              <div className="relative group">
                <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                  <User className="h-5 w-5 text-slate-500 group-focus-within:text-[#ff4b4b] transition-colors" />
                </div>
                <input 
                  type="text"
                  required
                  value={firstName}
                  onChange={(e) => setFirstName(e.target.value)}
                  placeholder="First Name"
                  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-[#dc2626]/50 focus:ring-1 focus:ring-[#dc2626]/50 transition-all"
                />
              </div>

              <div className="relative group">
                <input 
                  type="text"
                  required
                  value={lastName}
                  onChange={(e) => setLastName(e.target.value)}
                  placeholder="Last Name"
                  className="w-full bg-[#030408]/50 border border-white/10 rounded-2xl px-5 py-4 text-white placeholder-slate-600 focus:outline-none focus:border-[#dc2626]/50 focus:ring-1 focus:ring-[#dc2626]/50 transition-all"
                />
              </div>
            </div>

            <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-[#ff4b4b] 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-[#dc2626]/50 focus:ring-1 focus:ring-[#dc2626]/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-[#ff4b4b] 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-[#dc2626]/50 focus:ring-1 focus:ring-[#dc2626]/50 transition-all"
              />
            </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-[#991b1b] to-[#dc2626] text-white font-bold text-lg rounded-2xl py-4 overflow-hidden shadow-[0_10px_30px_rgba(220,38,38,0.3)] hover:shadow-[0_15px_40px_rgba(220,38,38,0.5)] 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 ? "Creating account..." : "Create Account"} 
                {!isLoading && <UserPlus className="w-5 h-5 group-hover:translate-x-1 transition-transform" />}
              </span>
            </button>
          </form>

          <div className="mt-8 text-center">
            <p className="text-sm text-slate-400">
              Already have an account?{" "}
              <Link href="/login" className="font-bold text-white hover:text-[#ff4b4b] transition-colors underline decoration-white/30 underline-offset-4">
                Sign in
              </Link>
            </p>
          </div>
        </div>
      </motion.div>
    </div>
  );
}

export default function RegisterPage() {
  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-[#dc2626] animate-spin" /></div>}>
      <RegisterForm />
    </Suspense>
  );
}
