"use client";

import Link from "next/link";
import { AnimatePresence, motion } from "framer-motion";
import { ClipboardList, Minus, Plus, Trash2, Truck, X } from "lucide-react";
import { useCart } from "@/context/CartContext";

const formatPkr = (amount: number) =>
  `Rs. ${amount.toLocaleString("en-PK", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

export default function CartDrawer() {
  const {
    items,
    totalPrice,
    isCartOpen,
    closeCart,
    updateQuantity,
    removeFromCart,
  } = useCart();

  return (
    <AnimatePresence>
      {isCartOpen && (
        <>
          <motion.button
            type="button"
            aria-label="Close cart"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-[70] bg-foreground/40"
            onClick={closeCart}
          />
          <motion.aside
            initial={{ x: "100%" }}
            animate={{ x: 0 }}
            exit={{ x: "100%" }}
            transition={{ type: "spring", stiffness: 380, damping: 36 }}
            className="fixed inset-y-0 right-0 z-[80] flex w-full max-w-md flex-col bg-card shadow-elevated"
          >
            <div className="flex items-center justify-between border-b border-border px-5 py-4">
              <h2 className="text-sm font-bold uppercase tracking-[0.12em]">Shopping Cart</h2>
              <button
                type="button"
                onClick={closeCart}
                className="rounded-lg p-2 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
              >
                <X className="h-5 w-5" />
              </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 text-center">
                  <p className="text-sm font-semibold">Your cart is empty</p>
                  <p className="mt-1 text-xs text-muted-foreground">Add products to get started.</p>
                  <Link
                    href="/products"
                    onClick={closeCart}
                    className="mt-5 rounded-xl bg-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground"
                  >
                    Browse products
                  </Link>
                </div>
              ) : (
                <div className="space-y-5">
                  {items.map((item) => {
                    const image =
                      item.product.colors.find((c) => c.name === item.selectedColor)?.image ||
                      item.product.colors[0]?.image;
                    return (
                      <div key={`${item.product.id}-${item.selectedColor}`} className="flex gap-3">
                        <Link
                          href={`/product/${item.product.id}`}
                          onClick={closeCart}
                          className="h-20 w-20 shrink-0 overflow-hidden rounded-lg border border-border bg-secondary"
                        >
                          {image ? (
                            // eslint-disable-next-line @next/next/no-img-element
                            <img src={image} alt={item.product.name} className="h-full w-full object-cover" />
                          ) : (
                            <div className="flex h-full w-full items-center justify-center text-[10px] text-muted-foreground">
                              No image
                            </div>
                          )}
                        </Link>
                        <div className="min-w-0 flex-1">
                          <Link
                            href={`/product/${item.product.id}`}
                            onClick={closeCart}
                            className="line-clamp-2 text-sm font-semibold uppercase tracking-wide hover:text-primary"
                          >
                            {item.product.name}
                          </Link>
                          <div className="mt-1 flex items-baseline gap-2">
                            {item.product.originalPrice ? (
                              <span className="text-xs text-muted-foreground line-through">
                                {formatPkr(item.product.originalPrice)}
                              </span>
                            ) : null}
                            <span className="text-sm font-bold text-primary">
                              {formatPkr(item.product.price)}
                            </span>
                          </div>
                          <div className="mt-3 flex items-center gap-2">
                            <div className="inline-flex items-center rounded-full border border-border bg-secondary/50">
                              <button
                                type="button"
                                onClick={() =>
                                  updateQuantity(item.product.id, item.selectedColor, item.quantity - 1)
                                }
                                className="flex h-8 w-8 items-center justify-center text-muted-foreground hover:text-foreground"
                              >
                                {item.quantity <= 1 ? (
                                  <Trash2 className="h-3.5 w-3.5" />
                                ) : (
                                  <Minus className="h-3.5 w-3.5" />
                                )}
                              </button>
                              <span className="w-7 text-center text-sm font-semibold">{item.quantity}</span>
                              <button
                                type="button"
                                onClick={() =>
                                  updateQuantity(item.product.id, item.selectedColor, item.quantity + 1)
                                }
                                className="flex h-8 w-8 items-center justify-center text-muted-foreground hover:text-foreground"
                              >
                                <Plus className="h-3.5 w-3.5" />
                              </button>
                            </div>
                            <button
                              type="button"
                              onClick={() => removeFromCart(item.product.id, item.selectedColor)}
                              className="rounded-lg p-2 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
                              aria-label="Remove item"
                            >
                              <Trash2 className="h-4 w-4" />
                            </button>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>

            {items.length > 0 && (
              <div className="border-t border-border bg-secondary/30 px-5 py-4">
                <div className="mb-4 flex justify-center gap-3">
                  <span className="flex h-10 w-10 items-center justify-center rounded-full border border-border bg-card shadow-card">
                    <ClipboardList className="h-4 w-4 text-muted-foreground" />
                  </span>
                  <span className="flex h-10 w-10 items-center justify-center rounded-full border border-border bg-card shadow-card">
                    <Truck className="h-4 w-4 text-muted-foreground" />
                  </span>
                </div>

                <div className="flex items-center justify-between text-sm">
                  <span className="font-medium">Subtotal:</span>
                  <span className="font-bold">{formatPkr(totalPrice)} PKR</span>
                </div>
                <p className="mt-1 text-xs text-muted-foreground">
                  Taxes and shipping calculated at checkout.
                </p>

                <div className="mt-4 space-y-2">
                  <Link
                    href="/cart"
                    onClick={closeCart}
                    className="flex w-full items-center justify-center rounded-xl border border-border bg-secondary px-4 py-3 text-sm font-bold uppercase tracking-wide transition-colors hover:bg-secondary/80"
                  >
                    View Cart
                  </Link>
                  <Link
                    href="/checkout"
                    onClick={closeCart}
                    className="flex w-full items-center justify-center rounded-xl bg-primary px-4 py-3 text-sm font-bold uppercase tracking-wide text-primary-foreground transition-all hover:opacity-90"
                  >
                    Check Out
                  </Link>
                </div>
              </div>
            )}
          </motion.aside>
        </>
      )}
    </AnimatePresence>
  );
}
