"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, type MouseEvent } from "react";
import { Heart, Plus } from "lucide-react";
import type { Product } from "@/data/types";
import { useCart } from "@/context/cart-context";
import { useWishlist } from "@/context/wishlist-context";
import { SafeImage } from "@/components/ui/SafeImage";
import { colorToHex } from "@/lib/color-swatch";
import { discountPercent, formatPrice } from "@/lib/format";
import { cn } from "@/lib/cn";

function defaultVariantLabel(product: Product) {
  const parts = product.variants
    .map((variant) => variant.options[0])
    .filter(Boolean);
  return parts.length ? parts.join(" / ") : undefined;
}

/** Editorial BhoFit plate — matted photo, hover motion, add-to-bag. */
export function ProductCard({
  product,
  index = 0,
  compact = false,
}: {
  product: Product;
  index?: number;
  compact?: boolean;
  showProgress?: boolean;
}) {
  const router = useRouter();
  const { addItem, items } = useCart();
  const { toggle, has } = useWishlist();
  const href = `/product/${product.id}`;
  const saved = has(product.id);
  const inBag = items.some((item) => item.product.id === product.id);
  const off = discountPercent(product.price, product.compareAt);
  const colorVariant = product.variants.find((v) => v.id === "color");
  const colors = colorVariant?.options.slice(0, 5) ?? [];
  const genderLabel =
    product.gender === "unisex" ? "Unisex" : product.gender;
  const look = String(index + 1).padStart(2, "0");
  const out = product.stock <= 0;

  useEffect(() => {
    router.prefetch(href);
  }, [href, router]);

  const onAdd = (event: MouseEvent) => {
    event.preventDefault();
    event.stopPropagation();
    if (out) return;
    addItem(product, 1, defaultVariantLabel(product));
  };

  return (
    <article
      className={cn("product-card group flex h-full flex-col", compact && "is-compact")}
      style={{ animationDelay: `${Math.min(index, 12) * 55}ms` }}
    >
      <div className="product-card-plate relative bg-[var(--paper)] p-[5px] shadow-[0_1px_0_rgba(18,22,20,0.04)]">
        {off > 0 ? (
          <span
            aria-hidden
            className="absolute left-0 top-4 z-[2] h-8 w-[2px] origin-top bg-[var(--accent)] transition-transform duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] group-hover:scale-y-[1.35]"
          />
        ) : (
          <span
            aria-hidden
            className="absolute left-0 top-5 z-[2] h-0 w-[2px] origin-top bg-[var(--accent)] transition-all duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] group-hover:h-7"
          />
        )}

        <Link
          href={href}
          prefetch
          className="product-card-shot relative block aspect-[4/5] overflow-hidden bg-surface"
        >
          <SafeImage
            src={product.images[0]}
            alt={product.name}
            fill
            sizes="(max-width: 640px) 50vw, 25vw"
            className="object-cover object-center"
            loading="lazy"
          />
          <span
            aria-hidden
            className="product-card-shine pointer-events-none absolute inset-y-0 -left-1/2 z-[1] w-[70%]"
          />
        </Link>

        <button
          type="button"
          aria-label="Wishlist"
          onClick={(event) => {
            event.preventDefault();
            toggle(product);
          }}
          className="absolute right-2.5 top-2.5 z-[3] inline-flex h-7 w-7 items-center justify-center bg-[var(--paper)]/85 text-foreground backdrop-blur-[2px] transition duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] group-hover:-translate-y-0.5 group-hover:scale-105"
        >
          <Heart
            className={cn(
              "h-3.5 w-3.5 transition-transform duration-500",
              saved && "fill-[var(--accent)] text-[var(--accent)]",
              saved && "scale-110",
            )}
            strokeWidth={1.5}
          />
        </button>
      </div>

      <div className="mt-2.5 flex min-h-0 flex-1 flex-col px-0.5">
        <div className="flex h-4 items-center justify-between gap-2">
          <p className="font-display text-[12px] leading-none text-muted">
            {look}
          </p>
          <p className="text-[9px] font-medium uppercase tracking-[0.18em] text-muted">
            {genderLabel}
          </p>
        </div>
        <Link
          href={href}
          className="font-display mt-1.5 block h-[2.3em] line-clamp-2 text-[16px] leading-[1.15] text-foreground transition-colors duration-500 group-hover:text-[var(--accent)]"
        >
          {product.name}
        </Link>
        <div className="mt-1.5 flex h-5 items-center justify-between gap-2">
          <p className="flex min-w-0 items-baseline gap-1.5">
            <span className="font-display text-[15px] tabular-nums leading-none">
              {formatPrice(product.price)}
            </span>
            {product.compareAt ? (
              <span className="text-[10px] text-muted line-through tabular-nums">
                {formatPrice(product.compareAt)}
              </span>
            ) : null}
          </p>
          {colors.length > 0 ? (
            <div className="flex shrink-0 items-center gap-[3px]">
              {colors.map((option) => {
                const hex = colorToHex(option) ?? "#d4d4d4";
                return (
                  <span
                    key={option}
                    title={option}
                    className="h-[7px] w-[7px] rounded-full ring-1 ring-black/10"
                    style={{ backgroundColor: hex }}
                  />
                );
              })}
            </div>
          ) : null}
        </div>
        <button
          type="button"
          onClick={onAdd}
          disabled={out}
          aria-label={out ? "Out of stock" : `Add ${product.name} to cart`}
          className={cn(
            "mt-2.5 flex h-8 w-full shrink-0 items-center justify-center gap-1.5 text-[9px] font-medium uppercase tracking-[0.16em] transition duration-300",
            out
              ? "cursor-not-allowed bg-[#121614]/50 text-white/70"
              : inBag
                ? "bg-[var(--accent)] text-white"
                : "bg-[#121614] text-[var(--on-ink)] hover:bg-[var(--accent)]",
          )}
        >
          <Plus className="h-3 w-3" strokeWidth={1.75} />
          {out ? "Out of stock" : inBag ? "In bag" : "Add to cart"}
        </button>
      </div>
    </article>
  );
}
