import React, { useState } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { X, Trash2, Plus, Minus, ShoppingBag, ArrowLeft, Tag, Check, Sparkles, AlertCircle } from 'lucide-react';
import { useCart } from '../context/CartContext';
import { formatPrice, toPersianDigits } from '../utils/formatters';

interface CartDrawerProps {
  onProceedToCheckout: () => void;
}

export const CartDrawer: React.FC<CartDrawerProps> = ({ onProceedToCheckout }) => {
  const {
    items,
    itemCount,
    subtotal,
    discountAmount,
    couponCode,
    appliedCoupon,
    finalTotal,
    isCartOpen,
    setIsCartOpen,
    removeFromCart,
    updateQuantity,
    clearCart,
    applyCoupon,
    removeCoupon,
    couponLoading,
  } = useCart();

  const [inputCoupon, setInputCoupon] = useState('');

  const handleApplyCoupon = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!inputCoupon.trim()) return;
    const success = await applyCoupon(inputCoupon);
    if (success) {
      setInputCoupon('');
    }
  };

  return (
    <AnimatePresence>
      {isCartOpen && (
        <div className="fixed inset-0 z-50 overflow-hidden">
          {/* Backdrop overlay */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={() => setIsCartOpen(false)}
            className="absolute inset-0 bg-black/70 backdrop-blur-sm"
          />

          <div className="fixed inset-y-0 left-0 max-w-full flex pl-0 sm:pl-10">
            <motion.div
              initial={{ x: '-100%' }}
              animate={{ x: 0 }}
              exit={{ x: '-100%' }}
              transition={{ type: 'spring', damping: 25, stiffness: 200 }}
              className="w-screen max-w-md bg-[#0f0920] border-r border-purple-500/20 shadow-2xl flex flex-col justify-between text-right"
            >
              
              {/* Header */}
              <div className="p-5 border-b border-purple-900/40 flex items-center justify-between bg-[#130b28]">
                <div className="flex items-center gap-2.5">
                  <div className="w-8 h-8 rounded-lg bg-purple-600/30 border border-purple-500/40 flex items-center justify-center text-purple-300">
                    <ShoppingBag className="w-4 h-4" />
                  </div>
                  <div>
                    <h3 className="text-base font-bold text-white">سبد خرید شما</h3>
                    <div className="text-xs text-zinc-400">
                      {toPersianDigits(itemCount)} قلم کالا
                    </div>
                  </div>
                </div>

                <div className="flex items-center gap-2">
                  {items.length > 0 && (
                    <button
                      onClick={clearCart}
                      className="text-xs text-rose-400 hover:text-rose-300 px-2 py-1 rounded hover:bg-rose-950/40 transition-colors"
                      title="خالی کردن سبد خرید"
                    >
                      خالی کردن
                    </button>
                  )}
                  <button
                    onClick={() => setIsCartOpen(false)}
                    className="p-1.5 rounded-lg text-zinc-400 hover:text-white hover:bg-purple-950 transition-colors"
                  >
                    <X className="w-5 h-5" />
                  </button>
                </div>
              </div>

              {/* Items List */}
              <div className="flex-1 overflow-y-auto p-5 space-y-4">
                {items.length === 0 ? (
                  <div className="py-20 text-center space-y-4">
                    <div className="w-16 h-16 rounded-2xl bg-[#170e30] border border-purple-500/20 mx-auto flex items-center justify-center text-purple-400">
                      <ShoppingBag className="w-8 h-8 opacity-40" />
                    </div>
                    <div className="text-zinc-300 font-bold text-base">سبد خرید شما خالی است</div>
                    <p className="text-xs text-zinc-500 max-w-xs mx-auto">
                      می‌توانید از بخش فروشگاه، پلن WireGuard موردنظر خود را انتخاب کنید.
                    </p>
                    <button
                      onClick={() => setIsCartOpen(false)}
                      className="mt-2 px-5 py-2.5 rounded-xl bg-purple-600 hover:bg-purple-500 text-white text-xs font-bold transition-colors"
                    >
                      شروع خرید از فروشگاه
                    </button>
                  </div>
                ) : (
                  items.map((item) => (
                    <div
                      key={item.product.id}
                      className="p-3.5 rounded-xl bg-[#140c2a] border border-purple-500/15 flex items-center gap-3 relative group"
                    >
                      <img
                        src={item.product.image}
                        alt={item.product.title}
                        className="w-16 h-16 rounded-lg object-cover bg-purple-950 border border-purple-500/20 shrink-0"
                        referrerPolicy="no-referrer"
                      />

                      <div className="flex-1 min-w-0">
                        <div className="text-sm font-bold text-zinc-200 truncate">
                          {item.product.title}
                        </div>
                        <div className="text-xs text-purple-400 font-medium mt-0.5">
                          {formatPrice(item.product.price)}
                        </div>

                        {/* Quantity Counter */}
                        <div className="flex items-center gap-2 mt-2">
                          <div className="flex items-center border border-purple-500/30 rounded-lg bg-[#0c071a] px-1 py-0.5">
                            <button
                              onClick={() => updateQuantity(item.product.id, item.quantity + 1)}
                              className="p-1 text-zinc-400 hover:text-white"
                              title="افزایش"
                            >
                              <Plus className="w-3.5 h-3.5" />
                            </button>
                            <span className="px-2 text-xs font-bold text-white min-w-[20px] text-center font-vazir">
                              {toPersianDigits(item.quantity)}
                            </span>
                            <button
                              onClick={() => updateQuantity(item.product.id, item.quantity - 1)}
                              className="p-1 text-zinc-400 hover:text-white"
                              title="کاهش"
                            >
                              <Minus className="w-3.5 h-3.5" />
                            </button>
                          </div>

                          <button
                            onClick={() => removeFromCart(item.product.id)}
                            className="p-1 text-zinc-500 hover:text-rose-400 transition-colors"
                            title="حذف از سبد"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </div>

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

              {/* Footer / Summary with Coupon Input */}
              {items.length > 0 && (
                <div className="p-5 border-t border-purple-900/40 bg-[#130b28] space-y-4">
                  
                  {/* Coupon Input Form */}
                  <div>
                    {appliedCoupon ? (
                      <div className="flex items-center justify-between p-2.5 rounded-xl bg-emerald-950/40 border border-emerald-500/30 text-xs">
                        <div className="flex items-center gap-2 text-emerald-300">
                          <Check className="w-4 h-4 text-emerald-400" />
                          <span>کد <strong>{appliedCoupon.code}</strong> اعمال شد ({formatPrice(discountAmount)} تخفیف)</span>
                        </div>
                        <button
                          onClick={removeCoupon}
                          className="text-rose-400 hover:text-rose-300 font-bold px-2 py-0.5"
                        >
                          حذف
                        </button>
                      </div>
                    ) : (
                      <form onSubmit={handleApplyCoupon} className="flex gap-2">
                        <input
                          type="text"
                          value={inputCoupon}
                          onChange={(e) => setInputCoupon(e.target.value)}
                          placeholder="کد تخفیف (مثال: ZANA)"
                          className="flex-1 bg-[#0c071a] text-xs text-zinc-100 placeholder-zinc-500 px-3 py-2.5 rounded-xl border border-purple-500/20 focus:outline-none focus:border-purple-500 uppercase"
                        />
                        <button
                          type="submit"
                          disabled={couponLoading || !inputCoupon.trim()}
                          className="px-4 py-2.5 rounded-xl bg-purple-950/80 hover:bg-purple-900 text-purple-300 hover:text-white border border-purple-500/30 text-xs font-bold transition-colors disabled:opacity-50"
                        >
                          {couponLoading ? 'بررسی...' : 'اعمال'}
                        </button>
                      </form>
                    )}
                  </div>

                  {/* Price Calculations */}
                  <div className="space-y-1.5 text-xs">
                    <div className="flex justify-between text-zinc-400">
                      <span>جمع مبلغ اقلام:</span>
                      <span className="font-semibold text-zinc-200">{formatPrice(subtotal)}</span>
                    </div>

                    {discountAmount > 0 && (
                      <div className="flex justify-between text-emerald-400">
                        <span>مبلغ تخفیف:</span>
                        <span className="font-bold">-{formatPrice(discountAmount)}</span>
                      </div>
                    )}

                    <div className="flex justify-between text-base font-black text-white pt-2 border-t border-purple-900/40">
                      <span>مبلغ نهایی قابل پرداخت:</span>
                      <span className="text-purple-300">{formatPrice(finalTotal)}</span>
                    </div>
                  </div>

                  {/* Checkout Button */}
                  <button
                    onClick={() => {
                      setIsCartOpen(false);
                      onProceedToCheckout();
                    }}
                    className="w-full py-3.5 rounded-xl bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white font-bold text-sm shadow-xl shadow-purple-600/30 transition-all hover:scale-[1.02] active:scale-95 flex items-center justify-center gap-2"
                  >
                    <span>تکمیل و ثبت نهایی سفارش</span>
                    <ArrowLeft className="w-4 h-4" />
                  </button>

                </div>
              )}

            </motion.div>
          </div>
        </div>
      )}
    </AnimatePresence>
  );
};
