"use client";

import React, { useState } from "react";
import { useCart } from "@/context/CartContext";
import {
  X,
  Trash2,
  Plus,
  Minus,
  ShoppingCart,
  Truck,
  ArrowRight,
  Sparkles,
  ShieldCheck,
  Tag,
  Check,
} from "lucide-react";

export const CartDrawer: React.FC = () => {
  const {
    cart,
    isCartOpen,
    setIsCartOpen,
    removeFromCart,
    updateQuantity,
    clearCart,
    subtotal,
    discountAmount,
    vatAmount,
    freeShippingThreshold,
    amountNeededForFreeShipping,
    appliedPromo,
    applyPromoCode,
    removePromoCode,
    setIsCheckoutOpen,
  } = useCart();

  const [promoInput, setPromoInput] = useState("");
  const [promoMsg, setPromoMsg] = useState<{ success: boolean; text: string } | null>(null);

  if (!isCartOpen) return null;

  const handleApplyPromo = (e: React.FormEvent) => {
    e.preventDefault();
    if (!promoInput) return;
    const res = applyPromoCode(promoInput);
    setPromoMsg({ success: res.success, text: res.message });
    if (res.success) setPromoInput("");
  };

  const handleCheckoutClick = () => {
    setIsCartOpen(false);
    setIsCheckoutOpen(true);
  };

  const freeShippingProgress = Math.min(100, Math.round((subtotal / freeShippingThreshold) * 100));

  return (
    <div className="fixed inset-0 z-50 overflow-hidden bg-slate-950/60 backdrop-blur-xs flex justify-end animate-fadeIn">
      <div className="bg-white w-full max-w-md h-full shadow-2xl flex flex-col justify-between overflow-hidden">
        {/* Cart Header */}
        <div className="p-4 sm:p-5 border-b border-slate-200 bg-slate-900 text-white flex items-center justify-between">
          <div className="flex items-center gap-2.5">
            <ShoppingCart className="w-5 h-5 text-amber-400" />
            <div>
              <h2 className="font-extrabold text-base tracking-tight">Your Shopping Cart</h2>
              <p className="text-[11px] text-slate-300">
                {cart.length} {cart.length === 1 ? "item" : "items"} selected
              </p>
            </div>
          </div>

          <button
            onClick={() => setIsCartOpen(false)}
            className="p-2 text-slate-300 hover:text-white hover:bg-slate-800 rounded-xl transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Free Shipping Progress Indicator */}
        <div className="p-3.5 bg-blue-50 border-b border-blue-100">
          <div className="flex items-center justify-between text-xs font-bold text-slate-800 mb-1.5">
            <div className="flex items-center gap-1.5">
              <Truck className="w-4 h-4 text-blue-900" />
              {amountNeededForFreeShipping === 0 ? (
                <span className="text-emerald-700 font-black">🎉 You qualify for FREE SA Courier Shipping!</span>
              ) : (
                <span>Add <strong className="text-blue-950">R{amountNeededForFreeShipping.toFixed(2)}</strong> for FREE Courier</span>
              )}
            </div>
            <span className="text-blue-950 font-extrabold">{freeShippingProgress}%</span>
          </div>

          <div className="w-full bg-slate-200 h-2 rounded-full overflow-hidden">
            <div
              className={`h-full transition-all duration-500 rounded-full ${
                amountNeededForFreeShipping === 0 ? "bg-emerald-500" : "bg-gradient-to-r from-blue-900 to-amber-500"
              }`}
              style={{ width: `${freeShippingProgress}%` }}
            />
          </div>
        </div>

        {/* Cart Items Scroll Area */}
        <div className="flex-1 overflow-y-auto p-4 space-y-4">
          {cart.length === 0 ? (
            <div className="h-full flex flex-col items-center justify-center text-center p-6 text-slate-500">
              <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center text-slate-400 mb-3">
                <ShoppingCart className="w-8 h-8" />
              </div>
              <h3 className="font-bold text-slate-800 text-base">Your cart is currently empty</h3>
              <p className="text-xs text-slate-500 mt-1 max-w-xs">
                Explore our wide selection of school stationery, office supplies, and writing pens to get started.
              </p>
              <button
                onClick={() => setIsCartOpen(false)}
                className="mt-5 px-5 py-2.5 bg-blue-950 text-white text-xs font-extrabold rounded-xl hover:bg-slate-900 transition-colors"
              >
                Browse Products
              </button>
            </div>
          ) : (
            cart.map((item) => {
              const price = typeof item.product.price === "number" ? item.product.price : parseFloat(item.product.price);
              const itemTotal = price * item.quantity;
              return (
                <div
                  key={item.product.id}
                  className="flex gap-3 p-3 bg-slate-50 rounded-2xl border border-slate-200 hover:border-slate-300 transition-all"
                >
                  <img
                    src={item.product.image}
                    alt={item.product.name}
                    className="w-16 h-16 object-cover rounded-xl border border-slate-200 shrink-0 bg-white"
                  />

                  <div className="flex-1 min-w-0 flex flex-col justify-between">
                    <div>
                      <div className="flex justify-between items-start gap-1">
                        <h4 className="font-bold text-xs text-slate-900 line-clamp-2">
                          {item.product.name}
                        </h4>
                        <button
                          onClick={() => removeFromCart(item.product.id)}
                          className="text-slate-400 hover:text-rose-600 p-0.5"
                          title="Remove item"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                        </button>
                      </div>
                      <div className="text-[10px] text-slate-500 font-mono mt-0.5">
                        R{price.toFixed(2)} each
                      </div>
                    </div>

                    <div className="flex items-center justify-between mt-2 pt-1 border-t border-slate-200/60">
                      {/* Quantity Buttons */}
                      <div className="flex items-center border border-slate-300 rounded-lg bg-white overflow-hidden">
                        <button
                          onClick={() => updateQuantity(item.product.id, item.quantity - 1)}
                          className="p-1 text-slate-600 hover:bg-slate-100"
                        >
                          <Minus className="w-3 h-3" />
                        </button>
                        <span className="px-2 text-xs font-bold text-slate-900">{item.quantity}</span>
                        <button
                          onClick={() => updateQuantity(item.product.id, item.quantity + 1)}
                          className="p-1 text-slate-600 hover:bg-slate-100"
                        >
                          <Plus className="w-3 h-3" />
                        </button>
                      </div>

                      <span className="font-black text-slate-950 text-sm">
                        R{itemTotal.toFixed(2)}
                      </span>
                    </div>
                  </div>
                </div>
              );
            })
          )}
        </div>

        {/* Footer Area: Promo Code & Checkout Summary */}
        {cart.length > 0 && (
          <div className="p-4 bg-slate-50 border-t border-slate-200 space-y-3">
            {/* Promo Code Form */}
            {!appliedPromo ? (
              <form onSubmit={handleApplyPromo} className="flex gap-2">
                <div className="relative flex-1">
                  <input
                    type="text"
                    placeholder="Voucher code (e.g. DIVERSE10)"
                    value={promoInput}
                    onChange={(e) => setPromoInput(e.target.value)}
                    className="w-full pl-8 pr-3 py-1.5 bg-white border border-slate-300 rounded-xl text-xs uppercase font-medium focus:outline-none focus:ring-1 focus:ring-blue-900"
                  />
                  <Tag className="absolute left-2.5 top-2 w-3.5 h-3.5 text-slate-400" />
                </div>
                <button
                  type="submit"
                  className="px-3 py-1.5 bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold rounded-xl transition-colors shrink-0"
                >
                  Apply
                </button>
              </form>
            ) : (
              <div className="p-2 bg-emerald-50 border border-emerald-200 rounded-xl flex items-center justify-between text-xs font-bold text-emerald-800">
                <span className="flex items-center gap-1.5">
                  <Check className="w-3.5 h-3.5 text-emerald-600" />
                  Code {appliedPromo.code} applied!
                </span>
                <button onClick={removePromoCode} className="text-slate-500 hover:text-rose-600 text-[10px] underline">
                  Remove
                </button>
              </div>
            )}

            {promoMsg && !appliedPromo && (
              <p className={`text-[11px] font-semibold ${promoMsg.success ? "text-emerald-600" : "text-rose-600"}`}>
                {promoMsg.text}
              </p>
            )}

            {/* Calculations Breakdown */}
            <div className="space-y-1.5 text-xs text-slate-600 pt-1">
              <div className="flex justify-between">
                <span>Subtotal (incl. VAT)</span>
                <span className="font-semibold text-slate-900">R{subtotal.toFixed(2)}</span>
              </div>

              {discountAmount > 0 && (
                <div className="flex justify-between text-emerald-700 font-bold">
                  <span>Discount Applied</span>
                  <span>-R{discountAmount.toFixed(2)}</span>
                </div>
              )}

              <div className="flex justify-between text-slate-500 text-[11px]">
                <span>Estimated SA Courier Shipping</span>
                <span>{amountNeededForFreeShipping === 0 ? "FREE" : "Calculated at checkout (R85)"}</span>
              </div>

              <div className="flex justify-between text-sm font-black text-slate-950 pt-2 border-t border-slate-200">
                <span>Estimated Total</span>
                <span className="text-blue-950 text-base">
                  R{(subtotal - discountAmount + (amountNeededForFreeShipping === 0 ? 0 : 85)).toFixed(2)}
                </span>
              </div>
            </div>

            {/* Main Action Buttons */}
            <div className="space-y-2 pt-1">
              <button
                onClick={handleCheckoutClick}
                className="w-full py-3.5 bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 text-slate-950 font-black text-sm rounded-2xl shadow-md transition-all flex items-center justify-center gap-2 cursor-pointer"
              >
                <span>PROCEED TO CHECKOUT</span>
                <ArrowRight className="w-4 h-4" />
              </button>

              <button
                onClick={clearCart}
                className="w-full py-1.5 text-center text-slate-500 hover:text-rose-600 text-xs font-semibold"
              >
                Clear Shopping Cart
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
