import React from 'react';
import { X, ShoppingBag, Trash2, Plus, Minus, ArrowRight, MessageCircle, Truck } from 'lucide-react';
import { WCProduct, stripHtmlTags } from '../services/woocommerce';
import { calculateCartShipping } from '../services/shippingService';

export interface CartItem {
  product: WCProduct;
  quantity: number;
}

interface CartDrawerProps {
  isOpen: boolean;
  onClose: () => void;
  cartItems: CartItem[];
  onUpdateQuantity: (productId: number, delta: number) => void;
  onRemoveItem: (productId: number) => void;
  onClearCart: () => void;
  onOpenCheckout?: (isWhatsApp?: boolean) => void;
}

export const CartDrawer: React.FC<CartDrawerProps> = ({
  isOpen,
  onClose,
  cartItems,
  onUpdateQuantity,
  onRemoveItem,
  onClearCart,
  onOpenCheckout,
}) => {
  if (!isOpen) return null;

  const totalAmount = cartItems.reduce((sum, item) => {
    const price = parseFloat(item.product.sale_price || item.product.price || '0');
    return sum + price * item.quantity;
  }, 0);

  const formattedPrice = (num: number) => `Rs ${num.toLocaleString('en-PK')}`;

  const shippingRates = calculateCartShipping(cartItems, 'Pakistan');
  const grandTotal = totalAmount + shippingRates.shippingCost;

  const handleCheckoutWhatsApp = () => {
    if (cartItems.length === 0) return;
    const itemListText = cartItems
      .map(
        (item) =>
          `• ${stripHtmlTags(item.product.name)} (x${item.quantity}) - ${formattedPrice(
            parseFloat(item.product.sale_price || item.product.price || '0') * item.quantity
          )}`
      )
      .join('\n');

    const shippingText = shippingRates.isFreeShipping ? 'FREE' : formattedPrice(shippingRates.shippingCost);

    const message = encodeURIComponent(
      `🛒 *TIME N LIFE - CART ORDER INQUIRY*\n` +
      `━━━━━━━━━━━━━━━━━━━━━━\n` +
      `🌐 *Website:* https://timenlife.com\n\n` +
      `*Selected Items:*\n${itemListText}\n\n` +
      `📦 *Delivery Charges:* ${shippingText}\n` +
      `💵 *Total Amount:* ${formattedPrice(grandTotal)}\n` +
      `━━━━━━━━━━━━━━━━━━━━━━\n` +
      `Please confirm availability & delivery details for Cash on Delivery. Thank you!`
    );

    window.open(`https://wa.me/923313333400?text=${message}`, '_blank');
  };

  return (
    <div className="fixed inset-0 z-50 overflow-hidden animate-in fade-in duration-200">
      {/* Backdrop */}
      <div
        onClick={onClose}
        className="absolute inset-0 bg-black/60 backdrop-blur-xs transition-opacity"
      />

      {/* Drawer Body */}
      <div className="fixed inset-y-0 right-0 max-w-full flex pl-10">
        <div className="w-screen max-w-md bg-[#FFFDFB] shadow-2xl border-l border-[#F2E5D9] flex flex-col justify-between">
          
          {/* Header */}
          <div className="p-5 bg-[#FAF5F0] border-b border-[#F2E5D9] flex items-center justify-between">
            <div className="flex items-center gap-2">
              <ShoppingBag className="w-5 h-5 text-[#C81E3D]" />
              <h3 className="font-bold font-playfair text-slate-800 text-lg">
                Your Shopping Cart ({cartItems.reduce((acc, i) => acc + i.quantity, 0)})
              </h3>
            </div>
            <button
              onClick={onClose}
              className="p-1 rounded-full text-slate-400 hover:text-slate-800 hover:bg-rose-100 transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          {/* Cart Item List */}
          <div className="flex-1 overflow-y-auto p-5 space-y-4">
            {cartItems.length > 0 ? (
              cartItems.map(({ product, quantity }) => {
                const itemPrice = parseFloat(product.sale_price || product.price || '0');
                return (
                  <div
                    key={product.id}
                    className="p-3 bg-[#FAF5F0] rounded-2xl border border-[#F2E5D9] flex gap-3 items-center justify-between"
                  >
                    <img
                      src={product.images?.[0]?.src || 'https://images.unsplash.com/photo-1523275335684-37898b6baf30?auto=format&fit=crop&w=800&q=80'}
                      alt={product.name}
                      className="w-16 h-16 object-cover rounded-xl border border-[#E8D9CC]"
                    />

                    <div className="flex-1 space-y-1">
                      <h4 className="text-xs font-bold text-slate-800 line-clamp-1">{stripHtmlTags(product.name)}</h4>
                      <div className="text-xs font-extrabold text-[#C81E3D]">
                        {formattedPrice(itemPrice)}
                      </div>

                      <div className="flex items-center gap-2 pt-1">
                        <div className="flex items-center bg-white rounded-lg border border-slate-200">
                          <button
                            onClick={() => onUpdateQuantity(product.id, -1)}
                            className="p-1 text-slate-600 hover:text-slate-900"
                          >
                            <Minus className="w-3 h-3" />
                          </button>
                          <span className="px-2 text-xs font-bold">{quantity}</span>
                          <button
                            onClick={() => onUpdateQuantity(product.id, 1)}
                            className="p-1 text-slate-600 hover:text-slate-900"
                          >
                            <Plus className="w-3 h-3" />
                          </button>
                        </div>

                        <button
                          onClick={() => onRemoveItem(product.id)}
                          className="text-slate-400 hover:text-rose-600 text-xs p-1"
                          title="Remove item"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                        </button>
                      </div>
                    </div>

                    <div className="text-xs font-bold text-slate-800">
                      {formattedPrice(itemPrice * quantity)}
                    </div>
                  </div>
                );
              })
            ) : (
              <div className="text-center py-16 space-y-3">
                <ShoppingBag className="w-12 h-12 text-slate-300 mx-auto" />
                <p className="text-sm font-semibold text-slate-700">Your cart is currently empty</p>
                <p className="text-xs text-slate-400">Explore products in our shop catalog and add items.</p>
              </div>
            )}
          </div>

          {/* Footer Checkout Summary */}
          {cartItems.length > 0 && (
            <div className="p-5 bg-[#FAF5F0] border-t border-[#F2E5D9] space-y-2.5">
              <div className="flex items-center justify-between text-xs text-slate-600">
                <span>Subtotal</span>
                <span className="font-bold text-slate-800">{formattedPrice(totalAmount)}</span>
              </div>

              <div className="flex items-center justify-between text-xs bg-amber-50/80 p-2 rounded-lg border border-amber-200/60">
                <div className="flex items-center gap-1.5 text-slate-700 font-medium">
                  <Truck className="w-3.5 h-3.5 text-amber-800" />
                  <span>Delivery Charges</span>
                  <span className="text-[10px] text-slate-500">({shippingRates.shippingClassLabel})</span>
                </div>
                <span className={`font-bold ${shippingRates.isFreeShipping ? 'text-emerald-700 bg-emerald-100 px-2 py-0.5 rounded text-[11px]' : 'text-slate-900'}`}>
                  {shippingRates.isFreeShipping ? 'FREE' : formattedPrice(shippingRates.shippingCost)}
                </span>
              </div>

              <div className="flex items-center justify-between text-sm pt-1 border-t border-slate-200/60">
                <span className="font-bold text-slate-800">Total Payable</span>
                <span className="font-extrabold text-[#C81E3D] text-lg font-playfair">
                  {formattedPrice(grandTotal)}
                </span>
              </div>

              <div className="space-y-2 pt-2">
                <button
                  onClick={() => {
                    onClose();
                    onOpenCheckout?.();
                  }}
                  className="w-full py-3.5 bg-[#C81E3D] hover:bg-[#a61530] text-white font-bold text-xs uppercase tracking-wider rounded-xl shadow-md transition-colors flex items-center justify-center gap-2 cursor-pointer"
                >
                  <Truck className="w-4 h-4" />
                  <span>DIRECT CHECKOUT (COD / LEOPARDS)</span>
                </button>

                <button
                  onClick={() => {
                    onClose();
                    onOpenCheckout?.(true);
                  }}
                  className="w-full py-3 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs uppercase tracking-wider rounded-xl shadow-xs transition-colors flex items-center justify-center gap-2 cursor-pointer"
                >
                  <MessageCircle className="w-4 h-4" />
                  <span>CHECKOUT VIA WHATSAPP</span>
                </button>

                <button
                  onClick={onClearCart}
                  className="w-full text-center text-xs text-slate-400 hover:text-rose-600 font-semibold pt-1"
                >
                  Clear Cart
                </button>
              </div>
            </div>
          )}

        </div>
      </div>
    </div>
  );
};
