"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect } from "react";
import { useCart } from "@/lib/cart-context";
import { formatPrice } from "@/lib/format";
import { QuantitySelector } from "./QuantitySelector";
import { EmptyState } from "./EmptyState";
import { siteConfig } from "@/lib/siteConfig";

export function CartDrawer() {
  const { isOpen, closeCart, lines, catalog, setQuantity, removeItem, subtotal, itemCount } =
    useCart();

  useEffect(() => {
    if (!isOpen) return;
    const onKey = (e: KeyboardEvent) => e.key === "Escape" && closeCart();
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [isOpen, closeCart]);

  if (!isOpen) return null;

  const resolvedLines = lines
    .map((l) => ({ line: l, product: catalog.find((p) => p.id === l.productId) }))
    .filter((x) => x.product);

  return (
    <div className="fixed inset-0 z-[60]" role="dialog" aria-modal="true" aria-label="Shopping cart">
      <button
        aria-label="Close cart"
        onClick={closeCart}
        className="absolute inset-0 animate-fade-in bg-black/40"
      />
      <div className="absolute right-0 top-0 flex h-full w-full max-w-md animate-slide-in flex-col bg-white shadow-2xl">
        <div className="flex items-center justify-between border-b border-black/[0.06] px-5 py-4">
          <h2 className="font-display text-lg font-semibold text-brand-ink">
            Your cart {itemCount > 0 && `(${itemCount})`}
          </h2>
          <button
            aria-label="Close cart"
            onClick={closeCart}
            className="rounded-full p-1.5 text-black/50 hover:bg-black/5 hover:text-brand-ink"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" d="M6 6l12 12M18 6L6 18" />
            </svg>
          </button>
        </div>

        <div className="flex-1 overflow-auto px-5 py-4">
          {resolvedLines.length === 0 ? (
            <EmptyState
              title="Your cart is empty"
              description="Browse the catalog and add something you like."
              action={
                <Link
                  href="/"
                  onClick={closeCart}
                  className="inline-block rounded-lg bg-brand-ink px-4 py-2 text-sm font-semibold text-white hover:bg-black"
                >
                  Start shopping
                </Link>
              }
            />
          ) : (
            <ul className="flex flex-col gap-4">
              {resolvedLines.map(({ line, product }) => (
                <li key={line.productId} className="flex gap-3">
                  <Link
                    href={`/product/${product!.slug}`}
                    onClick={closeCart}
                    className="relative h-20 w-20 shrink-0 overflow-hidden rounded-lg bg-brand-cream"
                  >
                    <Image
                      src={product!.images[0] ?? "/images/products/placeholder.webp"}
                      alt={product!.name}
                      fill
                      sizes="80px"
                      className="object-cover"
                    />
                  </Link>
                  <div className="flex flex-1 flex-col justify-between">
                    <div className="flex items-start justify-between gap-2">
                      <Link
                        href={`/product/${product!.slug}`}
                        onClick={closeCart}
                        className="line-clamp-2 text-sm font-medium text-brand-ink"
                      >
                        {product!.name}
                      </Link>
                      <button
                        aria-label={`Remove ${product!.name}`}
                        onClick={() => removeItem(line.productId)}
                        className="shrink-0 text-black/35 hover:text-danger"
                      >
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
                          <path strokeLinecap="round" d="M6 6l12 12M18 6L6 18" />
                        </svg>
                      </button>
                    </div>
                    <div className="flex items-center justify-between">
                      <QuantitySelector
                        quantity={line.quantity}
                        max={product!.stock}
                        size="sm"
                        onChange={(q) => setQuantity(line.productId, q)}
                      />
                      <span className="text-sm font-semibold text-brand-ink">
                        {formatPrice(product!.price * line.quantity)}
                      </span>
                    </div>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>

        {resolvedLines.length > 0 && (
          <div className="border-t border-black/[0.06] px-5 py-4">
            <div className="flex items-center justify-between text-sm text-black/60">
              <span>Subtotal</span>
              <span className="font-medium text-brand-ink">{formatPrice(subtotal)}</span>
            </div>
            <p className="mt-1 text-xs text-black/45">
              Delivery ({formatPrice(siteConfig.deliveryFee)}) and any promo code are
              applied at checkout.
            </p>
            <Link
              href="/checkout"
              onClick={closeCart}
              className="mt-3 block w-full rounded-lg bg-brand-orange py-3 text-center text-sm font-semibold text-white transition hover:bg-brand-orange-dark"
            >
              Checkout
            </Link>
          </div>
        )}
      </div>
    </div>
  );
}
