"use client";

import { useEffect, useRef, useState } from "react";
import { useCart } from "@/lib/cartStore";
import Image from "next/image";
import cloudinaryLoader from "@/lib/cloudinaryLoader";
import Link from "next/link";
import { X, Minus, Plus, Trash, ShoppingBag } from "lucide-react";
import { useLanguage } from "@/lib/i18n/context";

export default function CartDrawer() {
  const { t, locale } = useLanguage();
  const isRTL = locale === "ar";
  const { items, isOpen, closeCart, updateQty, removeItem, clearCart, total, count } = useCart();
  const itemsRef = useRef<HTMLDivElement>(null);
  const [mounted, setMounted] = useState(false);
  useEffect(() => { setMounted(true); }, []);

  // Prevent body scroll; let wheel events scroll the drawer items directly
  useEffect(() => {
    document.body.style.overflow = isOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [isOpen]);

  useEffect(() => {
    const el = itemsRef.current;
    if (!el) return;
    const onWheel = (e: WheelEvent) => {
      e.stopPropagation();
      el.scrollTop += e.deltaY;
    };
    el.addEventListener("wheel", onWheel, { passive: true });
    return () => el.removeEventListener("wheel", onWheel);
  }, []);

  return (
    <>
      {/* Backdrop */}
      {isOpen && (
        <div
          className="fixed inset-0 bg-black/50 z-40 backdrop-blur-sm"
          onClick={closeCart}
        />
      )}

      {/* Drawer */}
      <div
        className={`fixed top-0 h-[100dvh] w-full max-w-md bg-brand-sand-light z-50 flex flex-col shadow-2xl transition-transform duration-400 ease-in-out ${isRTL ? "left-0" : "right-0"}`}
        style={{ transform: isOpen ? "translateX(0)" : isRTL ? "translateX(-100%)" : "translateX(100%)" }}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-5 border-b border-brand-dark/10">
          <div className="flex items-center gap-3">
            <ShoppingBag size={20} className="text-brand-section" />
            <span className="text-brand-dark font-bold text-lg" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
              {t.cart.title}
            </span>
            {mounted && count() > 0 && (
              <span className="bg-brand-yellow text-brand-dark text-xs font-bold rounded-full w-5 h-5 flex items-center justify-center">
                {count()}
              </span>
            )}
          </div>
          <button onClick={closeCart} className="text-brand-dark/40 hover:text-brand-dark transition-colors">
            <X size={22} />
          </button>
        </div>

        {/* Items */}
        <div ref={itemsRef} className="flex-1 min-h-0 overflow-y-auto overscroll-contain px-6 py-4 space-y-4">
          {items.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full gap-4 text-center">
              <ShoppingBag size={48} className="text-brand-dark/15" />
              <p className="text-brand-dark/40 text-sm">{t.cart.empty}</p>
              <button
                onClick={closeCart}
                className="text-brand-section-accent text-sm font-semibold hover:underline"
              >
                {t.cart.continueShopping}
              </button>
            </div>
          ) : (
            items.map(item => {
              const hasWholesale = !!(item.price_gros && item.price_gros > 0 && item.min_qty_gros && item.min_qty_gros > 1);
              const isGros       = hasWholesale && item.quantity >= item.min_qty_gros!;
              const unitPrice    = isGros ? item.price_gros! : item.price;
              const lineTotal    = unitPrice * item.quantity;
              const fullTotal    = item.price  * item.quantity;

              return (
                <div
                  key={`${item.id}-${item.size}`}
                  className="relative bg-brand-dark/5 rounded-2xl p-4 border border-brand-dark/8 hover:border-brand-dark/15 transition-colors"
                >
                  {/* Delete */}
                  <button
                    onClick={() => removeItem(item.id, item.size)}
                    className={`absolute top-3 ${isRTL ? "left-3" : "right-3"} w-7 h-7 rounded-full bg-brand-dark/8 flex items-center justify-center text-brand-dark/35 hover:bg-red-500/20 hover:text-red-400 transition-colors`}
                  >
                    <Trash size={13} />
                  </button>

                  <div className="flex gap-4 items-center">
                    {/* Image */}
                    <div className="w-20 h-20 rounded-2xl bg-brand-dark/10 flex-shrink-0 relative overflow-hidden">
                      {item.image_url && (
                        <Image loader={cloudinaryLoader} src={item.image_url} alt={item.name} fill className="object-contain p-2" sizes="80px" />
                      )}
                    </div>

                    {/* Info + controls */}
                    <div className={`flex-1 min-w-0 ${isRTL ? "pl-7" : "pr-7"}`}>
                      <p className="text-brand-dark text-[15px] font-semibold leading-snug" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
                        {item.name}
                      </p>
                      {item.size && (
                        <span className="inline-block bg-brand-dark/10 text-brand-dark/55 text-[10px] font-bold px-2.5 py-0.5 rounded-full mt-1 tracking-wide">
                          {item.size}
                        </span>
                      )}

                      <div className="flex items-center justify-between mt-3">
                        {/* Qty stepper */}
                        <div className="flex items-center gap-1 bg-brand-dark/10 rounded-full p-1">
                          <button
                            onClick={() => updateQty(item.id, item.quantity - 1, item.size)}
                            className="w-6 h-6 rounded-full flex items-center justify-center bg-brand-dark/10 text-brand-dark hover:bg-brand-dark/25 transition-colors"
                          >
                            <Minus size={10} />
                          </button>
                          <span className="text-brand-dark text-sm font-bold w-6 text-center">{item.quantity}</span>
                          <button
                            onClick={() => updateQty(item.id, item.quantity + 1, item.size)}
                            className="w-6 h-6 rounded-full flex items-center justify-center bg-brand-dark/10 text-brand-dark hover:bg-brand-dark/25 transition-colors"
                          >
                            <Plus size={10} />
                          </button>
                        </div>

                        {/* Price */}
                        <div className="text-right">
                          {isGros && (
                            <span className="inline-block bg-brand-yellow text-brand-dark text-[9px] font-bold px-2 py-0.5 rounded-full mb-1">
                              Prix gros ✓
                            </span>
                          )}
                          <p className="text-brand-dark font-bold text-base" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
                            {lineTotal.toLocaleString("fr-MR")} MRU
                          </p>
                          {isGros ? (
                            <p className="text-brand-dark/35 text-[10px] line-through">
                              {fullTotal.toLocaleString("fr-MR")} MRU
                            </p>
                          ) : item.quantity > 1 ? (
                            <p className="text-brand-dark/35 text-[10px]">
                              {unitPrice.toLocaleString("fr-MR")} × {item.quantity}
                            </p>
                          ) : null}
                        </div>
                      </div>

                      {/* Wholesale hint — shown when not yet at threshold */}
                      {hasWholesale && !isGros && (
                        <p className="text-brand-dark/35 text-[10px] mt-2">
                          Prix gros dès {item.min_qty_gros} pcs → {item.price_gros!.toLocaleString("fr-MR")} MRU/u
                        </p>
                      )}
                    </div>
                  </div>
                </div>
              );
            })
          )}
        </div>

        {/* Footer */}
        {items.length > 0 && (
          <div className="border-t border-brand-dark/10 px-6 pt-5 pb-[max(1.25rem,env(safe-area-inset-bottom))] space-y-4">
            <div className="flex items-center justify-between">
              <span className="text-brand-dark/50 text-sm">{t.cart.total}</span>
              <span className="text-brand-dark font-bold text-lg" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
                {total().toLocaleString("fr-MR")} MRU
              </span>
            </div>
            <Link
              href="/commander"
              onClick={closeCart}
              className="block w-full bg-brand-yellow text-brand-dark font-bold py-4 rounded-2xl text-sm text-center tracking-wide hover:bg-brand-yellow/90 transition-colors"
            >
              {t.cart.checkout}
            </Link>
            <button
              onClick={clearCart}
              className="w-full text-brand-dark/30 text-xs font-semibold hover:text-red-400 transition-colors py-1"
            >
              {t.cart.clear}
            </button>
          </div>
        )}
      </div>
    </>
  );
}
