"use client";

import { useState, useEffect } from "react";
import { useCart } from "@/context/CartContext";
import { useAuth } from "@/context/AuthContext";
import Header from "@/components/layout/Header";
import Footer from "@/components/layout/Footer";
import { Skeleton } from "@/components/ui/Skeleton";
import { api, getImageUrl } from "@/lib/api";
import { PaymentMethod, DeliveryType, Order, Product } from "@/types";
import ProductCard from "@/components/product/ProductCard";
import { 
  Loader2, 
  CheckCircle2, 
  AlertCircle, 
  CreditCard, 
  Truck, 
  MapPin, 
  ChevronRight,
  ArrowRight, 
  ShoppingBag,
  Sparkles,
  ShieldCheck,
  RotateCcw,
  ShoppingBasket
} from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
import Link from "next/link";
import { useSettings } from "@/context/SettingsContext";

export default function CheckoutPage() {
  const router = useRouter();
  const { items, totalPrice, clearCart, appliedCoupon, discountAmount } = useCart();
  const { user, isLoading: authLoading } = useAuth();
  const { settings, currency, formatMoney } = useSettings();
  const [loading, setLoading] = useState(true);
  const [processing, setProcessing] = useState(false);
  const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>([]);
  const [deliveryTypes, setDeliveryTypes] = useState<DeliveryType[]>([]);
  const [selectedPayment, setSelectedPayment] = useState<number | null>(null);
  const [selectedDelivery, setSelectedDelivery] = useState<number | null>(null);
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);
  
  const [formData, setFormData] = useState({
    first_name: "",
    last_name: "",
    address: "",
    city: "",
    zip: "",
    phone: "",
    notes: ""
  });

  const [orderSuccess, setOrderSuccess] = useState<number | null>(null);
  const [orderSummary, setOrderSummary] = useState<Order | null>(null);
  const [suggestedProducts, setSuggestedProducts] = useState<Product[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [walletBalance, setWalletBalance] = useState("0.00");
  const [razorpayLoaded, setRazorpayLoaded] = useState(false);

  // Load suggested products when order is successful
  useEffect(() => {
    if (orderSuccess) {
      api.getOrderById(orderSuccess).then(res => {
        if (res.data) setOrderSummary(res.data as any);
      }).catch(() => {}); // Suppress warning

      api.getPopularProducts().then(res => {
        if (res.data) setSuggestedProducts(res.data.slice(0, 4));
      }).catch(() => {}); // Suppress warning
    }
  }, [orderSuccess]);

  // Consolidated Initialization Logic
  useEffect(() => {
    if (!isMounted) return;

    // 1. Auth & Cart Guard
    if (!authLoading) {
      if (!user) {
        router.push("/login?redirect=/checkout");
        return;
      }
      if (items.length === 0 && !orderSuccess) {
        router.push("/cart");
        return;
      }
    }

    // 2. Pre-fill Form Data
    if (user && formData.first_name === "") {
      const names = user.name.split(" ");
      setFormData(prev => ({
        ...prev,
        first_name: names[0] || "",
        last_name: names.slice(1).join(" ") || "",
        phone: user.phone || "",
        address: user.address || "",
        city: user.city || "",
        zip: user.zip || ""
      }));
    }

    // 3. Fetch Initial Data (Payment & Delivery)
    const fetchData = async () => {
      if (paymentMethods.length > 0) return; // Already fetched

      try {
        const [pmRes, dtRes, walletRes] = await Promise.all([
          api.getPaymentMethods(),
          api.getDeliveryTypes(),
          api.getWallet().catch(() => ({ data: { balance: "0.00" } }))
        ]);

        if (walletRes.data) {
          setWalletBalance(walletRes.data.balance);
        }

        if (pmRes.data) {
          const methods = pmRes.data;
          
          // Add Wallet Payment Method if balance is sufficient
          const currentTotal = totalPrice + (deliveryTypes.find(d => d.id === selectedDelivery)?.cost || 0);
          if (Number(walletRes.data?.balance || 0) >= currentTotal) {
             // We can dynamically add wallet as a payment method or handle it separately
             // For now, let's just fetch it to show the user
          }
          
          setPaymentMethods(methods);
          const cod = methods.find(p => p.type === 'cod');
          if (cod) setSelectedPayment(cod.id);
          else if (methods.length > 0) setSelectedPayment(methods[0].id);

          // Dynamically load Razorpay if it's an available method
          const hasRazorpay = methods.some(p => p.type?.toLowerCase() === 'razorpay');
          if (hasRazorpay && !(window as any).Razorpay) {
            const script = document.createElement('script');
            script.src = 'https://checkout.razorpay.com/v1/checkout.js';
            script.async = true;
            script.onload = () => setRazorpayLoaded(true);
            document.body.appendChild(script);
          } else if (hasRazorpay) {
            setRazorpayLoaded(true);
          }
        }

        if (dtRes.data) {
          setDeliveryTypes(dtRes.data);
          if (dtRes.data.length > 0) setSelectedDelivery(dtRes.data[0].id);
        }
      } catch (error) {
        // Error handling silently in production
      } finally {
        setLoading(false);
      }
    };

    if (user) fetchData();
  }, [isMounted, authLoading, user, items.length, orderSuccess, router, formData.first_name, paymentMethods.length]);

  // Handle gateway callbacks (PayPal/Paytm success)
  useEffect(() => {
    if (!isMounted) return;

    const handleCallback = async () => {
      const searchParams = new URLSearchParams(window.location.search);
      const status = searchParams.get('status');
      if (!status) return;

      const orderId = searchParams.get('order_id');
      const transactionId = searchParams.get('transaction_id') || '';

      if (status === 'success') {
        if (orderId) {
          setOrderSuccess(parseInt(orderId));
          clearCart();
          localStorage.removeItem('pending_checkout');
          window.history.replaceState({}, '', window.location.pathname);
        } else {
          const savedCheckoutStr = localStorage.getItem('pending_checkout');
          if (savedCheckoutStr) {
            try {
              const savedCheckout = JSON.parse(savedCheckoutStr);
              const { 
                formData: savedForm, 
                selectedPayment: savedPM, 
                selectedDelivery: savedDT, 
                appliedCoupon: savedCoupon,
                items: savedItems
              } = savedCheckout;

              const orderItems = (items && items.length > 0) ? items : savedItems;
              if (!orderItems || orderItems.length === 0) return;
              
              const orderData: Order = {
                payment_method_id: savedPM,
                delivery_type_id: savedDT,
                shipping_address: {
                  name: `${savedForm.first_name} ${savedForm.last_name}`.trim(),
                  first_name: savedForm.first_name,
                  last_name: savedForm.last_name,
                  address: savedForm.address,
                  city: savedForm.city,
                  zip: savedForm.zip,
                  phone: savedForm.phone
                },
                items: orderItems.map((item: any) => ({
                  product_id: item.id,
                  quantity: item.quantity
                })),
                notes: savedForm.notes,
                payment_status: 'paid',
                transaction_id: transactionId,
                coupon_code: savedCoupon?.code
              };

              const response = await api.createOrder(orderData);
              if ((response.status === "success" || (response as any).message === "Order placed successfully") && (response.data?.id || (response as any).order?.id)) {
                const orderId = response.data?.id || (response as any).order?.id;
                setOrderSuccess(orderId);
                clearCart();
                localStorage.removeItem('pending_checkout');
                window.history.replaceState({}, '', window.location.pathname);
                window.scrollTo({ top: 0, behavior: 'smooth' });
              }
            } catch (err) {
              console.error("Failed to process returned payment:", err);
              setError("Payment was successful but we failed to create your order.");
            }
          }
        }
      } else if (status === 'cancel' || status === 'error') {
        setError(searchParams.get('message') || "Payment was cancelled or failed.");
        localStorage.removeItem('pending_checkout');
        window.history.replaceState({}, '', window.location.pathname);
      }
    };

    handleCallback();
  }, [isMounted, clearCart]);

  const TAX_RATE = 0.05; // 5% Tax
  const subtotal = totalPrice;
  const deliveryFee = Number(deliveryTypes.find(d => d.id === selectedDelivery)?.cost || 0);
  const taxFee = subtotal * TAX_RATE;
  const finalTotal = subtotal + deliveryFee + taxFee - (discountAmount || 0);

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

  const sectionVariants = {
    hidden: { opacity: 0, y: 15 },
    visible: {
      opacity: 1,
      y: 0,
      transition: { duration: 0.5 },
    },
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Validation matching Flutter logic
    if (items.length === 0) {
      setError("Your cart is empty");
      return;
    }
    if (!formData.first_name || !formData.last_name || !formData.address || !formData.city) {
      setError("Please fill in all required shipping fields.");
      return;
    }

    if (!formData.zip) {
      setError("ZIP / postal code is required.");
      return;
    }

    const cleanedPhone = formData.phone.replace(/\D/g, "");
    if (!cleanedPhone || cleanedPhone.length !== 11) {
      setError("Phone number must be 11 digits (numbers only).");
      return;
    }
    if (!selectedDelivery) {
      setError("Please select a delivery method.");
      return;
    }
    if (!selectedPayment) {
      setError("Please select a payment method.");
      return;
    }

    setProcessing(true);
    setError(null);

    try {
      // Wallet Payment Logic
      if (selectedPayment === 999) {
        if (Number(walletBalance) < finalTotal) {
          setError("Insufficient wallet balance.");
          setProcessing(false);
          return;
        }
        // Proceed directly as paid
      }

      const paymentMethod = paymentMethods.find(m => m.id === selectedPayment);
      let paymentStatus = 'pending';
      let transactionId = '';

      // Handle Payment Initiation for Testing/Production (Matching Flutter logic)
      if (selectedPayment !== 999 && paymentMethod && paymentMethod.type && paymentMethod.type.toLowerCase() !== 'cod') {
        const type = paymentMethod.type.toLowerCase();
        const callbackUrl = `${window.location.origin}/checkout`;
        
        // console.log("Initiating payment for type:", type);
        
        try {
          const initiationRes = await api.initiatePayment({
            payment_method_id: selectedPayment,
            amount: finalTotal,
            currency: currency === '$' ? 'USD' : currency, // Fallback logic
            callback_url: callbackUrl
          });

          // console.log("Payment initiation response:", initiationRes);

          if (type === 'paypal' && (initiationRes.approval_link || initiationRes.data?.approval_link)) {
            const approvalLink = initiationRes.approval_link || initiationRes.data?.approval_link;
            // Save checkout data to restore after redirect
            const checkoutData = {
              formData,
              selectedPayment,
              selectedDelivery,
              appliedCoupon,
              items // Save items too to avoid race condition on return
            };
            localStorage.setItem('pending_checkout', JSON.stringify(checkoutData));
            
            // Redirect to PayPal
            window.location.href = approvalLink;
            return;
          } else if (type === 'paytm' && (initiationRes.txnToken || initiationRes.data?.txnToken)) {
            const data = initiationRes.data || initiationRes;
            // Save checkout data to restore after redirect
            const checkoutData = {
              formData,
              selectedPayment,
              selectedDelivery,
              appliedCoupon,
              items
            };
            localStorage.setItem('pending_checkout', JSON.stringify(checkoutData));
            
            // Handle Paytm Form Post (Production/Testing URLs)
            const environment = data.environment || 'TEST';
            const actionUrl = environment === 'PROD' 
              ? 'https://securegw.paytm.in/theia/processTransaction'
              : 'https://securegw-stage.paytm.in/theia/processTransaction';
            
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = actionUrl;
            
            const fields = {
              mid: data.mid,
              orderId: data.orderId,
              txnToken: data.txnToken
            };

            Object.entries(fields).forEach(([key, value]) => {
              const input = document.createElement('input');
              input.type = 'hidden';
              input.name = key;
              input.value = value as string;
              form.appendChild(input);
            });

            document.body.appendChild(form);
            form.submit();
            return;
          } else if (type === 'stripe' && (initiationRes.client_secret || initiationRes.data?.client_secret)) {
            const data = initiationRes.data || initiationRes;
            // In a real production app, you would use Stripe Elements or Redirect here
            // For now, we simulate a successful payment as this is often how web-view based payments work in initial testing
            paymentStatus = 'paid';
            transactionId = data.transaction_id || data.payment_intent_id || `stripe_${Date.now()}`;
          } else if (type === 'razorpay' && (initiationRes.razorpay_order_id || initiationRes.data?.razorpay_order_id)) {
            const data = initiationRes.data || initiationRes;
            // Handle Razorpay Checkout
            if ((window as any).Razorpay) {
              const options = {
                key: data.razorpay_key,
                amount: data.amount,
                currency: data.currency || 'INR',
                name: settings?.site_name || "Ready Grocery",
                description: "Order Payment",
                order_id: data.razorpay_order_id,
                handler: async function (response: any) {
                  // Payment successful - now create order on server
                  const orderData: Order = {
                    payment_method_id: selectedPayment,
                    delivery_type_id: selectedDelivery!,
                    shipping_address: {
                      name: `${formData.first_name} ${formData.last_name}`.trim(),
                      first_name: formData.first_name,
                      last_name: formData.last_name,
                      address: formData.address,
                      city: formData.city,
                      zip: formData.zip,
                      phone: formData.phone
                    },
                    items: items.map(item => ({
                      product_id: item.id,
                      quantity: item.quantity
                    })),
                    notes: formData.notes,
                    payment_status: 'paid',
                    transaction_id: response.razorpay_payment_id,
                    coupon_code: appliedCoupon?.code
                  };

                  const createRes = await api.createOrder(orderData);
                  if (createRes.status === "success" || (createRes as any).message === "Order placed successfully") {
                    const orderId = createRes.data?.id || (createRes as any).order?.id;
                    setOrderSuccess(orderId);
                    clearCart();
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                  }
                },
                prefill: {
                  name: `${formData.first_name} ${formData.last_name}`,
                  email: user?.email,
                  contact: formData.phone
                },
                theme: {
                  color: "#2b9d10"
                }
              };
              const rzp = new (window as any).Razorpay(options);
              rzp.open();
              setProcessing(false);
              return;
            } else {
              throw new Error("Razorpay SDK failed to load. Please refresh and try again.");
            }
          }
        } catch (initErr: any) {
          console.error("Payment initiation error:", initErr);
          // If initiation fails, but it's not COD, we should show error
          throw new Error(initErr.message || "Failed to initiate payment");
        }
      }

      const orderData: Order = {
        payment_method_id: selectedPayment,
        delivery_type_id: selectedDelivery,
        shipping_address: {
          name: `${formData.first_name} ${formData.last_name}`.trim(),
          first_name: formData.first_name,
          last_name: formData.last_name,
          address: formData.address,
          city: formData.city,
          zip: formData.zip,
          phone: formData.phone
        },
        items: items.map(item => ({
          product_id: item.id,
          quantity: item.quantity
        })),
        notes: formData.notes,
        payment_status: paymentStatus,
        transaction_id: transactionId,
        coupon_code: appliedCoupon?.code
      };

      const response = await api.createOrder(orderData);
      console.log("Order creation response:", response);

      if ((response.status === "success" || (response as any).message === "Order placed successfully") && (response.data?.id || (response as any).order?.id)) {
        const orderId = response.data?.id || (response as any).order?.id;
        // Professional approach: Save shipping details to user profile for future use
        if (user) {
          try {
            await api.updateProfile({
              name: `${formData.first_name} ${formData.last_name}`.trim(),
              phone: formData.phone,
              address: formData.address,
              city: formData.city,
              zip: formData.zip
            });
          } catch (profileErr) {
            console.warn("Failed to update profile with shipping details:", profileErr);
          }
        }
        
        setOrderSuccess(orderId);
        clearCart();
        // Scroll to top for success message
        window.scrollTo({ top: 0, behavior: 'smooth' });
      } else {
        throw new Error(response.message || "Failed to create order");
      }
    } catch (err: any) {
      console.error("Order submission error:", err);
      setError(err.message || "Failed to place order. Please try again.");
    } finally {
      setProcessing(false);
    }
  };

  if (orderSuccess) {
    return (
      <div className="min-h-screen bg-white flex flex-col relative overflow-hidden">
        <Header />
        <main className="flex-1 container mx-auto px-4 py-12 md:py-20 relative z-10">
          <div className="flex flex-col items-center gap-12 md:gap-16 max-w-4xl mx-auto">
            <div className="w-full relative flex flex-col items-center">
              <div className="text-center space-y-10 relative z-10">
                <motion.div 
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="space-y-6"
                >
                  <motion.div 
                    initial={{ scale: 0.9, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    className="w-16 h-16 md:w-20 md:h-20 bg-primary rounded-2xl flex items-center justify-center mx-auto shadow-lg shadow-primary/10"
                  >
                    <CheckCircle2 className="text-white" size={32} strokeWidth={2.5} />
                  </motion.div>

                  <div className="space-y-3">
                    <h1 className="text-3xl md:text-5xl font-black text-zinc-900 tracking-tight">
                      ORDER <span className="text-primary">SUCCESSFUL</span>
                    </h1>
                    <p className="text-zinc-400 font-bold uppercase tracking-widest text-[10px]">
                      Your order has been placed successfully
                    </p>
                  </div>
                </motion.div>

                {/* Order Info Cards */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4 w-full max-w-2xl mx-auto">
                  <motion.div 
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.2 }}
                    className="bg-white border border-zinc-100 rounded-2xl p-6 flex flex-col items-center gap-3"
                  >
                    <div className="w-10 h-10 rounded-xl flex items-center justify-center border border-zinc-50 bg-zinc-50 text-zinc-900">
                      <ShoppingBag size={18} />
                    </div>
                    <div className="space-y-0.5">
                      <p className="text-[9px] font-black text-zinc-400 uppercase tracking-widest">Order ID</p>
                      <p className="font-bold text-zinc-900 text-base">#{orderSuccess}</p>
                    </div>
                  </motion.div>

                  <motion.div 
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.3 }}
                    className="bg-white border border-zinc-100 rounded-2xl p-6 flex flex-col items-center gap-3"
                  >
                    <div className="w-10 h-10 rounded-xl flex items-center justify-center border border-zinc-50 bg-zinc-50 text-zinc-900">
                      <Truck size={18} />
                    </div>
                    <div className="space-y-0.5">
                      <p className="text-[9px] font-black text-zinc-400 uppercase tracking-widest">Items</p>
                      <p className="font-bold text-zinc-900 text-base">
                        {orderSummary?.items?.length || items.length} items
                      </p>
                    </div>
                  </motion.div>

                  <motion.div 
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.4 }}
                    className="bg-white border border-zinc-100 rounded-2xl p-6 flex flex-col items-center gap-3"
                  >
                    <div className="w-10 h-10 rounded-xl flex items-center justify-center border border-zinc-50 bg-zinc-50 text-zinc-900">
                      <ShieldCheck size={18} />
                    </div>
                    <div className="space-y-0.5">
                      <p className="text-[9px] font-black text-zinc-400 uppercase tracking-widest">Payment</p>
                      <p className="font-bold text-zinc-900 text-base">
                        {orderSummary?.payment_status === "paid" ? "Paid & verified" : "Pending confirmation"}
                      </p>
                    </div>
                  </motion.div>
                </div>

                <motion.div 
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.5 }}
                  className="flex flex-col sm:flex-row gap-4 pt-4 justify-center"
                >
                  <Link 
                    href={`/orders/${orderSuccess}`}
                    className="px-10 h-14 bg-zinc-900 text-white rounded-xl font-black text-[11px] flex items-center justify-center gap-3 transition-all hover:bg-black active:scale-95 shadow-lg shadow-zinc-200"
                  >
                    <span>TRACK THIS ORDER</span>
                    <ChevronRight size={16} />
                  </Link>
                  <Link 
                    href="/" 
                    className="px-10 h-14 bg-primary text-white rounded-xl font-black text-[11px] flex items-center justify-center gap-3 transition-all hover:brightness-95 active:scale-95 shadow-lg shadow-primary/20"
                  >
                    <span>BACK TO SHOPPING</span>
                    <ArrowRight size={16} />
                  </Link>
                </motion.div>
              </div>
            </div>

            {/* Related Products Section */}
            {suggestedProducts.length > 0 && (
              <motion.div 
                initial={{ opacity: 0, y: 30 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true }}
                className="w-full max-w-5xl space-y-10"
              >
                <div className="flex flex-col items-center text-center space-y-3">
                  <div className="flex items-center gap-3">
                    <div className="h-[1.5px] w-6 bg-[#2b9d10]" />
                    <span className="text-[10px] font-black text-[#2b9d10] uppercase tracking-[0.2em]">Recommendations</span>
                    <div className="h-[1.5px] w-6 bg-[#2b9d10]" />
                  </div>
                  <h2 className="text-3xl md:text-4xl font-black text-zinc-900 tracking-tighter">
                    YOU MIGHT <span className="text-zinc-400">ALSO LIKE</span>
                  </h2>
                </div>

                <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 md:gap-8">
                  {suggestedProducts.map((product, idx) => (
                    <motion.div
                      key={product.id}
                      initial={{ opacity: 0, y: 15 }}
                      whileInView={{ opacity: 1, y: 0 }}
                      viewport={{ once: true }}
                      transition={{ delay: idx * 0.1 }}
                      className="transform-gpu"
                    >
                      <ProductCard product={product} />
                    </motion.div>
                  ))}
                </div>

                <div className="flex justify-center">
                  <Link 
                    href="/products"
                    className="group flex items-center gap-3 bg-white border border-zinc-100 px-8 py-4 rounded-2xl font-black text-[10px] text-zinc-900 hover:border-[#2b9d10]/20 transition-all active:scale-95"
                  >
                    DISCOVER MORE
                    <div className="w-8 h-8 bg-zinc-50 rounded-xl flex items-center justify-center text-[#2b9d10] group-hover:bg-[#2b9d10] group-hover:text-white transition-all">
                      <ChevronRight size={16} />
                    </div>
                  </Link>
                </div>
              </motion.div>
            )}

            {/* Next Steps Footer */}
            <motion.div 
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 1.5 }}
              className="mt-8 flex flex-wrap justify-center gap-6 md:gap-12"
            >
              <div className="flex items-center gap-2 opacity-30 grayscale hover:grayscale-0 hover:opacity-100 transition-all duration-500 cursor-default">
                <RotateCcw size={14} />
                <span className="text-[9px] font-black uppercase tracking-widest">7 Days Return</span>
              </div>
              <div className="flex items-center gap-2 opacity-30 grayscale hover:grayscale-0 hover:opacity-100 transition-all duration-500 cursor-default">
                <ShieldCheck size={14} />
                <span className="text-[9px] font-black uppercase tracking-widest">100% Secure</span>
              </div>
              <div className="flex items-center gap-2 opacity-30 grayscale hover:grayscale-0 hover:opacity-100 transition-all duration-500 cursor-default">
                <Truck size={14} />
                <span className="text-[9px] font-black uppercase tracking-widest">Fast Delivery</span>
              </div>
            </motion.div>
          </div>
        </main>
        <Footer />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-white flex flex-col relative">
      <Header />
      
      <main className="flex-1 container mx-auto px-4 py-8 md:py-12 relative z-10">
        {/* Breadcrumb / Progress */}
        <div className="max-w-7xl mx-auto mb-6 md:mb-10">
          <nav className="flex items-center gap-2 text-[9px] font-bold uppercase tracking-[0.15em] text-zinc-400 mb-6">
            <Link href="/" className="hover:text-primary transition-colors">HOME</Link>
            <ChevronRight size={10} />
            <Link href="/cart" className="hover:text-primary transition-colors">CART</Link>
            <ChevronRight size={10} />
            <span className="text-zinc-900">CHECKOUT</span>
          </nav>

          <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
            <div className="space-y-1">
              <h1 className="text-3xl md:text-5xl font-black text-zinc-900 tracking-tighter">
                SECURE <span className="text-primary">CHECKOUT</span>
              </h1>
              <p className="text-[9px] md:text-[10px] font-bold text-zinc-400 uppercase tracking-widest">
                Finalize your order for premium organic goodness
              </p>
            </div>

            {/* Stepper UI - Minimal */}
            <div className="flex items-center gap-2 bg-white p-1 rounded-xl border border-zinc-100">
              {[
                { icon: ShoppingBag, label: "Cart", status: "completed" },
                { icon: MapPin, label: "Shipping", status: "current" },
                { icon: CreditCard, label: "Payment", status: "pending" }
              ].map((step, idx) => (
                <div key={idx} className="flex items-center gap-2 px-3 py-1.5">
                  <div className={cn(
                      "w-6 h-6 rounded-lg flex items-center justify-center transition-all duration-500",
                      step.status === "completed" ? "bg-primary text-white" :
                      step.status === "current" ? "bg-zinc-900 text-white" :
                      "bg-zinc-50 text-zinc-300 border border-zinc-100"
                    )}>
                    <step.icon size={10} strokeWidth={2.5} />
                  </div>
                  <span className={cn(
                    "hidden sm:block text-[8px] font-black uppercase tracking-widest",
                    step.status === "current" ? "text-zinc-900" : "text-zinc-400"
                  )}>{step.label}</span>
                  {idx < 2 && <div className="hidden sm:block w-2 h-[1px] bg-zinc-100 ml-1" />}
                </div>
              ))}
            </div>
          </div>
        </div>

        {loading ? (
          <div className="max-w-7xl mx-auto">
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-12">
              {/* Left Column Skeleton */}
              <div className="lg:col-span-7 space-y-4">
                {/* Form Sections */}
                {[1, 2, 3].map((section) => (
                  <div key={section} className="bg-white p-6 md:p-8 rounded-2xl border border-zinc-100 space-y-6">
                    <div className="flex items-center gap-4">
                      <Skeleton className="w-10 h-10 rounded-xl" />
                      <Skeleton className="h-5 w-32 rounded-lg" />
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                      {[1, 2, 3, 4].map((field) => (
                        <div key={field} className="space-y-2">
                          <Skeleton className="h-2.5 w-16 rounded-full" />
                          <Skeleton className="h-12 w-full rounded-xl" />
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>

              {/* Right Column Skeleton */}
              <div className="lg:col-span-5">
                <div className="sticky top-32">
                  <div className="bg-white p-6 rounded-2xl border border-zinc-100 space-y-6">
                    <Skeleton className="h-6 w-24 rounded-lg" />
                    <div className="space-y-4">
                      {[1, 2, 3].map((item) => (
                        <div key={item} className="flex gap-3">
                          <Skeleton className="w-11 h-11 rounded-lg" />
                          <div className="flex-1 space-y-1.5">
                            <Skeleton className="h-3 w-full rounded-lg" />
                            <Skeleton className="h-2 w-1/2 rounded-lg" />
                          </div>
                        </div>
                      ))}
                    </div>
                    <div className="pt-5 border-t border-zinc-100 space-y-3">
                      <div className="flex justify-between">
                        <Skeleton className="h-2.5 w-14 rounded-full" />
                        <Skeleton className="h-2.5 w-10 rounded-full" />
                      </div>
                      <div className="flex justify-between">
                        <Skeleton className="h-2.5 w-16 rounded-full" />
                        <Skeleton className="h-2.5 w-12 rounded-full" />
                      </div>
                    </div>
                    <Skeleton className="h-16 w-full rounded-xl" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="flex flex-col lg:flex-row gap-8 lg:gap-12 max-w-7xl mx-auto">
            <motion.div 
              variants={containerVariants}
              initial="hidden"
              animate="visible"
              className="flex-1 space-y-4"
            >
              <motion.div variants={sectionVariants} className="bg-white p-6 md:p-8 rounded-2xl border border-zinc-100 relative overflow-hidden group">
                <div className="relative z-10">
                  <div className="flex items-center gap-4 mb-6">
                    <div className="w-10 h-10 bg-zinc-50 text-zinc-900 rounded-xl flex items-center justify-center border border-zinc-100">
                      <MapPin size={18} strokeWidth={2.5} />
                    </div>
                    <div>
                      <h2 className="text-lg font-black text-zinc-900 tracking-tight">Shipping Details</h2>
                      <p className="text-[9px] font-bold text-zinc-400 uppercase tracking-widest mt-0.5">Delivery Address</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                    {[
                      { name: "first_name", label: "First Name", placeholder: "e.g. John", type: "text" },
                      { name: "last_name", label: "Last Name", placeholder: "e.g. Doe", type: "text" },
                      { name: "address", label: "Street Address", placeholder: "123 Street Name, Apt 4B", type: "text", full: true },
                      { name: "city", label: "City", placeholder: "Dhaka", type: "text" },
                      { name: "zip", label: "ZIP Code", placeholder: "1212", type: "text" },
                      { name: "phone", label: "Phone Number", placeholder: "1XXX XXXXXX", type: "tel", prefix: "+880", full: true },
                    ].map((field) => (
                      <div key={field.name} className={cn("space-y-1.5", field.full && "md:col-span-2")}>
                        <label className="text-[9px] font-bold text-zinc-400 uppercase tracking-widest ml-1">
                          {field.label}
                        </label>
                        <div className="relative group/input">
                          {field.prefix && (
                            <span className="absolute left-4 top-1/2 -translate-y-1/2 text-zinc-400 font-black text-[10px] tracking-widest">{field.prefix}</span>
                          )}
                          <input 
                            required 
                            name={field.name} 
                            type={field.type}
                            value={(formData as any)[field.name]} 
                            onChange={handleInputChange} 
                            className={cn(
                              "w-full py-3.5 bg-white border border-zinc-100 focus:border-primary rounded-xl outline-none transition-all font-bold text-sm placeholder:text-zinc-300 placeholder:font-medium shadow-sm shadow-zinc-50/50",
                              field.prefix ? "pl-14 pr-4" : "px-4"
                            )} 
                            placeholder={field.placeholder} 
                          />
                        </div>
                      </div>
                    ))}
                    
                    <div className="md:col-span-2 space-y-1.5">
                      <label className="text-[9px] font-bold text-zinc-400 uppercase tracking-widest ml-1">
                        Order Notes (Optional)
                      </label>
                      <textarea 
                        name="notes" 
                        value={formData.notes} 
                        onChange={handleInputChange} 
                        rows={2}
                        className="w-full px-4 py-3.5 bg-white border border-zinc-100 focus:border-primary rounded-xl outline-none transition-all font-bold text-sm placeholder:text-zinc-300 resize-none shadow-sm shadow-zinc-50/50" 
                        placeholder="Any special instructions for delivery?" 
                      />
                    </div>
                  </div>
                </div>
              </motion.div>

              <motion.div variants={sectionVariants} className="bg-white p-6 md:p-8 rounded-2xl border border-zinc-100 relative overflow-hidden group">
                <div className="relative z-10">
                  <div className="flex items-center gap-4 mb-6">
                    <div className="w-10 h-10 bg-zinc-50 text-zinc-900 rounded-xl flex items-center justify-center border border-zinc-100">
                      <Truck size={18} strokeWidth={2.5} />
                    </div>
                    <div>
                      <h2 className="text-lg font-black text-zinc-900 tracking-tight">Delivery Method</h2>
                      <p className="text-[9px] font-bold text-zinc-400 uppercase tracking-widest mt-0.5">Shipping Speed</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    {deliveryTypes.map((type) => (
                      <div 
                        key={type.id}
                        onClick={() => setSelectedDelivery(type.id)}
                        className={cn(
                          "p-4 rounded-xl border transition-all cursor-pointer relative overflow-hidden flex flex-col gap-2",
                          selectedDelivery === type.id 
                            ? "border-primary bg-white" 
                            : "border-zinc-100 bg-white hover:border-zinc-200"
                        )}
                      >
                        <div className="flex items-center justify-between w-full">
                          <div className={cn(
                            "w-4 h-4 rounded-full border-2 flex items-center justify-center transition-all shrink-0",
                            selectedDelivery === type.id ? "border-primary bg-primary" : "border-zinc-200 bg-white"
                          )}>
                            {selectedDelivery === type.id && <div className="w-1 h-1 bg-white rounded-full" />}
                          </div>
                          <span className={cn(
                            "text-sm font-black tracking-tight",
                            selectedDelivery === type.id ? "text-primary" : "text-zinc-900"
                          )}>{formatMoney(Number(type.cost || 0))}</span>
                        </div>
                        <div>
                          <h3 className="font-black text-zinc-900 text-[13px] tracking-tight">{type.name}</h3>
                          {type.estimated_time && (
                            <p className="text-[8px] font-bold text-zinc-400 uppercase tracking-widest mt-0.5">{type.estimated_time}</p>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </motion.div>

              <motion.div variants={sectionVariants} className="bg-white p-6 md:p-8 rounded-2xl border border-zinc-100 relative overflow-hidden group">
                <div className="relative z-10">
                  <div className="flex items-center gap-4 mb-6">
                    <div className="w-10 h-10 bg-zinc-50 text-zinc-900 rounded-xl flex items-center justify-center border border-zinc-100">
                      <CreditCard size={18} strokeWidth={2.5} />
                    </div>
                    <div>
                      <h2 className="text-lg font-black text-zinc-900 tracking-tight">Payment Method</h2>
                      <p className="text-[9px] font-bold text-zinc-400 uppercase tracking-widest mt-0.5">Secure Payment</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    {paymentMethods.map((method) => (
                      <div 
                        key={method.id}
                        onClick={() => setSelectedPayment(method.id)}
                        className={cn(
                          "p-4 rounded-xl border transition-all cursor-pointer relative overflow-hidden flex flex-col gap-2",
                          selectedPayment === method.id 
                            ? "border-primary bg-white" 
                            : "border-zinc-100 bg-white hover:border-zinc-200"
                        )}
                      >
                        <div className="flex items-center justify-between w-full">
                          <div className={cn(
                            "w-4 h-4 rounded-full border-2 flex items-center justify-center transition-all shrink-0",
                            selectedPayment === method.id ? "border-primary bg-primary" : "border-zinc-200 bg-white"
                          )}>
                            {selectedPayment === method.id && <div className="w-1 h-1 bg-white rounded-full" />}
                          </div>
                          <div className={cn(
                            "w-7 h-7 rounded-lg flex items-center justify-center",
                            selectedPayment === method.id ? "bg-primary text-white" : "bg-zinc-50 text-zinc-400"
                          )}>
                            <CreditCard size={14} />
                          </div>
                        </div>
                        <div>
                          <h3 className="font-black text-zinc-900 text-[13px] tracking-tight">{method.name}</h3>
                          <p className="text-[8px] font-bold text-zinc-400 uppercase tracking-widest mt-0.5">
                            {method.type === 'cod' ? 'PAY UPON DELIVERY' : 'ONLINE TRANSACTION'}
                          </p>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </motion.div>
            </motion.div>

            {/* Right Side: Order Summary */}
            <div className="w-full lg:w-[380px]">
              <motion.div 
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                className="bg-white p-6 rounded-2xl text-zinc-900 lg:sticky lg:top-32 border border-zinc-100 relative overflow-hidden group"
              >
                <div className="relative z-10">
                  <div className="flex items-end justify-between mb-6">
                    <div>
                      <p className="text-[9px] font-black text-primary uppercase tracking-widest mb-1.5">Your Selection</p>
                      <h3 className="text-xl font-black tracking-tight text-zinc-900">SUMMARY</h3>
                    </div>
                    <div className="flex flex-col items-end">
                      <span className="text-[8px] font-black text-zinc-400 uppercase tracking-widest mb-1">Items</span>
                      <div className="px-1.5 py-0.5 bg-zinc-900 text-white rounded text-[9px] font-black">{items.length}</div>
                    </div>
                  </div>
                  
                  {/* Enhanced Item List */}
                  <div className="space-y-3 mb-6 max-h-[250px] overflow-y-auto pr-2 custom-scrollbar">
                    {items.map((item) => {
                      const { image, image_url, imageUrl, iconUrl } = item as any;
                      const displayImage = image || image_url || imageUrl || iconUrl || (item as any).icon_url;
                      
                      return (
                        <div key={item.id} className="flex items-center gap-3 group/item">
                          <div className="relative">
                            <div className="w-11 h-11 bg-zinc-50 rounded-lg flex items-center justify-center shrink-0 border border-zinc-100 overflow-hidden p-1.5">
                              {getImageUrl(displayImage) ? (
                                <img src={getImageUrl(displayImage)!} alt={item.name} className="w-full h-full object-contain" />
                              ) : (
                                <ShoppingBag size={14} className="text-zinc-300" />
                              )}
                            </div>
                            <div className="absolute -top-1 -right-1 w-4 h-4 bg-zinc-900 text-[8px] font-black flex items-center justify-center text-white rounded-md border-2 border-white">
                              {item.quantity}
                            </div>
                          </div>
                          <div className="flex-1 min-w-0">
                            <h4 className="text-[10px] font-black text-zinc-800 truncate uppercase tracking-widest">{item.name}</h4>
                            <p className="text-[8px] font-bold text-zinc-400 uppercase tracking-widest mt-0.5">{formatMoney(item.price)}</p>
                          </div>
                          <span className="text-[11px] font-black text-zinc-900">{formatMoney(item.price * item.quantity)}</span>
                        </div>
                      );
                    })}
                  </div>

                  {/* Refined Pricing Breakdown */}
                  <div className="space-y-2.5 pt-5 border-t border-zinc-100">
                    <div className="flex justify-between items-center">
                      <span className="text-[9px] font-black text-zinc-400 uppercase tracking-widest">Subtotal</span>
                      <span className="text-[11px] font-black text-zinc-600">{formatMoney(subtotal)}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-[9px] font-black text-zinc-400 uppercase tracking-widest">Shipping</span>
                      <span className="text-[11px] font-black text-primary">+ {formatMoney(deliveryFee)}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-[9px] font-black text-zinc-400 uppercase tracking-widest">Tax Estimate</span>
                      <span className="text-[11px] font-black text-zinc-600">+ {formatMoney(taxFee)}</span>
                    </div>
                    
                    <div className="pt-4">
                      <div className="bg-zinc-50 rounded-xl p-5 flex justify-between items-center border border-zinc-100">
                        <div>
                          <span className="block text-[8px] font-black text-zinc-400 uppercase tracking-widest mb-1">Total Payable</span>
                          <div className="flex items-baseline gap-1">
                            <span className="text-2xl font-black text-zinc-900 tracking-tighter tabular-nums leading-none">
                              {formatMoney(finalTotal)}
                            </span>
                          </div>
                        </div>
                        <div className="w-10 h-10 rounded-lg bg-white flex items-center justify-center border border-zinc-100">
                          <ShoppingBag size={18} className="text-zinc-900" />
                        </div>
                      </div>
                    </div>
                  </div>

                  {error && (
                    <motion.div 
                      initial={{ opacity: 0, scale: 0.95 }} 
                      animate={{ opacity: 1, scale: 1 }} 
                      className="mt-6 p-4 bg-red-50 border border-red-100 rounded-xl flex items-center gap-3 text-red-500 text-[9px] font-black uppercase tracking-widest"
                    >
                      <div className="w-6 h-6 bg-red-500 text-white rounded-md flex items-center justify-center shrink-0">
                        <AlertCircle size={14} strokeWidth={3} />
                      </div>
                      {error}
                    </motion.div>
                  )}

                  {/* Professional Payment Button */}
                  <div className="mt-8">
                    <button 
                      type="submit"
                      disabled={processing}
                      className="w-full h-16 bg-primary hover:brightness-105 disabled:bg-zinc-100 disabled:text-zinc-400 text-white rounded-xl font-black text-[11px] tracking-widest transition-all flex items-center justify-center gap-3 relative group overflow-hidden active:scale-[0.98] uppercase cursor-pointer"
                    >
                      {processing ? (
                        <>
                          <Loader2 size={16} className="animate-spin" />
                          PROCESSING
                        </>
                      ) : (
                        <>
                          COMPLETE PURCHASE <ArrowRight size={16} strokeWidth={3} />
                        </>
                      )}
                    </button>
                  </div>

                  {/* Refined Trust Indicators */}
                  <div className="mt-8 flex items-center justify-center gap-6">
                    {[
                      { icon: ShieldCheck, label: "Secure" },
                      { icon: RotateCcw, label: "Returns" },
                      { icon: Truck, label: "Fast" }
                    ].map((item, idx) => (
                      <div key={idx} className="flex items-center gap-1.5">
                        <item.icon size={12} className="text-zinc-300" />
                        <span className="text-[8px] font-black text-zinc-400 uppercase tracking-widest">{item.label}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </motion.div>
            </div>
          </form>
        )}
      </main>

      <Footer />
      
      <style jsx global>{`
        .custom-scrollbar::-webkit-scrollbar {
          width: 4px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
          background: rgba(0, 0, 0, 0.02);
          border-radius: 10px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
          background: rgba(0, 0, 0, 0.05);
          border-radius: 10px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
          background: rgba(0, 0, 0, 0.1);
        }
      `}</style>
    </div>
  );
}
