'use client';

import { useState, useMemo, useEffect, useCallback } from 'react';
import { useAppStore } from '@/lib/store';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { useToast } from '@/hooks/use-toast';
import {
  ArrowLeft,
  ShoppingCart,
  Minus,
  Plus,
  Trash2,
  MapPin,
  Phone,
  CreditCard,
  Truck,
  ShieldCheck,
  CheckCircle2,
  ShoppingBag,
  Banknote,
  ChevronRight,
  Clock,
  Wallet,
  AlertCircle,
} from 'lucide-react';

type CheckoutStep = 'cart' | 'delivery' | 'payment' | 'success';

interface ActiveGateway {
  id: string;
  name: string;
  slug: string;
  type: string;
  icon: string | null;
  description: string | null;
  instructions: string;
  sortOrder: number;
}

export default function CheckoutModule() {
  const { cart, removeFromCart, updateQuantity, clearCart, language, setCurrentSection, user } = useAppStore();
  const { toast } = useToast();
  const [step, setStep] = useState<CheckoutStep>('cart');
  const [deliveryAddress, setDeliveryAddress] = useState('');
  const [deliveryPhone, setDeliveryPhone] = useState('');
  const [deliveryNote, setDeliveryNote] = useState('');
  const [selectedGatewayId, setSelectedGatewayId] = useState<string>('cod');
  const [isPlacingOrder, setIsPlacingOrder] = useState(false);
  const [activeGateways, setActiveGateways] = useState<ActiveGateway[]>([]);
  const [gatewaysLoaded, setGatewaysLoaded] = useState(false);

  // Fetch active payment gateways
  const fetchGateways = useCallback(async () => {
    try {
      const res = await fetch('/api/payment-gateways');
      const data = await res.json();
      if (data.success) {
        setActiveGateways(data.gateways);
      }
    } catch (err) {
      console.error('Failed to fetch payment gateways:', err);
    } finally {
      setGatewaysLoaded(true);
    }
  }, []);

  useEffect(() => { fetchGateways(); }, [fetchGateways]);

  const cartTotal = useMemo(() => {
    return cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
  }, [cart]);

  const cartItemCount = useMemo(() => {
    return cart.reduce((sum, item) => sum + item.quantity, 0);
  }, [cart]);

  const deliveryFee = cartTotal >= 500 ? 0 : 50;
  const totalAmount = cartTotal + deliveryFee;

  // Get the selected gateway object (or null for COD)
  const selectedGateway = useMemo(() => {
    if (selectedGatewayId === 'cod') return null;
    return activeGateways.find(g => g.id === selectedGatewayId) || null;
  }, [selectedGatewayId, activeGateways]);

  // Parse instructions JSON
  const getInstructions = (instructionsStr: string): Record<string, string> | null => {
    try {
      return JSON.parse(instructionsStr || '{}');
    } catch {
      return null;
    }
  };

  // Redirect to home if cart is empty and not on success step
  if (cart.length === 0 && step !== 'success') {
    return (
      <div className="flex min-h-[60vh] flex-col items-center justify-center gap-4 px-4 py-8">
        <div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-primary/10">
          <ShoppingCart className="h-10 w-10 text-primary/50" />
        </div>
        <div className="text-center">
          <h2 className="text-lg font-bold text-foreground">
            {language === 'en' ? 'Your Cart is Empty' : 'আপনার কার্ট খালি'}
          </h2>
          <p className="mt-1 text-sm text-muted-foreground">
            {language === 'en'
              ? 'Add items to your cart to get started'
              : 'শুরু করতে কার্টে পণ্য যোগ করুন'}
          </p>
        </div>
        <Button
          className="bg-primary text-primary-foreground"
          onClick={() => setCurrentSection('marketplace')}
        >
          <ShoppingBag className="mr-2 h-4 w-4" />
          {language === 'en' ? 'Browse Products' : 'পণ্য ব্রাউজ করুন'}
        </Button>
      </div>
    );
  }

  const handlePlaceOrder = async () => {
    if (!deliveryAddress.trim() || !deliveryPhone.trim()) {
      toast({
        title: language === 'en' ? 'Missing Information' : 'তথ্য অসম্পূর্ণ',
        description: language === 'en'
          ? 'Please fill in delivery address and phone number'
          : 'দয়া করে ডেলিভারি ঠিকানা ও ফোন নম্বর দিন',
        variant: 'destructive',
      });
      setStep('delivery');
      return;
    }

    setIsPlacingOrder(true);

    try {
      // Create payment transaction if a gateway is selected (not COD)
      if (selectedGatewayId !== 'cod' && selectedGateway && user?.id) {
        await fetch('/api/payments', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            userId: user.id,
            gatewayId: selectedGateway.id,
            amount: totalAmount,
            currency: 'BDT',
            metadata: {
              cartItems: cart.map(i => ({ productId: i.productId, title: i.title, quantity: i.quantity, price: i.price })),
              deliveryAddress,
              deliveryPhone,
              deliveryNote,
            },
          }),
        });
      }
    } catch (err) {
      console.error('Payment initiation error:', err);
    }

    // Simulate order placement
    await new Promise((resolve) => setTimeout(resolve, 1500));
    setIsPlacingOrder(false);
    clearCart();
    setStep('success');
  };

  // ─── Success Step ───
  if (step === 'success') {
    return (
      <div className="flex min-h-[70vh] flex-col items-center justify-center gap-5 px-4 py-8">
        <div className="flex h-24 w-24 items-center justify-center rounded-full bg-green-100 dark:bg-green-900/30 animate-in zoom-in-50 duration-500">
          <CheckCircle2 className="h-12 w-12 text-green-600 dark:text-green-400" />
        </div>
        <div className="text-center animate-in fade-in slide-in-from-bottom-4 duration-500">
          <h1 className="text-2xl font-bold text-foreground">
            {language === 'en' ? 'Order Placed!' : 'অর্ডার সম্পন্ন!'}
          </h1>
          <p className="mt-2 text-sm text-muted-foreground max-w-xs">
            {language === 'en'
              ? 'Your order has been placed successfully. You will receive a confirmation shortly.'
              : 'আপনার অর্ডার সফলভাবে সম্পন্ন হয়েছে। শীঘ্রই আপনি কনফার্মেশন পাবেন।'}
          </p>
        </div>

        <Card className="w-full max-w-sm border-green-200 bg-green-50/50 dark:border-green-800 dark:bg-green-900/10">
          <CardContent className="p-4 space-y-2">
            <div className="flex items-center justify-between">
              <span className="text-xs text-muted-foreground">
                {language === 'en' ? 'Order ID' : 'অর্ডার আইডি'}
              </span>
              <span className="text-xs font-bold text-foreground">
                #ORD-{Math.floor(Math.random() * 9000 + 1000)}
              </span>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-xs text-muted-foreground">
                {language === 'en' ? 'Payment' : 'পেমেন্ট'}
              </span>
              <span className="text-xs font-medium text-foreground">
                {selectedGatewayId === 'cod'
                  ? (language === 'en' ? 'Cash on Delivery' : 'ক্যাশ অন ডেলিভারি')
                  : selectedGateway?.name || 'Online Payment'}
              </span>
            </div>
            <div className="flex items-center gap-1 text-xs text-primary">
              <Clock className="h-3 w-3" />
              <span>
                {language === 'en'
                  ? 'Estimated delivery: 30-60 minutes'
                  : 'আনুমানিক ডেলিভারি: ৩০-৬০ মিনিট'}
              </span>
            </div>
          </CardContent>
        </Card>

        <div className="flex gap-3 w-full max-w-sm">
          <Button
            variant="outline"
            className="flex-1 border-primary text-primary"
            onClick={() => setCurrentSection('orders')}
          >
            {language === 'en' ? 'View Orders' : 'অর্ডার দেখুন'}
          </Button>
          <Button
            className="flex-1 bg-primary text-primary-foreground"
            onClick={() => setCurrentSection('home')}
          >
            {language === 'en' ? 'Back to Home' : 'হোমে যান'}
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-4 px-4 py-4 pb-24">
      {/* Header */}
      <div className="flex items-center gap-3">
        <Button
          variant="ghost"
          size="icon"
          onClick={() => {
            if (step === 'cart') {
              setCurrentSection('home');
            } else if (step === 'delivery') {
              setStep('cart');
            } else if (step === 'payment') {
              setStep('delivery');
            }
          }}
          className="shrink-0"
        >
          <ArrowLeft className="h-5 w-5" />
        </Button>
        <div className="flex-1">
          <h1 className="text-xl font-bold text-foreground">
            {step === 'cart' && (language === 'en' ? 'My Cart' : 'আমার কার্ট')}
            {step === 'delivery' && (language === 'en' ? 'Delivery Details' : 'ডেলিভারি তথ্য')}
            {step === 'payment' && (language === 'en' ? 'Payment' : 'পেমেন্ট')}
          </h1>
          <p className="text-xs text-muted-foreground">
            {step === 'cart' && `${cartItemCount} ${language === 'en' ? 'items' : 'আইটেম'}`}
            {step === 'delivery' && (language === 'en' ? 'Where should we deliver?' : 'কোথায় ডেলিভারি করব?')}
            {step === 'payment' && (language === 'en' ? 'Choose payment method' : 'পেমেন্ট পদ্ধতি বেছে নিন')}
          </p>
        </div>
      </div>

      {/* Step Indicator */}
      <div className="flex items-center gap-1">
        {(['cart', 'delivery', 'payment'] as CheckoutStep[]).map((s, i) => (
          <div key={s} className="flex items-center gap-1 flex-1">
            <div
              className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-xs font-bold transition-colors ${
                step === s
                  ? 'bg-primary text-primary-foreground'
                  : i < ['cart', 'delivery', 'payment'].indexOf(step)
                  ? 'bg-green-500 text-white'
                  : 'bg-muted text-muted-foreground'
              }`}
            >
              {i < ['cart', 'delivery', 'payment'].indexOf(step) ? (
                <CheckCircle2 className="h-4 w-4" />
              ) : (
                i + 1
              )}
            </div>
            {i < 2 && (
              <div
                className={`h-0.5 flex-1 rounded-full transition-colors ${
                  i < ['cart', 'delivery', 'payment'].indexOf(step)
                    ? 'bg-green-500'
                    : 'bg-muted'
                }`}
              />
            )}
          </div>
        ))}
      </div>

      {/* ─── Cart Step ─── */}
      {step === 'cart' && (
        <>
          <div className="space-y-3">
            {cart.map((item) => (
              <Card key={item.productId} className="border-border/50 bg-card">
                <CardContent className="p-3">
                  <div className="flex gap-3">
                    {/* Product Image */}
                    <div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-primary/20 to-primary/5">
                      <ShoppingBag className="h-7 w-7 text-primary/60" />
                    </div>

                    <div className="flex flex-1 flex-col justify-between">
                      <div className="flex items-start justify-between gap-2">
                        <h4 className="text-sm font-semibold text-foreground line-clamp-2 leading-tight">
                          {item.title}
                        </h4>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive"
                          onClick={() => removeFromCart(item.productId)}
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </Button>
                      </div>

                      {item.unit && (
                        <p className="text-[10px] text-muted-foreground">{item.unit}</p>
                      )}

                      <div className="flex items-center justify-between mt-1">
                        <div className="flex items-center gap-2">
                          <Button
                            variant="outline"
                            size="icon"
                            className="h-7 w-7 rounded-md"
                            onClick={() =>
                              updateQuantity(item.productId, Math.max(1, item.quantity - 1))
                            }
                          >
                            <Minus className="h-3 w-3" />
                          </Button>
                          <span className="w-6 text-center text-sm font-bold">
                            {item.quantity}
                          </span>
                          <Button
                            variant="outline"
                            size="icon"
                            className="h-7 w-7 rounded-md"
                            onClick={() => updateQuantity(item.productId, item.quantity + 1)}
                          >
                            <Plus className="h-3 w-3" />
                          </Button>
                        </div>
                        <span className="text-base font-bold text-primary">
                          ৳{item.price * item.quantity}
                        </span>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {/* Free delivery banner */}
          <Card className={`border-0 ${cartTotal >= 500 ? 'bg-green-50 dark:bg-green-900/10' : 'bg-amber-50 dark:bg-amber-900/10'}`}>
            <CardContent className="flex items-center gap-3 p-3">
              <Truck className={`h-5 w-5 shrink-0 ${cartTotal >= 500 ? 'text-green-600 dark:text-green-400' : 'text-amber-600 dark:text-amber-400'}`} />
              <div className="flex-1">
                <p className={`text-xs font-semibold ${cartTotal >= 500 ? 'text-green-700 dark:text-green-300' : 'text-amber-700 dark:text-amber-300'}`}>
                  {cartTotal >= 500
                    ? language === 'en'
                      ? 'You get FREE delivery! 🎉'
                      : 'আপনি ফ্রি ডেলিভারি পাচ্ছেন! 🎉'
                    : language === 'en'
                    ? `Add ৳${500 - cartTotal} more for FREE delivery`
                    : `ফ্রি ডেলিভারির জন্য আরও ৳${500 - cartTotal} যোগ করুন`}
                </p>
              </div>
            </CardContent>
          </Card>

          {/* Price Summary */}
          <Card className="border-primary/10 bg-card">
            <CardContent className="p-4 space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">
                  {language === 'en' ? 'Subtotal' : 'সাবটোটাল'}
                </span>
                <span className="text-sm font-medium text-foreground">৳{cartTotal}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">
                  {language === 'en' ? 'Delivery Fee' : 'ডেলিভারি ফি'}
                </span>
                <span className={`text-sm font-medium ${deliveryFee === 0 ? 'text-green-600' : 'text-foreground'}`}>
                  {deliveryFee === 0
                    ? language === 'en' ? 'FREE' : 'ফ্রি'
                    : `৳${deliveryFee}`}
                </span>
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <span className="text-base font-bold text-foreground">
                  {language === 'en' ? 'Total' : 'মোট'}
                </span>
                <span className="text-lg font-bold text-primary">৳{totalAmount}</span>
              </div>
            </CardContent>
          </Card>

          {/* Clear Cart */}
          <button
            onClick={clearCart}
            className="w-full text-center text-xs text-muted-foreground hover:text-destructive transition-colors py-1"
          >
            {language === 'en' ? 'Clear Cart' : 'কার্ট মুছুন'}
          </button>

          {/* Continue Button */}
          <Button
            className="w-full bg-primary font-bold text-primary-foreground hover:bg-primary/90 h-12 text-base"
            onClick={() => setStep('delivery')}
          >
            {language === 'en' ? 'Continue to Delivery' : 'ডেলিভারিতে যান'}
            <ChevronRight className="ml-1 h-4 w-4" />
          </Button>
        </>
      )}

      {/* ─── Delivery Step ─── */}
      {step === 'delivery' && (
        <>
          <Card className="border-primary/10 bg-card">
            <CardContent className="p-4 space-y-4">
              <div className="flex items-center gap-2">
                <MapPin className="h-5 w-5 text-primary" />
                <h3 className="text-sm font-bold text-foreground">
                  {language === 'en' ? 'Delivery Address' : 'ডেলিভারি ঠিকানা'}
                </h3>
              </div>
              <Input
                placeholder={language === 'en' ? 'Enter your full address' : 'আপনার সম্পূর্ণ ঠিকানা লিখুন'}
                value={deliveryAddress}
                onChange={(e) => setDeliveryAddress(e.target.value)}
                className="rounded-xl"
              />

              <div className="flex items-center gap-2">
                <Phone className="h-5 w-5 text-primary" />
                <h3 className="text-sm font-bold text-foreground">
                  {language === 'en' ? 'Phone Number' : 'ফোন নম্বর'}
                </h3>
              </div>
              <Input
                placeholder={language === 'en' ? '01XXXXXXXXX' : '০১XXXXXXXXX'}
                value={deliveryPhone}
                onChange={(e) => setDeliveryPhone(e.target.value)}
                className="rounded-xl"
                type="tel"
              />

              <div className="flex items-center gap-2">
                <Truck className="h-5 w-5 text-primary" />
                <h3 className="text-sm font-bold text-foreground">
                  {language === 'en' ? 'Delivery Note (Optional)' : 'ডেলিভারি নোট (ঐচ্ছিক)'}
                </h3>
              </div>
              <Input
                placeholder={language === 'en' ? 'Any special instructions...' : 'বিশেষ নির্দেশনা...'}
                value={deliveryNote}
                onChange={(e) => setDeliveryNote(e.target.value)}
                className="rounded-xl"
              />
            </CardContent>
          </Card>

          {/* Delivery Estimate */}
          <Card className="border-primary/10 bg-primary/5">
            <CardContent className="flex items-center gap-3 p-3">
              <Clock className="h-5 w-5 text-primary shrink-0" />
              <div>
                <p className="text-xs font-semibold text-foreground">
                  {language === 'en' ? 'Estimated Delivery' : 'আনুমানিক ডেলিভারি'}
                </p>
                <p className="text-xs text-muted-foreground">
                  {language === 'en' ? '30-60 minutes' : '৩০-৬০ মিনিট'}
                </p>
              </div>
            </CardContent>
          </Card>

          <Button
            className="w-full bg-primary font-bold text-primary-foreground hover:bg-primary/90 h-12 text-base"
            onClick={() => {
              if (!deliveryAddress.trim() || !deliveryPhone.trim()) {
                toast({
                  title: language === 'en' ? 'Missing Information' : 'তথ্য অসম্পূর্ণ',
                  description: language === 'en'
                    ? 'Please fill in delivery address and phone number'
                    : 'দয়া করে ডেলিভারি ঠিকানা ও ফোন নম্বর দিন',
                  variant: 'destructive',
                });
                return;
              }
              setStep('payment');
            }}
          >
            {language === 'en' ? 'Continue to Payment' : 'পেমেন্টে যান'}
            <ChevronRight className="ml-1 h-4 w-4" />
          </Button>
        </>
      )}

      {/* ─── Payment Step ─── */}
      {step === 'payment' && (
        <>
          <div className="space-y-3">
            {/* Cash on Delivery - always available */}
            <Card
              className={`cursor-pointer transition-all duration-200 ${
                selectedGatewayId === 'cod'
                  ? 'border-primary bg-primary/5 shadow-md'
                  : 'border-border/50 bg-card hover:border-primary/20'
              }`}
              onClick={() => setSelectedGatewayId('cod')}
            >
              <CardContent className="flex items-center gap-3 p-4">
                <div className={`flex h-10 w-10 items-center justify-center rounded-xl ${
                  selectedGatewayId === 'cod' ? 'bg-primary text-primary-foreground' : 'bg-primary/10'
                }`}>
                  <Banknote className="h-5 w-5" />
                </div>
                <div className="flex-1">
                  <h4 className="text-sm font-bold text-foreground">
                    {language === 'en' ? 'Cash on Delivery' : 'ক্যাশ অন ডেলিভারি'}
                  </h4>
                  <p className="text-[10px] text-muted-foreground">
                    {language === 'en' ? 'Pay when you receive' : 'ডেলিভারিতে পেমেন্ট করুন'}
                  </p>
                </div>
                <div className={`h-5 w-5 rounded-full border-2 flex items-center justify-center ${
                  selectedGatewayId === 'cod'
                    ? 'border-primary bg-primary'
                    : 'border-muted-foreground/30'
                }`}>
                  {selectedGatewayId === 'cod' && (
                    <CheckCircle2 className="h-3 w-3 text-primary-foreground" />
                  )}
                </div>
              </CardContent>
            </Card>

            {/* Dynamic payment gateways from database */}
            {!gatewaysLoaded ? (
              <div className="flex items-center justify-center py-6">
                <span className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
              </div>
            ) : activeGateways.length === 0 ? (
              <Card className="border-dashed">
                <CardContent className="flex items-center gap-3 p-4">
                  <AlertCircle className="h-5 w-5 text-muted-foreground" />
                  <p className="text-xs text-muted-foreground">
                    {language === 'en'
                      ? 'No online payment methods available'
                      : 'কোনো অনলাইন পেমেন্ট পদ্ধতি উপলব্ধ নেই'}
                  </p>
                </CardContent>
              </Card>
            ) : (
              activeGateways.map((gateway) => {
                const isSelected = selectedGatewayId === gateway.id;
                const instructions = getInstructions(gateway.instructions);

                return (
                  <Card
                    key={gateway.id}
                    className={`cursor-pointer transition-all duration-200 ${
                      isSelected
                        ? 'border-primary bg-primary/5 shadow-md'
                        : 'border-border/50 bg-card hover:border-primary/20'
                    }`}
                    onClick={() => setSelectedGatewayId(gateway.id)}
                  >
                    <CardContent className="p-4">
                      <div className="flex items-center gap-3">
                        <div className={`flex h-10 w-10 items-center justify-center rounded-xl text-lg ${
                          isSelected ? 'bg-primary/10' : 'bg-muted'
                        }`}>
                          {gateway.icon || <Wallet className="h-5 w-5 text-muted-foreground" />}
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <h4 className="text-sm font-bold text-foreground">{gateway.name}</h4>
                            <Badge variant="outline" className="text-[9px]">
                              {gateway.type === 'mobile_banking' && (language === 'en' ? 'Mobile' : 'মোবাইল')}
                              {gateway.type === 'card' && (language === 'en' ? 'Card' : 'কার্ড')}
                              {gateway.type === 'crypto' && (language === 'en' ? 'Crypto' : 'ক্রিপ্টো')}
                              {gateway.type === 'digital_wallet' && (language === 'en' ? 'Wallet' : 'ওয়ালেট')}
                              {gateway.type === 'custom' && (language === 'en' ? 'Custom' : 'কাস্টম')}
                            </Badge>
                          </div>
                          {gateway.description && (
                            <p className="text-[10px] text-muted-foreground mt-0.5 line-clamp-1">
                              {gateway.description}
                            </p>
                          )}
                        </div>
                        <div className={`h-5 w-5 rounded-full border-2 flex items-center justify-center ${
                          isSelected
                            ? 'border-primary bg-primary'
                            : 'border-muted-foreground/30'
                        }`}>
                          {isSelected && (
                            <CheckCircle2 className="h-3 w-3 text-primary-foreground" />
                          )}
                        </div>
                      </div>

                      {/* Show payment instructions when selected */}
                      {isSelected && instructions && Object.keys(instructions).length > 0 && (
                        <div className="mt-3 rounded-lg bg-accent/30 p-3 border border-primary/10">
                          <p className="text-[10px] font-semibold text-foreground mb-1.5">
                            {language === 'en' ? 'Payment Instructions' : 'পেমেন্ট নির্দেশনা'}
                          </p>
                          <div className="space-y-1">
                            {Object.entries(instructions).map(([key, value]) => (
                              <div key={key} className="flex items-center gap-1.5 text-xs">
                                <span className="font-medium text-foreground capitalize">{key}:</span>
                                <span className="text-muted-foreground">{String(value)}</span>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                    </CardContent>
                  </Card>
                );
              })
            )}
          </div>

          {/* Order Summary */}
          <Card className="border-primary/10 bg-card">
            <CardContent className="p-4 space-y-2">
              <h3 className="text-sm font-bold text-foreground flex items-center gap-2">
                <ShoppingCart className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Order Summary' : 'অর্ডার সারসংক্ষেপ'}
              </h3>
              <Separator />
              <div className="space-y-1.5">
                {cart.map((item) => (
                  <div key={item.productId} className="flex items-center justify-between">
                    <span className="text-xs text-muted-foreground line-clamp-1 flex-1">
                      {item.title} × {item.quantity}
                    </span>
                    <span className="text-xs font-medium text-foreground ml-2">
                      ৳{item.price * item.quantity}
                    </span>
                  </div>
                ))}
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">
                  {language === 'en' ? 'Subtotal' : 'সাবটোটাল'}
                </span>
                <span className="text-sm font-medium text-foreground">৳{cartTotal}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">
                  {language === 'en' ? 'Delivery' : 'ডেলিভারি'}
                </span>
                <span className={`text-sm font-medium ${deliveryFee === 0 ? 'text-green-600' : 'text-foreground'}`}>
                  {deliveryFee === 0
                    ? language === 'en' ? 'FREE' : 'ফ্রি'
                    : `৳${deliveryFee}`}
                </span>
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <span className="text-base font-bold text-foreground">
                  {language === 'en' ? 'Total' : 'মোট'}
                </span>
                <span className="text-lg font-bold text-primary">৳{totalAmount}</span>
              </div>
            </CardContent>
          </Card>

          {/* Delivery Address Summary */}
          <Card className="border-primary/10 bg-card">
            <CardContent className="p-4 space-y-1.5">
              <h3 className="text-sm font-bold text-foreground flex items-center gap-2">
                <MapPin className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Deliver To' : 'ডেলিভারি ঠিকানা'}
              </h3>
              <p className="text-xs text-muted-foreground">{deliveryAddress}</p>
              <p className="text-xs text-muted-foreground">{deliveryPhone}</p>
              {deliveryNote && (
                <p className="text-xs text-primary/70 italic">{deliveryNote}</p>
              )}
            </CardContent>
          </Card>

          {/* Secure Payment Badge */}
          <div className="flex items-center justify-center gap-1.5 text-xs text-muted-foreground">
            <ShieldCheck className="h-3.5 w-3.5 text-green-600" />
            <span>{language === 'en' ? 'Secure & Encrypted Payment' : 'নিরাপদ ও এনক্রিপ্টেড পেমেন্ট'}</span>
          </div>

          {/* Place Order Button */}
          <Button
            className="w-full bg-primary font-bold text-primary-foreground hover:bg-primary/90 h-12 text-base"
            onClick={handlePlaceOrder}
            disabled={isPlacingOrder}
          >
            {isPlacingOrder ? (
              <div className="flex items-center gap-2">
                <div className="h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />
                {language === 'en' ? 'Placing Order...' : 'অর্ডার হচ্ছে...'}
              </div>
            ) : (
              <>
                {language === 'en' ? 'Place Order' : 'অর্ডার করুন'} · ৳{totalAmount}
              </>
            )}
          </Button>
        </>
      )}
    </div>
  );
}
