"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { motion } from "framer-motion";
import { Heart, ShoppingBag, Star } 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 { discountPercent, formatPrice } from "@/lib/format";
import { easeOut } from "@/lib/motion";
import { cn } from "@/lib/cn";

/** Modern marketplace product card — brand colors, clean hierarchy. */
export function ProductCard({
  product,
  index = 0,
  showProgress = false,
}: {
  product: Product;
  index?: number;
  compact?: boolean;
  showProgress?: boolean;
}) {
  const router = useRouter();
  const { addItem } = useCart();
  const { toggle, has } = useWishlist();
  const href = `/product/${product.id}`;

  useEffect(() => {
    router.prefetch(href);
  }, [href, router]);
  const saved = has(product.id);
  const off = discountPercent(product.price, product.compareAt);
  const progress =
    product.flashLimit && product.sold != null
      ? Math.min(100, Math.round((product.sold / product.flashLimit) * 100))
      : 0;

  const optionVariant =
    product.variants.find((variant) => variant.id === "color") ||
    product.variants.find((variant) => variant.id === "pack") ||
    product.variants[0];
  const options = optionVariant?.options.slice(0, 3) ?? [];

  return (
    <motion.article
      initial={{ opacity: 0, y: 14 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true, margin: "-24px" }}
      transition={{
        duration: 0.4,
        delay: Math.min(index * 0.03, 0.16),
        ease: easeOut,
      }}
      whileHover={{ y: -4 }}
      className="group flex h-full flex-col overflow-hidden rounded-2xl border border-border/80 bg-card shadow-[var(--shadow-soft)] transition hover:border-[color-mix(in_srgb,var(--brand-blue)_35%,var(--border))]"
    >
      <Link
        href={href}
        prefetch
        className="relative block aspect-[5/4] overflow-hidden bg-surface"
      >
        <SafeImage
          src={product.images[0]}
          alt={product.name}
          fill
          sizes="(max-width: 768px) 50vw, 20vw"
          className="object-cover object-center transition duration-500 group-hover:scale-[1.05]"
          loading="lazy"
        />
        <div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/35 via-transparent to-transparent opacity-80" />
        {off > 0 ? (
          <span className="absolute left-3 top-3 rounded-full bg-[var(--brand-orange)] px-2.5 py-1 text-[10px] font-bold tracking-wide text-white shadow">
            -{off}%
          </span>
        ) : null}
        {product.stock > 0 && product.stock <= 8 ? (
          <span className="absolute right-3 top-3 rounded-full bg-black/70 px-2 py-1 text-[10px] font-semibold text-white backdrop-blur">
            Only {product.stock} left
          </span>
        ) : null}
      </Link>

      <div className="flex flex-1 flex-col px-3.5 pb-3.5 pt-3 sm:px-4 sm:pb-4">
        <div className="flex items-center justify-between gap-2">
          <p className="truncate text-[10px] font-semibold uppercase tracking-[0.14em] text-[var(--brand-blue)]">
            {product.category}
          </p>
          <p className="inline-flex shrink-0 items-center gap-1 text-[11px] font-medium text-foreground">
            <Star className="h-3 w-3 fill-[var(--brand-orange)] text-[var(--brand-orange)]" />
            {product.rating.toFixed(1)}
          </p>
        </div>

        <Link
          href={href}
          prefetch
          className="mt-1.5 line-clamp-2 text-[13px] font-semibold leading-snug tracking-tight text-foreground transition hover:text-[var(--brand-blue)] sm:text-sm"
        >
          {product.name}
        </Link>

        <div className="mt-2 flex items-baseline gap-2">
          <p className="text-base font-bold tabular-nums text-foreground">
            {formatPrice(product.price)}
          </p>
          {product.compareAt ? (
            <p className="text-xs text-muted line-through tabular-nums">
              {formatPrice(product.compareAt)}
            </p>
          ) : null}
        </div>

        {options.length > 0 ? (
          <div className="mt-2.5 flex flex-wrap gap-1">
            {options.map((option) => (
              <span
                key={option}
                className="inline-flex h-6 items-center rounded-md border border-border bg-surface/70 px-1.5 text-[10px] font-medium text-muted"
              >
                {option}
              </span>
            ))}
          </div>
        ) : null}

        {showProgress && product.flashLimit ? (
          <div className="mt-2.5">
            <div className="h-1.5 overflow-hidden rounded-full bg-surface">
              <motion.div
                initial={{ width: 0 }}
                whileInView={{ width: `${progress}%` }}
                viewport={{ once: true }}
                transition={{ duration: 0.8, ease: easeOut }}
                className="h-full rounded-full bg-[var(--brand-orange)]"
              />
            </div>
            <p className="mt-1 text-[10px] text-muted">
              Selling fast · {product.sold}/{product.flashLimit}
            </p>
          </div>
        ) : null}

        <div className="mt-auto flex items-center gap-2 pt-3.5">
          <button
            type="button"
            onClick={() => addItem(product)}
            className="inline-flex h-10 flex-1 items-center justify-center gap-1.5 rounded-xl bg-[var(--brand-blue)] text-[11px] font-bold uppercase tracking-[0.06em] text-white transition hover:bg-[var(--brand-blue-deep)]"
          >
            <ShoppingBag className="h-3.5 w-3.5" />
            Add
          </button>
          <button
            type="button"
            aria-label="Wishlist"
            onClick={() => toggle(product)}
            className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-border bg-background transition hover:border-[var(--brand-orange)] hover:bg-surface"
          >
            <Heart
              className={cn(
                "h-4 w-4 text-[var(--brand-orange)]",
                saved && "fill-[var(--brand-orange)]",
              )}
            />
          </button>
        </div>
      </div>
    </motion.article>
  );
}
