"use client";

import Image from "next/image";
import Link from "next/link";
import { Heart, ShoppingBag, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { useCartStore } from "@/store/cart-store";
import { useWishlistStore } from "@/store/wishlist-store";

export function WishlistDrawer() {
  const products = useWishlistStore((state) => state.products);
  const isOpen = useWishlistStore((state) => state.isOpen);
  const closeWishlist = useWishlistStore((state) => state.closeWishlist);
  const removeProduct = useWishlistStore((state) => state.removeProduct);
  const addItem = useCartStore((state) => state.addItem);

  return (
    <Sheet open={isOpen} onOpenChange={(open) => { if (!open) closeWishlist(); }}>
      <SheetContent>
        <SheetHeader>
          <SheetTitle>Mis favoritos</SheetTitle>
          <SheetDescription>{products.length} producto{products.length === 1 ? "" : "s"} guardado{products.length === 1 ? "" : "s"}.</SheetDescription>
        </SheetHeader>
        <div className="flex-1 space-y-4 overflow-y-auto p-6">
          {products.length === 0 ? (
            <div className="grid min-h-72 place-items-center rounded-3xl border border-dashed border-slate-300 bg-slate-50 text-center">
              <div><Heart className="mx-auto mb-3 size-10 text-fuchsia-500" /><p className="font-black">Aún no guardas favoritos</p><p className="mt-1 text-sm text-slate-500">Pulsa el corazón de cualquier producto.</p></div>
            </div>
          ) : products.map((product) => (
            <article key={product.id} className="grid grid-cols-[84px_1fr_auto] gap-4 rounded-2xl border border-slate-100 p-3 shadow-sm">
              <Link href={`/product/${product.slug}`} onClick={closeWishlist} className="relative aspect-square overflow-hidden rounded-xl bg-slate-100" prefetch={false}>
                <Image src={product.thumbnail} alt={product.name} fill sizes="84px" className="object-cover" />
              </Link>
              <div>
                <Link href={`/product/${product.slug}`} onClick={closeWishlist} prefetch={false} className="text-sm font-black leading-5 hover:text-fuchsia-600">{product.name}</Link>
                <p className="mt-1 text-xs text-slate-500">{product.category} · {product.collection}</p>
                <Button size="sm" variant="magenta" className="mt-3" onClick={() => addItem(product, product.variants[0]?.id)}><ShoppingBag className="size-3.5" />Agregar</Button>
              </div>
              <button className="self-start rounded-full p-2 text-slate-400 hover:bg-rose-50 hover:text-rose-600" onClick={() => removeProduct(product.id)} aria-label="Quitar favorito"><Trash2 className="size-4" /></button>
            </article>
          ))}
        </div>
      </SheetContent>
    </Sheet>
  );
}
