"use client";

import { Suspense } from "react";
import { useState } from "react";
import { useAuth } from "@/context/AuthContext";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect } from "react";
import Link from "next/link";
import { motion } from "framer-motion";
import { ArrowLeft, Mail, Lock, Eye, EyeOff, ShoppingBag, ArrowRight, ShieldCheck, Zap, Heart } from "lucide-react";
import { Skeleton } from "@/components/ui/Skeleton";
import { useTranslation } from "@/lib/i18n";
import { useSettings } from "@/context/SettingsContext";

function LoginContent() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const { login, user, isLoading } = useAuth();
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirect = searchParams.get("redirect") || "/";
  const { t } = useTranslation();
  const { settings } = useSettings();
  const siteName = settings?.site_name || "SmartGrocery SaaS";
  const [siteFirst, ...siteRestParts] = siteName.split(" ");
  const siteFirstWord = siteFirst || siteName;
  const siteRest = siteRestParts.join(" ");
  const logo = (settings as any)?.logo as string | undefined;

  useEffect(() => {
    if (!isLoading && user) {
      router.push(redirect);
    }
  }, [user, isLoading, router, redirect]);

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

    try {
      await login({ email, password });
      router.push(redirect);
    } catch (err: any) {
      const message =
        err?.message === "Invalid login credentials"
          ? t("invalidLoginMessage")
          : err?.message || "Something went wrong while logging you in.";
      setError(message);
    } finally {
      setLoading(false);
    }
  };

  if (isLoading || user) {
    return (
      <div className="min-h-screen bg-[#fcfcfc] flex flex-col lg:flex-row relative overflow-hidden">
        <div className="hidden lg:flex lg:w-1/2 bg-[#1a1a1a] relative items-center justify-center p-20 overflow-hidden">
          <div className="relative z-10 w-full max-w-lg space-y-12">
            <div className="flex items-center gap-4">
              <Skeleton className="w-16 h-16 rounded-2xl bg-zinc-800" />
              <div className="space-y-2">
                <Skeleton className="h-8 w-32 rounded-lg bg-zinc-800" />
                <Skeleton className="h-4 w-24 rounded-lg bg-zinc-800" />
              </div>
            </div>
            <div className="space-y-6">
              <Skeleton className="h-20 w-3/4 rounded-2xl bg-zinc-800" />
              <Skeleton className="h-6 w-full rounded-xl bg-zinc-800" />
            </div>
            <div className="grid grid-cols-2 gap-6 pt-12">
              {[1, 2, 3, 4].map((i) => (
                <div key={i} className="space-y-3">
                  <Skeleton className="h-5 w-5 rounded-lg bg-zinc-800" />
                  <Skeleton className="h-4 w-24 rounded-lg bg-zinc-800" />
                  <Skeleton className="h-3 w-16 rounded-lg bg-zinc-800" />
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="flex-1 flex flex-col items-center justify-center p-6 md:p-20">
          <div className="max-w-md w-full space-y-12">
            <div className="space-y-4">
              <Skeleton className="h-12 w-48 rounded-2xl" />
              <Skeleton className="h-6 w-64 rounded-xl" />
            </div>
            <div className="space-y-8">
              <div className="space-y-6">
                <div className="space-y-2">
                  <Skeleton className="h-3 w-20 rounded-full ml-2" />
                  <Skeleton className="h-16 w-full rounded-[2rem]" />
                </div>
                <div className="space-y-2">
                  <div className="flex justify-between px-2">
                    <Skeleton className="h-3 w-16 rounded-full" />
                    <Skeleton className="h-3 w-12 rounded-full" />
                  </div>
                  <Skeleton className="h-16 w-full rounded-[2rem]" />
                </div>
              </div>
              <Skeleton className="h-20 w-full rounded-[2rem]" />
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#fcfcfc] flex flex-col lg:flex-row relative overflow-hidden">
      {/* Decorative Blobs */}
      <div className="absolute top-[-10%] left-[-10%] w-[40%] h-[40%] bg-[#2b9d10] opacity-[0.03] blur-[120px] rounded-full pointer-events-none" />
      <div className="absolute bottom-[-10%] right-[-10%] w-[40%] h-[40%] bg-blue-500 opacity-[0.03] blur-[120px] rounded-full pointer-events-none" />

      {/* Left Side: Branding/Visuals (Visible on Desktop) */}
      <div className="hidden lg:flex lg:w-1/2 bg-[#1a1a1a] relative items-center justify-center p-20 overflow-hidden">
        {/* Animated Background Elements */}
        <motion.div 
          animate={{ 
            scale: [1, 1.2, 1],
            rotate: [0, 90, 0],
          }}
          transition={{ duration: 20, repeat: Infinity, ease: "linear" }}
          className="absolute top-[-20%] right-[-20%] w-[80%] h-[80%] border border-white/5 rounded-[4rem] pointer-events-none" 
        />
        <motion.div 
          animate={{ 
            scale: [1, 1.1, 1],
            rotate: [0, -90, 0],
          }}
          transition={{ duration: 25, repeat: Infinity, ease: "linear" }}
          className="absolute bottom-[-10%] left-[-10%] w-[60%] h-[60%] border border-white/5 rounded-full pointer-events-none" 
        />

        <div className="relative z-10 max-w-lg">
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8 }}
            className="space-y-12"
          >
            <Link href="/" className="inline-flex items-center gap-4 group">
              {logo ? (
                <div className="w-16 h-16 rounded-2xl overflow-hidden bg-white/5 border border-white/10 shadow-2xl shadow-green-500/20 group-hover:scale-110 transition-transform duration-500">
                  <img src={logo} alt={siteName} className="w-full h-full object-contain" />
                </div>
              ) : (
                <div className="w-16 h-16 bg-[#2b9d10] rounded-2xl flex items-center justify-center shadow-2xl shadow-green-500/20 group-hover:scale-110 transition-transform duration-500">
                  <ShoppingBag className="text-white" size={32} />
                </div>
              )}
              <div className="flex flex-col">
                <span className="text-3xl font-black text-white tracking-tighter leading-none">{siteFirstWord}</span>
                <span className="text-sm font-bold text-[#2b9d10] tracking-[0.3em] leading-none mt-1">{siteRest}</span>
              </div>
            </Link>

            <div className="space-y-6">
              <h1 className="text-6xl font-black text-white leading-tight tracking-tighter">
                Freshness <br />
                <span className="text-[#2b9d10]">Redefined.</span>
              </h1>
              <p className="text-zinc-500 text-xl font-medium leading-relaxed">
                Join thousands of happy customers and experience the future of grocery shopping today.
              </p>
            </div>

            <div className="grid grid-cols-2 gap-6 pt-12">
              {[
                { icon: <Zap size={20} />, label: "Express Delivery", desc: "Under 30 mins" },
                { icon: <ShieldCheck size={20} />, label: "Secure Payment", desc: "100% Protected" },
                { icon: <Heart size={20} />, label: "Fresh Quality", desc: "Farm to Table" },
                { icon: <ArrowRight size={20} />, label: "Best Prices", desc: "Daily Discounts" },
              ].map((item, i) => (
                <motion.div 
                  key={i}
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.5 + (i * 0.1) }}
                  className="space-y-2"
                >
                  <div className="text-[#2b9d10]">{item.icon}</div>
                  <div className="font-black text-white text-sm uppercase tracking-wider">{item.label}</div>
                  <div className="text-zinc-600 text-xs font-bold">{item.desc}</div>
                </motion.div>
              ))}
            </div>
          </motion.div>
        </div>
      </div>

      {/* Right Side: Login Form */}
      <div className="flex-1 flex flex-col items-center justify-center p-6 md:p-20 relative z-10">
        {/* Back Button */}
        <Link 
          href="/" 
          className="absolute top-8 md:top-12 left-6 md:left-20 flex items-center gap-3 text-zinc-400 hover:text-zinc-900 transition-all font-black text-[9px] md:text-[10px] uppercase tracking-[0.3em] group"
        >
          <div className="w-7 h-7 md:w-8 md:h-8 rounded-full bg-zinc-50 flex items-center justify-center group-hover:bg-zinc-100 transition-colors">
            <ArrowLeft size={12} className="md:w-[14px] md:h-[14px] group-hover:-translate-x-1 transition-transform" />
          </div>
          Back to Home
        </Link>

        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.5 }}
          className="max-w-md w-full space-y-8 md:space-y-12 mt-12 md:mt-0"
        >
            <div className="text-center lg:text-left space-y-3 md:space-y-4">
            <h2 className="text-4xl md:text-5xl font-black text-zinc-900 tracking-tighter leading-none">
                {t("welcomeBackHeadline")}
            </h2>
            <p className="text-zinc-400 font-bold text-base md:text-lg">
                {t("welcomeBackSub")}
            </p>
          </div>

          <form className="space-y-6 md:space-y-8" onSubmit={handleSubmit}>
            {error && (
              <motion.div 
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                className="bg-red-50 text-red-500 p-4 md:p-5 rounded-2xl md:rounded-[1.5rem] text-[10px] md:text-xs font-black text-center border border-red-100 flex items-center justify-center gap-3"
              >
                <div className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" />
                {error}
              </motion.div>
            )}

            <div className="space-y-4 md:space-y-6">
              <div className="space-y-2">
                <label className="text-[9px] md:text-[10px] font-black text-zinc-400 uppercase tracking-[0.2em] ml-2">
                  {t("emailAddress")}
                </label>
                <div className="relative group">
                  <div className="absolute inset-y-0 left-0 pl-5 md:pl-6 flex items-center pointer-events-none text-zinc-400 group-focus-within:text-[#2b9d10] transition-colors">
                    <Mail size={16} className="md:w-[18px] md:h-[18px]" />
                  </div>
                  <input
                    type="email"
                    required
                    aria-invalid={!!error}
                    className={`block w-full pl-12 md:pl-14 pr-5 md:pr-6 py-4 md:py-5 bg-white border rounded-2xl md:rounded-[2rem] text-sm font-black text-zinc-900 placeholder-zinc-300 focus:outline-none transition-all ${
                      error
                        ? "border-red-200 focus:border-red-400 focus:shadow-[0_10px_40px_-10px_rgba(248,113,113,0.25)]"
                        : "border-zinc-100 focus:border-[#2b9d10]/30 focus:shadow-[0_10px_40px_-10px_rgba(43,157,16,0.1)]"
                    }`}
                    placeholder="name@example.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <div className="flex justify-between items-center px-2">
                  <label className="text-[9px] md:text-[10px] font-black text-zinc-400 uppercase tracking-[0.2em]">
                    {t("password")}
                  </label>
                  <Link href="#" className="text-[9px] md:text-[10px] font-black text-[#2b9d10] hover:text-[#23800d] uppercase tracking-[0.2em] transition-colors">
                    {t("forgotPassword")}
                  </Link>
                </div>
                <div className="relative group">
                  <div className="absolute inset-y-0 left-0 pl-5 md:pl-6 flex items-center pointer-events-none text-zinc-400 group-focus-within:text-[#2b9d10] transition-colors">
                    <Lock size={16} className="md:w-[18px] md:h-[18px]" />
                  </div>
                  <input
                    type={showPassword ? "text" : "password"}
                    required
                    aria-invalid={!!error}
                    className={`block w-full pl-12 md:pl-14 pr-12 md:pr-14 py-4 md:py-5 bg-white border rounded-2xl md:rounded-[2rem] text-sm font-black text-zinc-900 placeholder-zinc-300 focus:outline-none transition-all ${
                      error
                        ? "border-red-200 focus:border-red-400 focus:shadow-[0_10px_40px_-10px_rgba(248,113,113,0.25)]"
                        : "border-zinc-100 focus:border-[#2b9d10]/30 focus:shadow-[0_10px_40px_-10px_rgba(43,157,16,0.1)]"
                    }`}
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute inset-y-0 right-0 pr-5 md:pr-6 flex items-center text-zinc-400 hover:text-[#2b9d10] transition-colors"
                  >
                    {showPassword ? <EyeOff size={16} className="md:w-[18px] md:h-[18px]" /> : <Eye size={16} className="md:w-[18px] md:h-[18px]" />}
                  </button>
                </div>
              </div>
            </div>

            <div className="flex items-center gap-3 px-2">
              <label className="relative flex items-center cursor-pointer group">
                <input
                  type="checkbox"
                  className="peer sr-only"
                />
                <div className="w-4 h-4 md:w-5 md:h-5 border-2 border-zinc-100 rounded md:rounded-lg bg-white peer-checked:bg-[#2b9d10] peer-checked:border-[#2b9d10] transition-all duration-300" />
                <Check size={10} className="md:w-[12px] md:h-[12px] absolute left-[3px] md:left-[4px] text-white opacity-0 peer-checked:opacity-100 transition-opacity" />
                <span className="ml-3 text-[11px] md:text-xs font-bold text-zinc-400 group-hover:text-zinc-600 transition-colors">Keep me signed in</span>
              </label>
            </div>

            <motion.button
              whileHover={{ scale: 1.01 }}
              whileTap={{ scale: 0.98 }}
              type="submit"
              disabled={loading}
              className="w-full bg-[#1a1a1a] text-white py-5 md:py-6 rounded-2xl md:rounded-[2rem] font-black text-[10px] md:text-xs tracking-[0.3em] uppercase hover:bg-black transition-all shadow-xl md:shadow-2xl shadow-zinc-200 disabled:opacity-50 flex items-center justify-center gap-3 md:gap-4 relative overflow-hidden group"
            >
              <div className="absolute inset-0 bg-gradient-to-r from-[#2b9d10] to-[#4ade80] opacity-0 group-hover:opacity-10 transition-opacity" />
              {loading ? (
                <>
                  <div className="w-4 h-4 md:w-5 md:h-5 border-2 md:border-3 border-white/30 border-t-white rounded-full animate-spin" />
                  AUTHENTICATING...
                </>
              ) : (
                <>
                  SIGN IN <ArrowRight size={14} className="md:w-[16px] md:h-[16px] group-hover:translate-x-1 transition-transform" />
                </>
              )}
            </motion.button>
          </form>

          <div className="pt-6 md:pt-8 text-center border-t border-zinc-50">
            <p className="text-xs md:text-sm text-zinc-400 font-bold">
              New to {siteName}?{" "}
              <Link href="/register" className="text-[#2b9d10] font-black uppercase tracking-[0.1em] hover:underline ml-2">
                Create Account
              </Link>
            </p>
          </div>
        </motion.div>
      </div>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense>
      <LoginContent />
    </Suspense>
  );
}

import { Check } from "lucide-react";
