"use client";

import Link from "next/link";
import { Plus } from "lucide-react";
import { useCart } from "@/context/cart-context";
import { discountPercent, formatPrice, splitPrice } from "@/lib/format";
import { cn } from "@/lib/cn";
import type { Product } from "@/data/types";
import { SafeImage } from "@/components/ui/SafeImage";

const CLAIMS: Record<string, string> = {
  "gluten-free": "Gluten-free",
  "dairy-free": "Dairy-free",
  "zero-cal": "Zero sugar",
  "low-fat": "Low fat",
  "whole-grain": "Whole grain",
  organic: "Organic",
  vegetarian: "Vegetarian",
  protein: "Protein",
};

function PriceMark({ amount }: { amount: number }) {
  const { dollars, cents } = splitPrice(amount);
  return (
    <span className="price-mark" aria-label={formatPrice(amount)}>
      <span className="cur">$</span>
      <span className="dol">{Number(dollars)}</span>
      <span className="cent">{cents}</span>
    </span>
  );
}

export function GroceryTile({
  product,
  layout = "rail",
}: {
  product: Product;
  layout?: "rail" | "grid";
}) {
  const { addItem } = useCart();
  const off = discountPercent(product.price, product.compareAt);
  const claim = product.tags.find((t) => CLAIMS[t]);
  const plenty = product.stock > 20;
  const stockLabel = plenty
    ? "Plenty in the bin"
    : product.stock > 0
      ? "Last few bins"
      : "Bin empty";

  return (
    <article
      className={cn(
        "group/tile tile-lift silo-paper flex h-full flex-col overflow-hidden rounded-[1.15rem] border border-border",
        layout === "rail" ? "w-[220px] shrink-0 sm:w-[240px]" : "min-w-0 w-full",
      )}
    >
      <Link href={`/product/${product.id}`} className="relative block overflow-hidden">
        <span className="group/promo relative block aspect-square bg-surface p-2.5">
          <span className="relative block h-full w-full overflow-hidden rounded-[0.85rem]">
            <SafeImage
              src={product.images[0]}
              alt={product.name}
              fill
              sizes="240px"
              className="object-cover transition duration-700 ease-out group-hover/tile:scale-[1.07]"
            />
            <span className="pointer-events-none absolute inset-0 bg-[linear-gradient(to_top,rgba(22,58,54,0.22),transparent_42%)]" />
            <span className="promo-reflection" />
          </span>
        </span>
        {off > 0 ? (
          <span className="absolute left-3.5 top-3.5 rounded-full bg-[var(--brand-orange)] px-2.5 py-1 text-[10px] font-bold tracking-[0.06em] text-white">
            {off}% CUT
          </span>
        ) : null}
      </Link>

      <div className="flex flex-1 flex-col px-3.5 pb-4 pt-1">
        <p className="text-[10px] font-semibold uppercase tracking-[0.18em] text-[var(--straw)]">
          {product.seller}
        </p>
        <Link
          href={`/product/${product.id}`}
          className="mt-1 line-clamp-2 min-h-[2.55em] font-serif text-[1.05rem] font-semibold leading-snug tracking-tight text-foreground transition group-hover/tile:text-[var(--spruce-ink)]"
        >
          {product.name}
        </Link>
        <p className="mt-1 text-[11px] text-muted">{product.shortDescription}</p>

        <div className="mt-3 flex items-end justify-between gap-2">
          <div>
            <PriceMark amount={product.price} />
            {product.compareAt ? (
              <p className="mt-0.5 text-[11px] text-muted line-through tabular-nums">
                {formatPrice(product.compareAt)}
              </p>
            ) : null}
          </div>
          {claim ? (
            <span className="mb-0.5 rounded-full border border-[color-mix(in_srgb,var(--spruce)_30%,var(--border))] bg-[color-mix(in_srgb,var(--spruce)_8%,transparent)] px-2 py-0.5 text-[10px] font-semibold text-[var(--spruce-ink)]">
              {CLAIMS[claim]}
            </span>
          ) : null}
        </div>

        <p className="mt-3 inline-flex items-center gap-1.5 text-[11px] text-muted">
          <span
            className={cn(
              "h-1.5 w-1.5 rounded-full",
              product.stock === 0
                ? "bg-[var(--brand-orange)]"
                : plenty
                  ? "bg-[var(--spruce)]"
                  : "bg-[var(--straw)]",
            )}
          />
          {stockLabel}
        </p>

        <button
          type="button"
          disabled={product.stock === 0}
          onClick={() => addItem(product)}
          className="btn-bin btn-bin-wide mt-3 disabled:cursor-not-allowed"
        >
          <Plus className="h-3.5 w-3.5" strokeWidth={2.6} />
          Add to cart
        </button>
      </div>
    </article>
  );
}
