"use client";

import { useState } from "react";
import Link from "next/link";
import { formatPrice } from "@/lib/format";
import type { PublicProduct } from "@/lib/merch-public";

// One merch product: swipeable photo gallery, sale price, option picker and
// "Add". Used by the shop page and the event page's "Add merch" strip.
export default function MerchProductCard({
  product: p,
  chosenVariantId,
  onChoose,
  onAdd,
  inCart = 0,
  compact = false,
}: {
  product: PublicProduct;
  chosenVariantId: string;
  onChoose: (variantId: string) => void;
  onAdd: () => void;
  inCart?: number;
  compact?: boolean;
}) {
  const [photo, setPhoto] = useState(0);
  const v = p.variants.find((x) => x.id === chosenVariantId);
  const soldOutAll = p.variants.every((x) => x.available === 0);
  const prices = p.variants.map((x) => x.priceCents);
  const min = Math.min(...prices);
  const max = Math.max(...prices);
  const images = p.images;

  return (
    <article className="flex h-full flex-col overflow-hidden rounded-2xl border border-line bg-panel">
      <div className="relative aspect-square bg-bg">
        {images.length > 0 && (
          // eslint-disable-next-line @next/next/no-img-element
          <img src={images[photo] ?? images[0]} alt={p.name} className="h-full w-full object-cover" />
        )}
        {p.compareAtCents && (
          <span className="absolute left-3 top-3 rounded-full bg-brand-orange px-2.5 py-0.5 text-[11px] font-bold uppercase text-white">
            Sale
          </span>
        )}
        {images.length > 1 && (
          <>
            <button
              type="button"
              aria-label="Previous photo"
              onClick={() => setPhoto((i) => (i - 1 + images.length) % images.length)}
              className="absolute left-2 top-1/2 h-8 w-8 -translate-y-1/2 rounded-full bg-black/50 text-white"
            >
              ‹
            </button>
            <button
              type="button"
              aria-label="Next photo"
              onClick={() => setPhoto((i) => (i + 1) % images.length)}
              className="absolute right-2 top-1/2 h-8 w-8 -translate-y-1/2 rounded-full bg-black/50 text-white"
            >
              ›
            </button>
            <div className="absolute bottom-2 left-0 right-0 flex justify-center gap-1.5">
              {images.map((_, i) => (
                <button
                  key={i}
                  type="button"
                  aria-label={`Photo ${i + 1}`}
                  onClick={() => setPhoto(i)}
                  className={`h-2 w-2 rounded-full ${i === photo ? "bg-white" : "bg-white/40"}`}
                />
              ))}
            </div>
          </>
        )}
      </div>
      <div className={`flex flex-1 flex-col gap-2 ${compact ? "p-3" : "p-4"}`}>
        {p.event && !compact && (
          <Link href={p.event.href} className="text-[11px] font-semibold uppercase tracking-wider text-brand-green-h">
            {p.event.title}
          </Link>
        )}
        <h3 className={`font-bold ${compact ? "text-sm" : ""}`}>{p.name}</h3>
        {p.description && !compact && <p className="text-sm text-muted">{p.description}</p>}
        <p className="flex items-baseline gap-2">
          <span className={`${compact ? "text-base" : "text-lg"} font-black`}>
            {min === max ? formatPrice(min, "kes") : `${formatPrice(min, "kes")} – ${formatPrice(max, "kes")}`}
          </span>
          {p.compareAtCents && (
            <span className="text-sm text-muted line-through">{formatPrice(p.compareAtCents, "kes")}</span>
          )}
        </p>
        <div className="mt-auto space-y-2 pt-1">
          {p.variants.length > 1 && (
            <select
              value={chosenVariantId}
              onChange={(e) => onChoose(e.target.value)}
              className="input"
              aria-label={`Option for ${p.name}`}
            >
              {p.variants.map((x) => (
                <option key={x.id} value={x.id} disabled={x.available === 0}>
                  {x.label}
                  {x.available === 0 ? " — sold out" : ""}
                  {x.priceCents !== p.priceCents ? ` (${formatPrice(x.priceCents, "kes")})` : ""}
                </option>
              ))}
            </select>
          )}
          <button
            type="button"
            onClick={onAdd}
            disabled={soldOutAll || !v || v.available === 0}
            className="w-full rounded-full bg-brand-orange px-4 py-2 text-sm font-semibold text-white hover:brightness-110 disabled:opacity-50"
          >
            {soldOutAll ? "Sold out" : inCart > 0 ? `Added (${inCart}) — add another` : "Add to cart"}
          </button>
        </div>
      </div>
    </article>
  );
}
