"use client";

import Link from "next/link";
import { AnimatePresence, motion } from "framer-motion";
import { Minus, Plus, ShoppingBag, Trash2, X } from "lucide-react";
import { SafeImage } from "@/components/ui/SafeImage";
import { useCart } from "@/context/cart-context";
import { formatPrice } from "@/lib/format";

/** Right-side cart sidebar — opens after Add to cart. */
export function CartDrawer() {
  const {
    items,
    itemCount,
    subtotal,
    discount,
    shipping,
    total,
    isOpen,
    closeCart,
    removeItem,
    updateQuantity,
  } = useCart();

  return (
    <AnimatePresence>
      {isOpen ? (
        <motion.div
          key="cart-overlay"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-[70] bg-black/45"
          onClick={closeCart}
        >
          <motion.aside
            initial={{ x: "100%" }}
            animate={{ x: 0 }}
            exit={{ x: "100%" }}
            transition={{ type: "spring", stiffness: 320, damping: 34 }}
            className="absolute right-0 top-0 flex h-full w-full max-w-md flex-col bg-background shadow-2xl"
            onClick={(event) => event.stopPropagation()}
          >
            <div className="flex items-center justify-between border-b border-border px-5 py-4">
              <div>
                <p className="text-lg font-semibold tracking-tight">Your cart</p>
                <p className="text-xs text-muted">
                  {itemCount} {itemCount === 1 ? "item" : "items"}
                </p>
              </div>
              <button
                type="button"
                onClick={closeCart}
                className="inline-flex h-9 w-9 items-center justify-center rounded-full border border-border"
                aria-label="Close cart"
              >
                <X className="h-4 w-4" />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto px-5 py-4">
              {items.length === 0 ? (
                <div className="flex h-full flex-col items-center justify-center gap-3 text-center">
                  <ShoppingBag className="h-8 w-8 text-muted" />
                  <p className="text-sm text-muted">Your cart is empty.</p>
                  <Link
                    href="/shop"
                    onClick={closeCart}
                    className="rounded-full bg-foreground px-4 py-2 text-xs font-semibold text-background"
                  >
                    Continue shopping
                  </Link>
                </div>
              ) : (
                <ul className="space-y-4">
                  {items.map((item) => (
                    <li
                      key={`${item.product.id}-${item.variantLabel ?? ""}`}
                      className="flex gap-3 rounded-2xl border border-border bg-card p-3"
                    >
                      <Link
                        href={`/product/${item.product.id}`}
                        onClick={closeCart}
                        className="relative h-20 w-20 shrink-0 overflow-hidden rounded-xl bg-surface"
                      >
                        <SafeImage
                          src={item.product.images[0]}
                          alt={item.product.name}
                          fill
                          sizes="80px"
                          className="object-cover"
                        />
                      </Link>
                      <div className="min-w-0 flex-1">
                        <Link
                          href={`/product/${item.product.id}`}
                          onClick={closeCart}
                          className="line-clamp-2 text-sm font-medium leading-snug hover:opacity-70"
                        >
                          {item.product.name}
                        </Link>
                        {item.variantLabel ? (
                          <p className="mt-0.5 text-xs text-muted">
                            {item.variantLabel}
                          </p>
                        ) : null}
                        <p className="mt-1 text-sm font-semibold tabular-nums">
                          {formatPrice(item.product.price)}
                        </p>
                        <div className="mt-2 flex items-center justify-between">
                          <div className="inline-flex items-center rounded-full border border-border">
                            <button
                              type="button"
                              aria-label="Decrease quantity"
                              className="inline-flex h-7 w-7 items-center justify-center"
                              onClick={() =>
                                updateQuantity(
                                  item.product.id,
                                  item.quantity - 1,
                                  item.variantLabel,
                                )
                              }
                            >
                              <Minus className="h-3 w-3" />
                            </button>
                            <span className="w-6 text-center text-xs tabular-nums">
                              {item.quantity}
                            </span>
                            <button
                              type="button"
                              aria-label="Increase quantity"
                              className="inline-flex h-7 w-7 items-center justify-center"
                              onClick={() =>
                                updateQuantity(
                                  item.product.id,
                                  item.quantity + 1,
                                  item.variantLabel,
                                )
                              }
                            >
                              <Plus className="h-3 w-3" />
                            </button>
                          </div>
                          <button
                            type="button"
                            aria-label="Remove item"
                            onClick={() =>
                              removeItem(item.product.id, item.variantLabel)
                            }
                            className="inline-flex h-7 w-7 items-center justify-center rounded-full text-muted transition hover:bg-surface hover:text-foreground"
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </button>
                        </div>
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </div>

            {items.length > 0 ? (
              <div className="border-t border-border px-5 py-4">
                <div className="space-y-1.5 text-sm">
                  <div className="flex justify-between text-muted">
                    <span>Subtotal</span>
                    <span className="tabular-nums">{formatPrice(subtotal)}</span>
                  </div>
                  {discount > 0 ? (
                    <div className="flex justify-between text-muted">
                      <span>Discount</span>
                      <span className="tabular-nums">
                        −{formatPrice(discount)}
                      </span>
                    </div>
                  ) : null}
                  <div className="flex justify-between text-muted">
                    <span>Shipping</span>
                    <span className="tabular-nums">
                      {shipping === 0 ? "Free" : formatPrice(shipping)}
                    </span>
                  </div>
                  <div className="flex justify-between pt-1 text-base font-semibold">
                    <span>Total</span>
                    <span className="tabular-nums">{formatPrice(total)}</span>
                  </div>
                </div>
                <div className="mt-4 grid gap-2">
                  <Link
                    href="/checkout"
                    onClick={closeCart}
                    className="inline-flex h-11 items-center justify-center rounded-full bg-foreground text-sm font-semibold text-background transition hover:opacity-90"
                  >
                    Checkout
                  </Link>
                  <Link
                    href="/cart"
                    onClick={closeCart}
                    className="inline-flex h-10 items-center justify-center rounded-full border border-border text-sm font-medium transition hover:bg-card"
                  >
                    View full cart
                  </Link>
                </div>
              </div>
            ) : null}
          </motion.aside>
        </motion.div>
      ) : null}
    </AnimatePresence>
  );
}
