"use client";

import Link from "next/link";
import { Heart, PackageOpen, Plus, Scale, Star } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { useCart } from "@/components/cart-provider";
import { useSiteSettings } from "@/components/site-settings-provider";
import { formatPrice, getDiscountPercent, productImageUrl, type Product } from "@/lib/commerce";

export function PriceBlock({ product, compact = false }: { product: Product; compact?: boolean }) {
  const settings = useSiteSettings();
  const discount = getDiscountPercent(product);
  return (
    <div className="space-y-1 text-left" dir="ltr">
      {settings.productCard.showConsumerPrice && discount > 0 ? (
        <div className={`consumer-price text-zinc-900 dark:text-zinc-200 ${compact ? "text-xs" : "text-sm"}`}>
          {formatPrice(product.consumerPrice)}
        </div>
      ) : <div className="h-5" />}
      <div className="flex items-baseline justify-end gap-1 text-zinc-950 dark:text-white">
        <span className={compact ? "text-base font-black" : "text-xl font-black"}>{formatPrice(product.salePrice)}</span>
        <span className="text-xs font-medium">{settings.currency}</span>
      </div>
    </div>
  );
}

export function ProductVisual({ product, className = "" }: { product: Product; className?: string }) {
  const url = productImageUrl(product);
  if (url) return <img src={url} alt={product.name} className={`h-full w-full object-contain ${className}`} loading="lazy" />;
  return (
    <div className={`flex h-full w-full items-center justify-center bg-[radial-gradient(circle_at_30%_20%,#ffffff_0%,#eef2f7_55%,#dde5ef_100%)] ${className}`}>
      <div className="flex flex-col items-center gap-3 text-center text-slate-400">
        <PackageOpen className="h-16 w-16 stroke-[1.3]" />
        <span className="max-w-36 text-xs font-medium">تصویر کالا را از پنل مدیریت اضافه کنید</span>
      </div>
    </div>
  );
}

export function ProductCard({ product, emphasis = false }: { product: Product; emphasis?: boolean }) {
  const cart = useCart();
  const settings = useSiteSettings();
  const discount = getDiscountPercent(product);
  const rating = product.rating > 5 ? product.rating / 10 : product.rating;
  const soldOut = product.stock <= 0;
  return (
    <article className={`group relative flex h-full min-w-0 flex-col overflow-hidden border bg-white transition duration-300 hover:-translate-y-1 hover:shadow-xl dark:bg-slate-900 ${settings.layout.cardDensity === "compact" ? "p-2.5" : "p-4"} ${emphasis ? "border-white/50" : "border-slate-200/80 dark:border-slate-700"}`} style={{ borderRadius: "var(--shop-card-radius)" }}>
      {settings.productCard.showDiscountBadge && discount > 0 && (
        <span className="absolute left-3 top-3 z-10 rounded-full bg-[var(--shop-accent)] px-2.5 py-1 text-xs font-black text-white shadow-sm" dir="rtl">
          ٪{new Intl.NumberFormat("fa-IR").format(discount)}
        </span>
      )}
      <div className="absolute right-3 top-3 z-10 flex flex-col gap-1 opacity-0 transition group-hover:opacity-100 focus-within:opacity-100">
        {settings.productCard.showFavorite && <Button aria-label="افزودن به علاقه‌مندی" size="icon" variant="secondary" className="h-8 w-8 rounded-full bg-white/95" onClick={() => cart.toggleFavorite(product.id)}><Heart className={`h-4 w-4 ${cart.favorites.includes(product.id) ? "fill-[var(--shop-accent)] text-[var(--shop-accent)]" : ""}`} /></Button>}
        {settings.productCard.showCompare && <Button aria-label="افزودن به مقایسه" size="icon" variant="secondary" className="h-8 w-8 rounded-full bg-white/95" onClick={() => cart.toggleCompare(product.id)}><Scale className={`h-4 w-4 ${cart.compare.includes(product.id) ? "text-[var(--shop-primary)]" : ""}`} /></Button>}
      </div>
      <Link href={`/product/${encodeURIComponent(product.id)}`} className="block aspect-square overflow-hidden rounded-2xl bg-slate-50">
        <ProductVisual product={product} />
      </Link>
      <div className="flex flex-1 flex-col px-1 pb-1 pt-3">
        <div className="mb-2 flex min-h-5 items-center justify-between gap-2 text-xs">
          {settings.productCard.showCategory ? <span className="truncate text-slate-500">{product.category}</span> : <span />}
          {settings.productCard.showRating && <span className="flex items-center gap-1 font-bold text-slate-700 dark:text-slate-200" dir="ltr">
            {rating.toFixed(1)} <Star className="h-3.5 w-3.5 fill-amber-400 text-amber-400" />
          </span>}
        </div>
        <Link href={`/product/${encodeURIComponent(product.id)}`} className="line-clamp-2 min-h-12 text-sm font-bold leading-6 text-slate-800 transition hover:text-[var(--shop-primary)] dark:text-slate-100">
          {product.name}
        </Link>
        {settings.productCard.showStock && !soldOut && product.stock <= 5 && <span className="mt-2 text-xs font-bold text-amber-600">تنها {new Intl.NumberFormat("fa-IR").format(product.stock)} عدد باقی مانده</span>}
        <div className="mt-auto flex items-end justify-between gap-2 pt-4">
          <Button title={settings.labels.addToCart} aria-label={settings.labels.addToCart} disabled={soldOut} size="icon" className="h-10 w-10 shrink-0 rounded-full bg-[var(--shop-primary)] text-white hover:brightness-95" onClick={() => { cart.addItem(product); toast.success(`${product.name} به سبد اضافه شد`); }}>
            <Plus className="h-5 w-5" />
          </Button>
          {soldOut ? <span className="pb-2 text-sm font-bold text-slate-400">{settings.labels.unavailable}</span> : <PriceBlock product={product} compact />}
        </div>
      </div>
    </article>
  );
}
