"use client";

import Link from "next/link";
import { useCart } from "@/context/CartContext";

/** Best-effort swatch colour parsed off the front of a "Color / Size" variant label — the
 *  cart API doesn't return a product image on line items, so the drawer falls back to a
 *  small colour chip + initials tile instead of a thumbnail (see report for this approximation). */
function swatchFromLabel(label: string | undefined): string | null {
  if (!label) return null;
  const first = label.split("/")[0]?.trim();
  return first || null;
}

function initials(name: string): string {
  return name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((w) => w[0])
    .join("")
    .toUpperCase();
}

/** Slide-out cart drawer: line items, qty steppers, remove, subtotal, checkout CTA.
 *  Extends CartIcon's click target (openDrawer) rather than routing to a full /cart page,
 *  per the design brief's "Cart drawer" requirement — /cart still exists as a fallback route
 *  for direct links / no-JS. */
export default function CartDrawer() {
  const { cart, loading, isDrawerOpen, closeDrawer, removeItem, setQuantity } = useCart();

  if (!isDrawerOpen) return null;

  return (
    <div className="fixed inset-0 z-[60]">
      <button
        aria-label="Close cart"
        onClick={closeDrawer}
        className="absolute inset-0 bg-[#1d2739]/50"
      />
      <div className="absolute right-0 top-0 h-full w-full max-w-md bg-white shadow-xl flex flex-col">
        <div className="flex items-center justify-between border-b border-[rgba(29,39,57,0.18)] px-6 py-5">
          <h2 className="font-black uppercase text-lg text-[#1d2739]">
            Your Bag [{cart?.items.reduce((s, i) => s + i.quantity, 0) ?? 0}]
          </h2>
          <button
            onClick={closeDrawer}
            className="text-[11px] font-bold uppercase tracking-wide text-[#b08968] hover:text-[#8f6d51]"
          >
            Close
          </button>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-4">
          {loading ? (
            <p className="text-sm text-[#6f7885]">Loading…</p>
          ) : !cart || cart.items.length === 0 ? (
            <p className="text-sm text-[#6f7885]">Your bag is empty.</p>
          ) : (
            <ul className="divide-y divide-[rgba(29,39,57,0.12)]">
              {cart.items.map((item) => {
                const swatch = swatchFromLabel(item.variantLabel);
                return (
                  <li key={item.variantId} className="py-4 flex gap-4">
                    <div
                      className="h-16 w-16 shrink-0 bg-[#f0f2f5] flex items-center justify-center text-[10px] font-bold uppercase text-[#6f7885]"
                      style={swatch ? { backgroundColor: swatch } : undefined}
                    >
                      {!swatch ? initials(item.productName) : null}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start justify-between gap-3">
                        <p className="text-[13px] font-bold uppercase text-[#1d2739] leading-tight">{item.productName}</p>
                        <span className="shrink-0 text-sm font-bold text-[#1d2739]">${item.lineTotal.toFixed(2)}</span>
                      </div>
                      {item.variantLabel ? (
                        <p className="mt-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-[#6f7885]">
                          {swatch ? <span className="h-2.5 w-2.5 border border-[rgba(29,39,57,0.25)]" style={{ backgroundColor: swatch }} /> : null}
                          {item.variantLabel}
                        </p>
                      ) : null}
                      <div className="mt-2 flex items-center gap-4">
                        <div className="flex items-center border border-[rgba(29,39,57,0.25)]">
                          <button
                            onClick={() => setQuantity(item.variantId, item.quantity - 1)}
                            className="h-6 w-6 text-sm hover:bg-[#f5f6f8]"
                            aria-label="Decrease quantity"
                          >
                            −
                          </button>
                          <span className="w-7 text-center text-xs font-semibold">{item.quantity}</span>
                          <button
                            onClick={() => setQuantity(item.variantId, item.quantity + 1)}
                            disabled={item.quantity >= item.stockQty}
                            className="h-6 w-6 text-sm hover:bg-[#f5f6f8] disabled:opacity-40"
                            aria-label="Increase quantity"
                          >
                            +
                          </button>
                        </div>
                        <button
                          onClick={() => removeItem(item.variantId)}
                          className="text-[10px] font-bold uppercase tracking-wide text-[#b08968] hover:text-[#8f6d51]"
                        >
                          Remove
                        </button>
                      </div>
                    </div>
                  </li>
                );
              })}
            </ul>
          )}
        </div>

        {cart && cart.items.length > 0 ? (
          <div className="border-t border-[rgba(29,39,57,0.18)] px-6 py-5">
            <div className="flex justify-between text-base font-black uppercase text-[#1d2739]">
              <span>Subtotal</span>
              <span>${cart.subtotal.toFixed(2)}</span>
            </div>
            <p className="mt-1 text-xs text-[#6f7885]">Shipping and tax calculated at checkout.</p>
            <Link
              href="/checkout"
              onClick={closeDrawer}
              className="mt-4 flex w-full items-center justify-center bg-[#b08968] hover:bg-[#8f6d51] text-white text-xs font-bold uppercase tracking-wide py-4 transition-colors"
            >
              Checkout
            </Link>
            <Link href="/cart" onClick={closeDrawer} className="mt-3 block text-center text-[11px] font-semibold uppercase tracking-wide text-[#6f7885] hover:text-[#1d2739]">
              View full bag
            </Link>
          </div>
        ) : null}
      </div>
    </div>
  );
}
