"use client";

import { useState, useEffect } from "react";
import { useCart } from "@/context/CartContext";
import Header from "@/components/layout/Header";
import Footer from "@/components/layout/Footer";
import { Skeleton } from "@/components/ui/Skeleton";
import { 
  Trash2, 
  Plus, 
  Minus, 
  ArrowRight, 
  ShoppingBag, 
  ChevronRight, 
  ShieldCheck, 
  Truck, 
  CreditCard,
  RotateCcw,
  Sparkles,
  Ticket,
  Heart,
  Loader2
} from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { getImageUrl, api } from "@/lib/api";
import { useSettings } from "@/context/SettingsContext";
import { useAuth } from "@/context/AuthContext";
import { useTranslation } from "@/lib/i18n";

export default function CartPage() {
  const router = useRouter();
  const { currency, formatMoney } = useSettings();
  const { user: authUser, isLoading: authLoading } = useAuth();
  const { t } = useTranslation();
  const { 
    items, 
    updateQuantity, 
    removeItem, 
    totalPrice, 
    totalItems, 
    applyCoupon, 
    removeCoupon,
    appliedCoupon,
    discountAmount 
  } = useCart();

  const [promoCode, setPromoCode] = useState("");
  const [isApplying, setIsApplying] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [isCheckingOut, setIsCheckingOut] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showSparkles, setShowSparkles] = useState(false);

  const handleApplyPromo = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!promoCode.trim()) return;
    if (subtotal <= 0) {
      setError("Your cart subtotal must be greater than zero");
      return;
    }
    if (authLoading) {
      setError("Please wait, checking your session...");
      return;
    }
    if (!authUser) {
      setError("Please login to apply a coupon");
      return;
    }

    setIsApplying(true);
    setError(null);
    try {
      const response = await api.applyCoupon(promoCode, subtotal);
      if (response.status === "success" && response.data) {
        // Calculate discount (backend should ideally return this, but we can calculate if needed)
        // Backend returns { code, discount, type, value }
        const discount = Number(
          (response as any).data?.discount ??
          (response as any).data?.discount_amount ??
          0
        );
        applyCoupon(response.data, discount);
        setShowSparkles(true);
        setTimeout(() => setShowSparkles(false), 2000);
      } else {
        setError(response.message || "Invalid coupon code");
      }
    } catch (err: any) {
      if (typeof err?.message === "string" && err.message.toLowerCase().includes("unauthenticated")) {
        setError("Session expired. Please login again to apply coupons");
      } else {
        setError(err.message || "Failed to apply coupon");
      }
    } finally {
      setIsApplying(false);
    }
  };

  // Optimize initial load
  useEffect(() => {
    // Reduce artificial delay for a snappier feel
    const timer = setTimeout(() => setIsLoading(false), 300);
    return () => clearTimeout(timer);
  }, []);

  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.08, // Faster stagger
        delayChildren: 0.1
      }
    }
  };

  const handleCheckout = async () => {
    setIsCheckingOut(true);
    // Snappier transition
    await new Promise(resolve => setTimeout(resolve, 400));
    setIsCheckingOut(false);
    router.push('/checkout');
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 15, scale: 0.99 },
    visible: {
      opacity: 1,
      y: 0,
      scale: 1,
      transition: {
        duration: 0.4,
      },
    },
  };

  const subtotal = totalPrice;
  const deliveryCharge = subtotal >= 100 ? 0 : 10;
  const finalTotal = subtotal + deliveryCharge - discountAmount;

  if (isLoading) {
    return (
      <div className="min-h-screen bg-white flex flex-col">
        <Header />
        <main className="flex-1 container mx-auto px-4 py-10 md:py-20">
          <div className="flex flex-col xl:flex-row gap-12 lg:gap-20">
            <div className="flex-1">
              <div className="mb-12 border-b border-zinc-100 pb-10 space-y-4">
                <Skeleton className="h-12 w-64 rounded-xl" />
                <Skeleton className="h-4 w-40 rounded-full" />
              </div>
              <div className="space-y-6">
                {[1, 2, 3].map((i) => (
                  <div key={i} className="flex flex-col md:flex-row gap-6 p-6 border border-zinc-100 rounded-2xl">
                    <Skeleton className="w-24 h-24 rounded-xl" />
                    <div className="flex-1 space-y-4 py-2">
                      <Skeleton className="h-6 w-1/2 rounded-lg" />
                      <Skeleton className="h-4 w-1/4 rounded-md" />
                      <div className="flex justify-between items-center pt-4">
                        <Skeleton className="h-8 w-24 rounded-lg" />
                        <Skeleton className="h-8 w-20 rounded-lg" />
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
            <div className="w-full xl:w-[380px] space-y-6">
              <Skeleton className="h-[400px] w-full rounded-2xl" />
            </div>
          </div>
        </main>
        <Footer />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-white flex flex-col relative overflow-hidden selection:bg-[#2b9d10]/10 selection:text-[#2b9d10]">
      {/* Clean Minimal Background */}
      <div className="fixed inset-0 pointer-events-none z-0 bg-zinc-50/30" />

      <Header />
      
      <main className="flex-1 container mx-auto px-4 py-8 md:py-16 relative z-10">
        {/* Minimal Breadcrumb */}
        <motion.nav 
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex items-center gap-3 mb-8 md:mb-12 text-[10px] font-bold tracking-[0.2em] text-zinc-400"
        >
          <Link href="/" className="hover:text-[#2b9d10] transition-colors uppercase">{t("homeUpper")}</Link>
          <ChevronRight size={10} className="text-zinc-300" />
          <span className="text-zinc-900 uppercase">{t("shoppingCartUpper")}</span>
        </motion.nav>

        <div className="flex flex-col xl:flex-row gap-10 lg:gap-16">
          {/* Cart Items Section */}
          <div className="flex-1">
            <motion.div 
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              className="mb-10 flex flex-col sm:flex-row sm:items-end justify-between border-b border-zinc-100 pb-8 gap-6"
            >
              <div>
                <h1 className="text-4xl md:text-5xl font-black text-zinc-900 tracking-tight">
                  {t("shopping")} <span className="text-[#2b9d10]">{t("cartUpper")}</span>
                </h1>
                <p className="text-zinc-500 text-sm mt-2">
                  {t("youHaveItems").replace("{n}", String(totalItems))}
                </p>
              </div>
              <Link href="/products" className="group text-[11px] font-bold text-zinc-500 hover:text-[#2b9d10] transition-all flex items-center gap-2 uppercase tracking-widest">
                {t("continueShoppingUpper")} <ArrowRight size={14} className="group-hover:translate-x-1 transition-transform" />
              </Link>
            </motion.div>

            {isLoading ? (
              <div className="space-y-6">
                {[1, 2, 3].map((i) => (
                  <div key={i} className="bg-white p-6 rounded-2xl border border-zinc-100 flex flex-col md:flex-row gap-6">
                    <Skeleton className="w-24 h-24 rounded-xl" />
                    <div className="flex-1 space-y-4 py-2">
                      <div className="flex items-center gap-3">
                        <Skeleton className="h-3 w-16 rounded-full" />
                      </div>
                      <Skeleton className="h-6 w-1/2 rounded-lg" />
                      <div className="flex flex-wrap items-center gap-8 pt-4">
                        <div className="space-y-2">
                          <Skeleton className="h-3 w-12 rounded-full" />
                          <Skeleton className="h-6 w-20 rounded-lg" />
                        </div>
                        <Skeleton className="h-10 w-28 rounded-xl" />
                        <Skeleton className="h-8 w-8 rounded-lg ml-auto" />
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : items.length > 0 ? (
              <motion.div 
                variants={containerVariants}
                initial="hidden"
                animate="visible"
                className="space-y-8"
              >
                <AnimatePresence mode="popLayout">
                  {items.map((item, index) => {
                    const { image, image_url, imageUrl, iconUrl } = item as any;
                    const displayImage = image || image_url || imageUrl || iconUrl || (item as any).icon_url;
                    
                    return (
                      <motion.div 
                        key={item.id}
                        variants={itemVariants}
                        exit={{ opacity: 0, scale: 0.98, transition: { duration: 0.2 } }}
                        className="bg-white p-5 rounded-2xl border border-zinc-100 flex flex-col md:flex-row items-center gap-6 group hover:border-[#2b9d10]/30 transition-all duration-300 relative"
                      >
                        {/* Image Section */}
                        <div className="w-24 h-24 bg-zinc-50 rounded-xl flex items-center justify-center relative overflow-hidden shrink-0 border border-zinc-100/50">
                          <div className="relative w-full h-full p-3">
                            {getImageUrl(displayImage) ? (
                              <Image
                                src={getImageUrl(displayImage)!}
                                alt={item.name}
                                fill
                                className="object-contain"
                              />
                            ) : (
                              <div className="w-full h-full flex items-center justify-center">
                                <ShoppingBag size={24} className="text-zinc-200" />
                              </div>
                            )}
                          </div>
                        </div>
                        
                        {/* Details */}
                        <div className="flex-1 flex flex-col md:flex-row items-center gap-6 w-full">
                          <div className="flex-1 text-center md:text-left">
                            <p className="text-[#2b9d10] text-[10px] font-bold uppercase tracking-widest mb-1">{item.unit}</p>
                            <h3 className="text-base font-bold text-zinc-900 line-clamp-1">
                              {item.name}
                            </h3>
                          </div>
                          
                          <div className="flex flex-wrap items-center justify-center md:justify-end gap-10 w-full md:w-auto">
                          <div className="text-center md:text-left">
                            <p className="text-[10px] text-zinc-400 font-bold uppercase tracking-widest mb-1">Price</p>
                            <p className="font-bold text-zinc-900 text-sm">{formatMoney(item.price)}</p>
                          </div>

                            {/* Quantity Controls */}
                            <div className="flex items-center bg-zinc-50 rounded-lg p-1 border border-zinc-100">
                              <button 
                                onClick={() => updateQuantity(item.id, item.quantity - 1)}
                                disabled={item.quantity <= 1}
                                className="w-7 h-7 flex items-center justify-center text-zinc-400 hover:text-zinc-900 disabled:opacity-30 transition-colors"
                              >
                                <Minus size={12} />
                              </button>
                              <span className="w-8 text-center font-bold text-zinc-900 text-xs">{item.quantity}</span>
                              <button 
                                onClick={() => updateQuantity(item.id, item.quantity + 1)}
                                className="w-7 h-7 flex items-center justify-center text-zinc-400 hover:text-[#2b9d10] transition-colors"
                              >
                                <Plus size={12} />
                              </button>
                            </div>

                            <div className="text-center md:text-left min-w-[70px]">
                              <p className="text-[10px] text-zinc-400 font-bold uppercase tracking-widest mb-1">Total</p>
                              <p className="font-bold text-[#2b9d10] text-base">{formatMoney(item.price * item.quantity)}</p>
                            </div>
                          </div>
                        </div>

                        {/* Actions */}
                        <div className="flex flex-row md:flex-col items-center justify-center mt-4 md:mt-0 pt-4 md:pt-0 border-t md:border-t-0 md:border-l border-zinc-100 md:pl-6">
                          <button 
                            onClick={() => removeItem(item.id)}
                            className="p-2 text-zinc-300 hover:text-red-500 transition-colors"
                          >
                            <Trash2 size={16} />
                          </button>
                        </div>
                      </motion.div>
                    );
                  })}
                </AnimatePresence>
              </motion.div>
            ) : (
              <motion.div 
                initial={{ opacity: 0, scale: 0.98 }}
                animate={{ opacity: 1, scale: 1 }}
                className="bg-white rounded-2xl p-12 md:p-16 text-center border border-zinc-100"
              >
                <div className="w-16 h-16 bg-zinc-50 rounded-full flex items-center justify-center mx-auto mb-6">
                  <ShoppingBag size={28} className="text-zinc-200" />
                </div>
                <h2 className="text-xl font-bold text-zinc-900 mb-2">{t("yourCartIsEmpty")}</h2>
                <p className="text-zinc-500 text-sm mb-8 max-w-xs mx-auto">
                  {t("looksLikeNothing")}
                </p>
                <Link 
                  href="/products" 
                  className="inline-flex items-center gap-2 bg-[#2b9d10] text-white px-8 py-3.5 rounded-xl font-bold text-xs hover:bg-[#23800d] transition-all"
                >
                  {t("startShopping")}
                  <ArrowRight size={16} />
                </Link>
              </motion.div>
            )}
          </div>

          {/* Order Summary Section - Clean & Sharp */}
          {items.length > 0 && (
              <motion.div 
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className="w-full xl:w-[380px] space-y-6"
              >
                {/* Summary Card */}
                <div className="bg-white rounded-2xl border border-zinc-100 p-8 shadow-sm">
                  <h2 className="text-lg font-bold text-zinc-900 mb-6">{t("orderSummary")}</h2>

                  <div className="space-y-4 mb-8">
                    <div className="flex justify-between items-center text-sm">
                      <span className="text-zinc-500">{t("subtotal")}</span>
                      <span className="font-bold text-zinc-900">{formatMoney(subtotal)}</span>
                    </div>
                    
                    <div className="flex justify-between items-center text-sm">
                      <span className="text-zinc-500">{t("shipping")}</span>
                      <span className={`font-bold ${deliveryCharge === 0 ? "text-[#2b9d10]" : "text-zinc-900"}`}>
                        {deliveryCharge === 0 ? t("free") : formatMoney(deliveryCharge)}
                      </span>
                    </div>

                    {discountAmount > 0 && (
                      <div className="flex justify-between items-center text-sm text-[#2b9d10]">
                        <span>{t("discount")}</span>
                        <span className="font-bold">- {formatMoney(discountAmount)}</span>
                      </div>
                    )}

                    <div className="pt-4 border-t border-zinc-100">
                      <div className="flex justify-between items-end">
                        <span className="text-sm font-medium text-zinc-500">{t("totalAmount")}</span>
                        <span className="text-2xl font-bold text-zinc-900">{formatMoney(finalTotal)}</span>
                      </div>
                    </div>
                  </div>

                  {/* Promo Input */}
                  <form onSubmit={handleApplyPromo} className="relative mb-6">
                    <input
                      type="text"
                      placeholder={t("promoCode")}
                      value={promoCode}
                      onChange={(e) => setPromoCode(e.target.value)}
                      className="w-full px-4 py-3.5 bg-zinc-50 border border-zinc-100 rounded-xl text-sm focus:outline-none focus:border-[#2b9d10] transition-all"
                    />
                    <button 
                      type="submit"
                      disabled={isApplying || !promoCode.trim() || subtotal <= 0 || authLoading || !authUser}
                      className="absolute right-2 top-2 bottom-2 px-4 bg-zinc-900 text-white rounded-lg text-[10px] font-bold hover:bg-black transition-all disabled:opacity-30"
                    >
                      {isApplying ? <Loader2 size={12} className="animate-spin" /> : t("apply")}
                    </button>
                  </form>
                  {!authLoading && !authUser && !error && (
                    <p className="text-xs font-bold text-zinc-500 mt-[-8px] mb-6">
                      {t("loginToApplyCoupons")}
                    </p>
                  )}
                  {error && (
                    <p className="text-xs font-bold text-red-600 mt-[-12px] mb-6">{error}</p>
                  )}

                  {/* Checkout Button */}
                  <button
                    onClick={handleCheckout}
                    disabled={isCheckingOut}
                    className="w-full bg-[#2b9d10] text-white py-4 rounded-xl font-bold text-xs hover:bg-[#23800d] transition-all flex items-center justify-center gap-2 tracking-widest"
                  >
                    {isCheckingOut ? (
                      <Loader2 size={18} className="animate-spin" />
                    ) : (
                      <>
                        {t("checkoutNow")}
                        <ArrowRight size={16} />
                      </>
                    )}
                  </button>

                  {/* Trust Info */}
                  <div className="mt-6 flex items-center justify-center gap-6 text-zinc-400">
                    <div className="flex items-center gap-1.5 text-[9px] font-bold uppercase tracking-wider">
                      <ShieldCheck size={14} className="text-[#2b9d10]" />
                      <span>{t("secure")}</span>
                    </div>
                    <div className="flex items-center gap-1.5 text-[9px] font-bold uppercase tracking-wider">
                      <Truck size={14} className="text-[#2b9d10]" />
                      <span>{t("fast")}</span>
                    </div>
                  </div>
                </div>

                {/* Shipping Notice */}
                <div className="bg-zinc-900 rounded-2xl p-6 text-white overflow-hidden relative">
                  <div className="absolute top-0 right-0 w-32 h-32 bg-[#2b9d10]/10 blur-3xl rounded-full -mr-16 -mt-16" />
                  <p className="text-[9px] font-bold uppercase tracking-wider text-[#2b9d10] mb-2 relative z-10">{t("freeDeliveryStatus")}</p>
                  <p className="text-xs text-zinc-400 leading-relaxed mb-4 relative z-10">
                    Add <span className="text-white font-bold">{formatMoney(Math.max(0, 100 - subtotal))}</span> more for <span className="text-white font-bold">{t("freeShippingUpper")}</span>.
                  </p>
                  <div className="h-1 bg-white/10 rounded-full overflow-hidden relative z-10">
                    <motion.div 
                      initial={{ width: 0 }}
                      animate={{ width: `${Math.min((subtotal / 100) * 100, 100)}%` }}
                      transition={{ duration: 1 }}
                      className="h-full bg-[#2b9d10]"
                    />
                  </div>
                </div>
              </motion.div>
          )}
        </div>
      </main>

      <Footer />
    </div>
  );
}
