import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useCartStore } from '@/lib/cart/store';
import { useCheckoutSettings } from '@/hooks/useAppearanceSettings';
import { Button } from '@/components/ui/button';
import Container from '@/components/Layout/Container';
import { formatPrice } from '@/lib/currency';
import { ArrowLeft, ShoppingBag, MapPin, Check, Edit2 } from 'lucide-react';
import { toast } from 'sonner';
import { apiClient } from '@/lib/api/client';
import { api } from '@/lib/api/client';
import { AddressSelector } from '@/components/AddressSelector';

interface SavedAddress {
  id: number;
  label: string;
  type: 'billing' | 'shipping' | 'both';
  first_name: string;
  last_name: string;
  company?: string;
  address_1: string;
  address_2?: string;
  city: string;
  state: string;
  postcode: string;
  country: string;
  email?: string;
  phone?: string;
  is_default: boolean;
}

export default function Checkout() {
  const navigate = useNavigate();
  const { cart } = useCartStore();
  const { layout, elements } = useCheckoutSettings();
  const [isProcessing, setIsProcessing] = useState(false);
  const user = (window as any).woonoowCustomer?.user;

  // Check if cart contains only virtual/downloadable products
  const isVirtualOnly = React.useMemo(() => {
    if (cart.items.length === 0) return false;
    return cart.items.every(item => item.virtual || item.downloadable);
  }, [cart.items]);

  // Calculate totals
  const subtotal = cart.items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
  const shipping = isVirtualOnly ? 0 : 0; // No shipping for virtual products
  const tax = 0; // TODO: Calculate tax
  const total = subtotal + shipping + tax;

  // Form state
  const [billingData, setBillingData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    address: '',
    city: '',
    state: '',
    postcode: '',
    country: '',
  });

  const [shippingData, setShippingData] = useState({
    firstName: '',
    lastName: '',
    address: '',
    city: '',
    state: '',
    postcode: '',
    country: '',
  });

  const [shipToDifferentAddress, setShipToDifferentAddress] = useState(false);
  const [orderNotes, setOrderNotes] = useState('');
  const [paymentMethod, setPaymentMethod] = useState(isVirtualOnly ? 'bacs' : 'cod');

  // Saved addresses
  const [savedAddresses, setSavedAddresses] = useState<SavedAddress[]>([]);
  const [selectedBillingAddressId, setSelectedBillingAddressId] = useState<number | null>(null);
  const [selectedShippingAddressId, setSelectedShippingAddressId] = useState<number | null>(null);
  const [loadingAddresses, setLoadingAddresses] = useState(true);
  const [showBillingModal, setShowBillingModal] = useState(false);
  const [showShippingModal, setShowShippingModal] = useState(false);
  const [showBillingForm, setShowBillingForm] = useState(true);
  const [showShippingForm, setShowShippingForm] = useState(true);

  // Load saved addresses
  useEffect(() => {
    const loadAddresses = async () => {
      if (!user?.isLoggedIn) {
        setLoadingAddresses(false);
        return;
      }

      try {
        const addresses = await api.get<SavedAddress[]>('/account/addresses');
        setSavedAddresses(addresses);

        // Auto-select default addresses
        const defaultBilling = addresses.find(a => a.is_default && (a.type === 'billing' || a.type === 'both'));
        const defaultShipping = addresses.find(a => a.is_default && (a.type === 'shipping' || a.type === 'both'));

        if (defaultBilling) {
          setSelectedBillingAddressId(defaultBilling.id);
          fillBillingFromAddress(defaultBilling);
          setShowBillingForm(false); // Hide form when default address is auto-selected
        }
        if (defaultShipping && !isVirtualOnly) {
          setSelectedShippingAddressId(defaultShipping.id);
          fillShippingFromAddress(defaultShipping);
          setShowShippingForm(false); // Hide form when default address is auto-selected
        }
      } catch (error) {
        console.error('Failed to load addresses:', error);
      } finally {
        setLoadingAddresses(false);
      }
    };

    loadAddresses();
  }, [user, isVirtualOnly]);

  // Helper functions to fill forms from saved addresses
  const fillBillingFromAddress = (address: SavedAddress) => {
    setBillingData({
      firstName: address.first_name,
      lastName: address.last_name,
      email: address.email || billingData.email,
      phone: address.phone || billingData.phone,
      address: address.address_1,
      city: address.city,
      state: address.state,
      postcode: address.postcode,
      country: address.country,
    });
  };

  const fillShippingFromAddress = (address: SavedAddress) => {
    setShippingData({
      firstName: address.first_name,
      lastName: address.last_name,
      address: address.address_1,
      city: address.city,
      state: address.state,
      postcode: address.postcode,
      country: address.country,
    });
  };

  const handleSelectBillingAddress = (address: SavedAddress) => {
    setSelectedBillingAddressId(address.id);
    fillBillingFromAddress(address);
    setShowBillingForm(false); // Hide form when address is selected
  };

  const handleSelectShippingAddress = (address: SavedAddress) => {
    setSelectedShippingAddressId(address.id);
    fillShippingFromAddress(address);
    setShowShippingForm(false); // Hide form when address is selected
  };

  // Auto-fill form with user data if logged in
  useEffect(() => {
    if (user?.isLoggedIn && user?.billing && savedAddresses.length === 0) {
      setBillingData({
        firstName: user.billing.first_name || '',
        lastName: user.billing.last_name || '',
        email: user.billing.email || user.email || '',
        phone: user.billing.phone || '',
        address: user.billing.address_1 || '',
        city: user.billing.city || '',
        state: user.billing.state || '',
        postcode: user.billing.postcode || '',
        country: user.billing.country || '',
      });
    }

    if (user?.isLoggedIn && user?.shipping) {
      setShippingData({
        firstName: user.shipping.first_name || '',
        lastName: user.shipping.last_name || '',
        address: user.shipping.address_1 || '',
        city: user.shipping.city || '',
        state: user.shipping.state || '',
        postcode: user.shipping.postcode || '',
        country: user.shipping.country || '',
      });
    }
  }, [user]);

  const handlePlaceOrder = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsProcessing(true);

    try {
      // Prepare order data
      const orderData = {
        items: cart.items.map(item => ({
          product_id: item.product_id,
          variation_id: item.variation_id,
          qty: item.quantity,
          meta: item.attributes ? Object.entries(item.attributes).map(([key, value]) => ({
            key,
            value
          })) : []
        })),
        billing: {
          first_name: billingData.firstName,
          last_name: billingData.lastName,
          email: billingData.email,
          phone: billingData.phone,
          address_1: billingData.address,
          city: billingData.city,
          state: billingData.state,
          postcode: billingData.postcode,
          country: billingData.country,
        },
        shipping: shipToDifferentAddress ? {
          first_name: shippingData.firstName,
          last_name: shippingData.lastName,
          address_1: shippingData.address,
          city: shippingData.city,
          state: shippingData.state,
          postcode: shippingData.postcode,
          country: shippingData.country,
          ship_to_different: true,
        } : {
          ship_to_different: false,
        },
        payment_method: paymentMethod,
        customer_note: orderNotes,
      };

      // Submit order
      const response = await apiClient.post('/checkout/submit', orderData);
      const data = (response as any).data || response;

      if (data.ok && data.order_id) {
        // Clear cart - use store method directly
        useCartStore.getState().clearCart();

        toast.success('Order placed successfully!');
        navigate(`/order-received/${data.order_id}?key=${data.order_key}`);
      } else {
        throw new Error(data.error || 'Failed to create order');
      }
    } catch (error: any) {
      toast.error(error.message || 'Failed to place order');
      console.error('Order creation error:', error);
    } finally {
      setIsProcessing(false);
    }
  };

  // Empty cart redirect
  if (cart.items.length === 0) {
    return (
      <Container>
        <div className="text-center py-16">
          <ShoppingBag className="mx-auto h-16 w-16 text-gray-400 mb-4" />
          <h2 className="text-2xl font-bold mb-2">Your cart is empty</h2>
          <p className="text-gray-600 mb-6">Add some products before checking out!</p>
          <Button onClick={() => navigate('/shop')}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Continue Shopping
          </Button>
        </div>
      </Container>
    );
  }

  return (
    <Container>
      <div className="py-8">
        {/* Header */}
        <div className="mb-8">
          <Button variant="ghost" onClick={() => navigate('/cart')} className="mb-4">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Cart
          </Button>
          <h1 className="text-3xl font-bold">Checkout</h1>
        </div>

        <form onSubmit={handlePlaceOrder}>
          <div className={`grid gap-8 ${layout.style === 'single-column' ? 'grid-cols-1' : layout.order_summary === 'top' ? 'grid-cols-1' : 'lg:grid-cols-3'}`}>
            {/* Billing & Shipping Forms */}
            <div className={`space-y-6 ${layout.style === 'single-column' || layout.order_summary === 'top' ? '' : 'lg:col-span-2'}`}>
              {/* Selected Billing Address Summary */}
              {!loadingAddresses && savedAddresses.length > 0 && savedAddresses.some(a => a.type === 'billing' || a.type === 'both') && (
                <div className="bg-white border rounded-lg p-6">
                  <div className="flex items-center justify-between mb-4">
                    <h2 className="text-xl font-bold flex items-center gap-2">
                      <MapPin className="w-5 h-5" />
                      Billing Address
                    </h2>
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={() => setShowBillingModal(true)}
                      className="flex items-center gap-2"
                    >
                      <Edit2 className="w-4 h-4" />
                      Change Address
                    </Button>
                  </div>

                  {selectedBillingAddressId ? (
                    (() => {
                      const selected = savedAddresses.find(a => a.id === selectedBillingAddressId);
                      return selected ? (
                        <div>
                          <div className="bg-primary/5 border-2 border-primary rounded-lg p-4">
                            <div className="flex items-center gap-2 mb-2">
                              <p className="font-semibold">{selected.label}</p>
                              {selected.is_default && (
                                <span className="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded">Default</span>
                              )}
                            </div>
                            <p className="text-sm font-medium text-gray-900">{selected.first_name} {selected.last_name}</p>
                            {selected.phone && <p className="text-sm text-gray-600">{selected.phone}</p>}
                            <p className="text-sm text-gray-600 mt-2">{selected.address_1}</p>
                            {selected.address_2 && <p className="text-sm text-gray-600">{selected.address_2}</p>}
                            <p className="text-sm text-gray-600">{selected.city}, {selected.state} {selected.postcode}</p>
                            <p className="text-sm text-gray-600">{selected.country}</p>
                          </div>
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => setShowBillingForm(true)}
                            className="mt-3 text-primary hover:text-primary"
                          >
                            Use a different address
                          </Button>
                        </div>
                      ) : null;
                    })()
                  ) : (
                    <p className="text-gray-500 text-sm">No address selected</p>
                  )}
                </div>
              )}

              {/* Billing Address Modal */}
              <AddressSelector
                isOpen={showBillingModal}
                onClose={() => setShowBillingModal(false)}
                addresses={savedAddresses}
                selectedAddressId={selectedBillingAddressId}
                onSelectAddress={handleSelectBillingAddress}
                type="billing"
              />

              {/* Billing Details Form - Only show if no saved address selected or user wants to enter manually */}
              {(savedAddresses.length === 0 || !selectedBillingAddressId || showBillingForm) && (
                <div className="bg-white border rounded-lg p-6">
                  <h2 className="text-xl font-bold mb-4">Billing Details</h2>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium mb-2">First Name *</label>
                      <input
                        type="text"
                        required
                        value={billingData.firstName}
                        onChange={(e) => setBillingData({ ...billingData, firstName: e.target.value })}
                        className="w-full border rounded-lg px-4 py-2"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-2">Last Name *</label>
                      <input
                        type="text"
                        required
                        value={billingData.lastName}
                        onChange={(e) => setBillingData({ ...billingData, lastName: e.target.value })}
                        className="w-full border rounded-lg px-4 py-2"
                      />
                    </div>
                    <div className="md:col-span-2">
                      <label className="block text-sm font-medium mb-2">Email Address *</label>
                      <input
                        type="email"
                        required
                        value={billingData.email}
                        onChange={(e) => setBillingData({ ...billingData, email: e.target.value })}
                        className="w-full border rounded-lg px-4 py-2"
                      />
                    </div>
                    <div className="md:col-span-2">
                      <label className="block text-sm font-medium mb-2">Phone *</label>
                      <input
                        type="tel"
                        required
                        value={billingData.phone}
                        onChange={(e) => setBillingData({ ...billingData, phone: e.target.value })}
                        className="w-full border rounded-lg px-4 py-2"
                      />
                    </div>

                    {/* Address fields - only for physical products */}
                    {!isVirtualOnly && (
                      <>
                        <div className="md:col-span-2">
                          <label className="block text-sm font-medium mb-2">Street Address *</label>
                          <input
                            type="text"
                            required
                            value={billingData.address}
                            onChange={(e) => setBillingData({ ...billingData, address: e.target.value })}
                            className="w-full border rounded-lg px-4 py-2"
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium mb-2">City *</label>
                          <input
                            type="text"
                            required
                            value={billingData.city}
                            onChange={(e) => setBillingData({ ...billingData, city: e.target.value })}
                            className="w-full border rounded-lg px-4 py-2"
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium mb-2">State / Province *</label>
                          <input
                            type="text"
                            required
                            value={billingData.state}
                            onChange={(e) => setBillingData({ ...billingData, state: e.target.value })}
                            className="w-full border rounded-lg px-4 py-2"
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium mb-2">Postcode / ZIP *</label>
                          <input
                            type="text"
                            required
                            value={billingData.postcode}
                            onChange={(e) => setBillingData({ ...billingData, postcode: e.target.value })}
                            className="w-full border rounded-lg px-4 py-2"
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium mb-2">Country *</label>
                          <input
                            type="text"
                            required
                            value={billingData.country}
                            onChange={(e) => setBillingData({ ...billingData, country: e.target.value })}
                            className="w-full border rounded-lg px-4 py-2"
                          />
                        </div>
                      </>
                    )}
                  </div>
                </div>
              )}

              {/* Ship to Different Address - only for physical products */}
              {!isVirtualOnly && (
                <div className="bg-white border rounded-lg p-6">
                  <label className="flex items-center gap-2 mb-4">
                    <input
                      type="checkbox"
                      checked={shipToDifferentAddress}
                      onChange={(e) => setShipToDifferentAddress(e.target.checked)}
                      className="w-4 h-4"
                    />
                    <span className="font-medium">Ship to a different address?</span>
                  </label>

                  {shipToDifferentAddress && (
                    <>
                      {/* Selected Shipping Address Summary */}
                      {!loadingAddresses && savedAddresses.length > 0 && savedAddresses.some(a => a.type === 'shipping' || a.type === 'both') && (
                        <div className="mb-6">
                          <div className="flex items-center justify-between mb-3">
                            <h3 className="text-lg font-semibold flex items-center gap-2">
                              <MapPin className="w-4 h-4" />
                              Shipping Address
                            </h3>
                            <Button
                              type="button"
                              variant="outline"
                              size="sm"
                              onClick={() => setShowShippingModal(true)}
                              className="flex items-center gap-2"
                            >
                              <Edit2 className="w-4 h-4" />
                              Change Address
                            </Button>
                          </div>

                          {selectedShippingAddressId ? (
                            (() => {
                              const selected = savedAddresses.find(a => a.id === selectedShippingAddressId);
                              return selected ? (
                                <div>
                                  <div className="bg-primary/5 border-2 border-primary rounded-lg p-4">
                                    <div className="flex items-center gap-2 mb-2">
                                      <p className="font-semibold">{selected.label}</p>
                                      {selected.is_default && (
                                        <span className="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded">Default</span>
                                      )}
                                    </div>
                                    <p className="text-sm font-medium text-gray-900">{selected.first_name} {selected.last_name}</p>
                                    {selected.phone && <p className="text-sm text-gray-600">{selected.phone}</p>}
                                    <p className="text-sm text-gray-600 mt-2">{selected.address_1}</p>
                                    {selected.address_2 && <p className="text-sm text-gray-600">{selected.address_2}</p>}
                                    <p className="text-sm text-gray-600">{selected.city}, {selected.state} {selected.postcode}</p>
                                    <p className="text-sm text-gray-600">{selected.country}</p>
                                  </div>
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => setShowShippingForm(true)}
                                    className="mt-3 text-primary hover:text-primary"
                                  >
                                    Use a different address
                                  </Button>
                                </div>
                              ) : null;
                            })()
                          ) : (
                            <p className="text-gray-500 text-sm">No address selected</p>
                          )}
                        </div>
                      )}

                      {/* Shipping Address Modal */}
                      <AddressSelector
                        isOpen={showShippingModal}
                        onClose={() => setShowShippingModal(false)}
                        addresses={savedAddresses}
                        selectedAddressId={selectedShippingAddressId}
                        onSelectAddress={handleSelectShippingAddress}
                        type="shipping"
                      />

                      {/* Shipping Form - Only show if no saved address selected or user wants to enter manually */}
                      {(!selectedShippingAddressId || showShippingForm) && (
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div>
                            <label className="block text-sm font-medium mb-2">First Name *</label>
                            <input
                              type="text"
                              required
                              value={shippingData.firstName}
                              onChange={(e) => setShippingData({ ...shippingData, firstName: e.target.value })}
                              className="w-full border rounded-lg px-4 py-2"
                            />
                          </div>
                          <div>
                            <label className="block text-sm font-medium mb-2">Last Name *</label>
                            <input
                              type="text"
                              required
                              value={shippingData.lastName}
                              onChange={(e) => setShippingData({ ...shippingData, lastName: e.target.value })}
                              className="w-full border rounded-lg px-4 py-2"
                            />
                          </div>
                          <div className="md:col-span-2">
                            <label className="block text-sm font-medium mb-2">Street Address *</label>
                            <input
                              type="text"
                              required
                              value={shippingData.address}
                              onChange={(e) => setShippingData({ ...shippingData, address: e.target.value })}
                              className="w-full border rounded-lg px-4 py-2"
                            />
                          </div>
                          <div>
                            <label className="block text-sm font-medium mb-2">City *</label>
                            <input
                              type="text"
                              required
                              value={shippingData.city}
                              onChange={(e) => setShippingData({ ...shippingData, city: e.target.value })}
                              className="w-full border rounded-lg px-4 py-2"
                            />
                          </div>
                          <div>
                            <label className="block text-sm font-medium mb-2">State / Province *</label>
                            <input
                              type="text"
                              required
                              value={shippingData.state}
                              onChange={(e) => setShippingData({ ...shippingData, state: e.target.value })}
                              className="w-full border rounded-lg px-4 py-2"
                            />
                          </div>
                          <div>
                            <label className="block text-sm font-medium mb-2">Postcode / ZIP *</label>
                            <input
                              type="text"
                              required
                              value={shippingData.postcode}
                              onChange={(e) => setShippingData({ ...shippingData, postcode: e.target.value })}
                              className="w-full border rounded-lg px-4 py-2"
                            />
                          </div>
                          <div>
                            <label className="block text-sm font-medium mb-2">Country *</label>
                            <input
                              type="text"
                              required
                              value={shippingData.country}
                              onChange={(e) => setShippingData({ ...shippingData, country: e.target.value })}
                              className="w-full border rounded-lg px-4 py-2"
                            />
                          </div>
                        </div>
                      )}
                    </>
                  )}
                </div>
              )}

              {/* Order Notes */}
              {elements.order_notes && (
                <div className="bg-white border rounded-lg p-6">
                  <h2 className="text-xl font-bold mb-4">Order Notes (Optional)</h2>
                  <textarea
                    value={orderNotes}
                    onChange={(e) => setOrderNotes(e.target.value)}
                    placeholder="Notes about your order, e.g. special notes for delivery."
                    className="w-full border rounded-lg px-4 py-2 h-32"
                  />
                </div>
              )}
            </div>

            {/* Order Summary */}
            <div className={`${layout.style === 'single-column' || layout.order_summary === 'top' ? 'order-first' : 'lg:col-span-1'}`}>
              <div className="bg-white border rounded-lg p-6 sticky top-4">
                <h2 className="text-xl font-bold mb-4">Your Order</h2>

                {/* Coupon Field */}
                {elements.coupon_field && (
                  <div className="mb-4 pb-4 border-b">
                    <label className="block text-sm font-medium mb-2">Coupon Code</label>
                    <div className="flex gap-2">
                      <input
                        type="text"
                        placeholder="Enter coupon code"
                        className="flex-1 px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                      />
                      <Button type="button" variant="outline" size="sm">Apply</Button>
                    </div>
                  </div>
                )}

                {/* Order Items */}
                <div className="space-y-3 mb-4 pb-4 border-b">
                  {cart.items.map((item) => (
                    <div key={item.key} className="flex justify-between text-sm">
                      <span>
                        {item.name} × {item.quantity}
                      </span>
                      <span className="font-medium">
                        {formatPrice(item.price * item.quantity)}
                      </span>
                    </div>
                  ))}
                </div>

                {/* Shipping Options */}
                {elements.shipping_options && (
                  <div className="mb-4 pb-4 border-b">
                    <h3 className="font-medium mb-3">Shipping Method</h3>
                    <div className="space-y-2">
                      <label className="flex items-center justify-between p-3 border rounded-lg cursor-pointer hover:bg-gray-50">
                        <div className="flex items-center gap-2">
                          <input type="radio" name="shipping" value="free" defaultChecked className="w-4 h-4" />
                          <span className="text-sm">Free Shipping</span>
                        </div>
                        <span className="text-sm font-medium">Free</span>
                      </label>
                      <label className="flex items-center justify-between p-3 border rounded-lg cursor-pointer hover:bg-gray-50">
                        <div className="flex items-center gap-2">
                          <input type="radio" name="shipping" value="express" className="w-4 h-4" />
                          <span className="text-sm">Express Shipping</span>
                        </div>
                        <span className="text-sm font-medium">$15.00</span>
                      </label>
                    </div>
                  </div>
                )}

                {/* Totals */}
                <div className="space-y-2 mb-6">
                  <div className="flex justify-between text-sm">
                    <span>Subtotal</span>
                    <span>{formatPrice(subtotal)}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span>Shipping</span>
                    <span>{shipping === 0 ? 'Free' : formatPrice(shipping)}</span>
                  </div>
                  {tax > 0 && (
                    <div className="flex justify-between text-sm">
                      <span>Tax</span>
                      <span>{formatPrice(tax)}</span>
                    </div>
                  )}
                  <div className="border-t pt-2 flex justify-between font-bold text-lg">
                    <span>Total</span>
                    <span>{formatPrice(total)}</span>
                  </div>
                </div>

                {/* Payment Method */}
                <div className="mb-6">
                  <h3 className="font-medium mb-3">Payment Method</h3>
                  <div className="space-y-2">
                    {/* Hide COD for virtual-only products */}
                    {!isVirtualOnly && (
                      <label className="flex items-center gap-2 p-3 border rounded-lg cursor-pointer hover:bg-gray-50">
                        <input
                          type="radio"
                          name="payment"
                          value="cod"
                          checked={paymentMethod === 'cod'}
                          onChange={(e) => setPaymentMethod(e.target.value)}
                          className="w-4 h-4"
                        />
                        <span>Cash on Delivery</span>
                      </label>
                    )}
                    <label className="flex items-center gap-2 p-3 border rounded-lg cursor-pointer hover:bg-gray-50">
                      <input
                        type="radio"
                        name="payment"
                        value="bacs"
                        checked={paymentMethod === 'bacs'}
                        onChange={(e) => setPaymentMethod(e.target.value)}
                        className="w-4 h-4"
                      />
                      <span>Bank Transfer</span>
                    </label>
                  </div>

                  {/* Payment Icons */}
                  {elements.payment_icons && (
                    <div className="flex items-center gap-2 mt-3 pt-3 border-t">
                      <span className="text-xs text-gray-500">We accept:</span>
                      <div className="flex gap-1">
                        <div className="w-10 h-6 bg-gray-100 rounded flex items-center justify-center text-xs font-bold">VISA</div>
                        <div className="w-10 h-6 bg-gray-100 rounded flex items-center justify-center text-xs font-bold">MC</div>
                        <div className="w-10 h-6 bg-gray-100 rounded flex items-center justify-center text-xs font-bold">AMEX</div>
                      </div>
                    </div>
                  )}
                </div>

                {/* Place Order Button - Only show in sidebar layout */}
                {layout.order_summary !== 'top' && (
                  <Button
                    type="submit"
                    size="lg"
                    className="w-full"
                    disabled={isProcessing}
                  >
                    {isProcessing ? 'Processing...' : 'Place Order'}
                  </Button>
                )}
              </div>
            </div>
          </div>

          {/* Place Order Button - Show at bottom when summary is on top */}
          {layout.order_summary === 'top' && (
            <div className="mt-6">
              <Button
                type="submit"
                size="lg"
                className="w-full"
                disabled={isProcessing}
              >
                {isProcessing ? 'Processing...' : 'Place Order'}
              </Button>
            </div>
          )}
        </form>
      </div>
    </Container>
  );
}
