import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { ShoppingBag, Plus, Minus, Trash2, Tag, ArrowLeft } from "lucide-react";
import { toast } from "sonner";
import { useCartStore } from "@/stores/cartStore";

const PROMO_CODES: Record<string, number> = {
  BNPASH10: 0.1,
  SAVE15: 0.15,
  WELCOME20: 0.2,
};

export default function CartPage() {
  const { items, removeFromCart, updateQuantity, totalPrice, totalItems } =
    useCartStore();
  const navigate = useNavigate();
  const [promoCode, setPromoCode] = useState("");
  const [discountRate, setDiscountRate] = useState(0);

  const shipping = totalPrice > 5000 ? 0 : 500;
  const discountAmount = Math.floor(totalPrice * discountRate);
  const finalTotal = totalPrice - discountAmount + shipping;

  const applyPromo = () => {
    const code = promoCode.trim().toUpperCase();
    if (PROMO_CODES[code]) {
      setDiscountRate(PROMO_CODES[code]);
      toast.success(`✅ تم تطبيق الكوبون! خصم ${PROMO_CODES[code] * 100}%`);
    } else {
      toast.error("كوبون غير صحيح");
    }
  };

  if (items.length === 0) {
    return (
      <div className="max-w-lg mx-auto px-4 py-20 text-center">
        <div className="bg-white rounded-3xl shadow-lg p-10">
          <ShoppingBag className="text-orange-300 mx-auto mb-4" size={72} />
          <h2 className="text-2xl font-black text-gray-800 mb-2">السلة فارغة</h2>
          <p className="text-gray-500 mb-6">لم تضف أي منتجات بعد. ابدأ التسوق الآن!</p>
          <Link to="/products" className="btn-primary inline-block">
            تسوق الآن
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 py-6">
      <div className="flex items-center gap-3 mb-6">
        <Link to="/products" className="text-orange-500 hover:text-orange-600 transition-colors">
          <ArrowLeft size={20} />
        </Link>
        <h1 className="text-2xl font-black text-gray-800">سلة التسوق</h1>
        <span className="bg-orange-100 text-orange-600 text-sm font-bold px-3 py-1 rounded-full">
          {totalItems} منتج
        </span>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Cart items */}
        <div className="lg:col-span-2 space-y-3">
          {items.map((item) => (
            <div key={item.variantKey || item.product.id} className="bg-white rounded-2xl p-4 shadow-sm border border-gray-100 flex gap-4">
              <Link to={`/products/${item.product.id}`}>
                <img
                  src={item.product.image}
                  alt={item.product.name}
                  className="w-24 h-24 object-cover rounded-xl bg-gray-50"
                />
              </Link>
              <div className="flex-1 min-w-0">
                <div className="flex justify-between">
                  <div className="flex-1 min-w-0 ml-2">
                    <p className="text-xs text-orange-500 font-semibold">{item.product.category}</p>
                    <Link
                      to={`/products/${item.product.id}`}
                      className="font-bold text-gray-800 text-sm hover:text-orange-500 transition-colors line-clamp-2"
                    >
                      {item.product.name}
                    </Link>
                    {item.variant && (
                      <div className="flex items-center gap-1.5 mt-1 flex-wrap">
                        {item.variant.colorHex && (
                          <span className="w-3.5 h-3.5 rounded-full border border-gray-300 shrink-0" style={{ backgroundColor: item.variant.colorHex }} />
                        )}
                        {item.variant.color && <span className="text-xs text-gray-500">{item.variant.color}</span>}
                        {item.variant.size && <span className="text-xs bg-gray-100 text-gray-600 px-1.5 py-0.5 rounded-md font-semibold">{item.variant.size}</span>}
                      </div>
                    )}
                  </div>
                  <button
                    onClick={() => {
                      removeFromCart(item.variantKey || item.product.id);
                      toast.success("تمت الإزالة من السلة");
                    }}
                    className="text-gray-300 hover:text-red-400 transition-colors p-1 shrink-0"
                  >
                    <Trash2 size={18} />
                  </button>
                </div>

                <div className="flex items-center justify-between mt-3">
                  <div className="flex items-center gap-2 bg-gray-100 rounded-xl p-1">
                    <button
                      onClick={() => updateQuantity(item.variantKey || item.product.id, item.quantity + 1)}
                      className="w-8 h-8 bg-white rounded-lg flex items-center justify-center hover:bg-orange-50 hover:text-orange-500 transition-colors shadow-sm"
                    >
                      <Plus size={14} />
                    </button>
                    <span className="w-8 text-center font-black">{item.quantity}</span>
                    <button
                      onClick={() => updateQuantity(item.variantKey || item.product.id, item.quantity - 1)}
                      className="w-8 h-8 bg-white rounded-lg flex items-center justify-center hover:bg-orange-50 hover:text-orange-500 transition-colors shadow-sm"
                    >
                      <Minus size={14} />
                    </button>
                  </div>
                  <span className="font-black text-orange-500 text-lg">
                    {((item.variant ? item.variant.price : item.product.price) * item.quantity).toLocaleString()} ر.ي
                  </span>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Order Summary + Form */}
        <div className="space-y-4">
          {/* Promo code */}
          <div className="bg-white rounded-2xl p-5 shadow-sm border border-gray-100">
            <h3 className="font-black text-gray-800 mb-3 flex items-center gap-2">
              <Tag size={18} className="text-orange-500" />
              كوبون الخصم
            </h3>
            <div className="flex gap-2">
              <input
                type="text"
                value={promoCode}
                onChange={(e) => setPromoCode(e.target.value)}
                placeholder="أدخل الكوبون"
                className="flex-1 border border-gray-200 rounded-xl px-3 py-2 text-sm outline-none focus:border-orange-400 text-right"
              />
              <button onClick={applyPromo} className="bg-orange-500 hover:bg-orange-600 text-white text-sm font-bold px-4 rounded-xl transition-colors">
                تطبيق
              </button>
            </div>
            <p className="text-xs text-gray-400 mt-2">جرب: BNPASH10 للحصول على خصم 10%</p>
          </div>

          {/* Order summary */}
          <div className="bg-white rounded-2xl p-5 shadow-sm border border-gray-100">
            <h3 className="font-black text-gray-800 mb-4">ملخص الطلب</h3>
            <div className="space-y-3 text-sm">
              <div className="flex justify-between text-gray-600">
                <span>{totalItems} منتج</span>
                <span>{totalPrice.toLocaleString()} ر.ي</span>
              </div>
              {discountAmount > 0 && (
                <div className="flex justify-between text-green-600 font-semibold">
                  <span>الخصم ({discountRate * 100}%)</span>
                  <span>- {discountAmount.toLocaleString()} ر.ي</span>
                </div>
              )}
              <div className="flex justify-between text-gray-600">
                <span>التوصيل</span>
                <span className={shipping === 0 ? "text-green-500 font-semibold" : ""}>
                  {shipping === 0 ? "مجاني 🎉" : `${shipping.toLocaleString()} ر.ي`}
                </span>
              </div>
              {shipping > 0 && (
                <p className="text-xs text-gray-400 bg-blue-50 p-2 rounded-lg">
                  أضف {(5000 - totalPrice).toLocaleString()} ر.ي للحصول على توصيل مجاني
                </p>
              )}
              <div className="border-t pt-3 flex justify-between font-black text-lg">
                <span>الإجمالي</span>
                <span className="text-orange-500">{finalTotal.toLocaleString()} ر.ي</span>
              </div>
            </div>
          </div>

          {/* Proceed to checkout */}
          <div className="bg-white rounded-2xl p-5 shadow-sm border border-gray-100">
            <button
              onClick={() => navigate("/checkout")}
              className="btn-primary w-full flex items-center justify-center gap-2 text-base py-4"
            >
              <ShoppingBag size={18} />
              متابعة الدفع — {finalTotal.toLocaleString()} ر.ي
            </button>
            <p className="text-xs text-gray-400 text-center mt-3">الدفع عند الاستلام (كاش)</p>
          </div>
        </div>
      </div>
    </div>
  );
}
