"use client";

import Link from "next/link";
import { useState } from "react";
import type { Product } from "@/lib/api";
import { addToCart, unitPrice } from "@/lib/cart";

/**
 * Buy box: colour/shade swatches (other variants of the same product), quantity-tier
 * pricing ("buy more, pay less"), minimum order and case-pack quick picks.
 */
export default function PdpBuy({ p }: { p: Product }) {
  const min = Math.max(1, p.minOrder || 1);
  const [qty, setQty] = useState(min);
  const [added, setAdded] = useState(false);
  const tiers = p.tiers ?? [];
  const unit = unitPrice({ price: p.price, qty, tiers });
  const out = p.inStock === false;
  const clamp = (n: number) => Math.max(min, Math.min(999, n || min));

  function add() {
    addToCart({
      id: p.slug, name: p.name, brand: p.brand, price: p.price, image: p.image || "", qty,
      tiers: tiers.map(({ qty, price }) => ({ qty, price })), minOrder: p.minOrder ?? null,
    });
    setAdded(true);
    setTimeout(() => setAdded(false), 1400);
  }

  return (
    <>
      {(p.variants?.length ?? 0) > 1 && (
        <div className="pb-pdp-variants">
          <div className="pb-pdp-variants-label">
            {p.variantGroup?.includes("hair-colour") ? "Shade" : "Colour"}: <strong>{p.variant}</strong>
          </div>
          <div className="pb-swatches" role="list">
            {p.variants!.map((v) => (
              <Link
                key={v.slug}
                href={`/portal/product/${v.slug}`}
                role="listitem"
                className={`pb-swatch${v.current ? " is-current" : ""}${v.hex ? "" : " pb-swatch--text"}`}
                title={v.name}
                aria-label={v.name}
                aria-current={v.current ? "true" : undefined}
                style={v.hex ? { background: v.hex } : undefined}
                scroll={false}
              >
                {!v.hex && v.name.replace(/^Shade /, "")}
              </Link>
            ))}
          </div>
        </div>
      )}

      {tiers.length > 0 && (
        <div className="pb-tiers" aria-label="Volume pricing">
          <div className="pb-tiers-head">Buy more, pay less</div>
          <table>
            <tbody>
              <tr className={unit === p.price ? "is-active" : ""}>
                <td>1{tiers[0].qty > 2 ? `–${tiers[0].qty - 1}` : ""} units</td>
                <td>AED {p.price} / unit</td>
              </tr>
              {tiers.map((t, i) => {
                const next = tiers[i + 1];
                const active = qty >= t.qty && (!next || qty < next.qty);
                return (
                  <tr key={t.qty} className={active ? "is-active" : ""}>
                    <td>{t.qty}{next ? `–${next.qty - 1}` : "+"} units</td>
                    <td>
                      AED {t.price} / unit <em>save {Math.round((1 - t.price / p.price) * 100)}%</em>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      <div className="pb-pdp-buy">
        <div className="pb-qty" data-qty>
          <button type="button" aria-label="Decrease quantity" onClick={() => setQty((q) => clamp(q - 1))}>−</button>
          <input type="text" value={qty} inputMode="numeric" aria-label="Quantity"
            onChange={(e) => setQty(clamp(parseInt(e.target.value)))} />
          <button type="button" aria-label="Increase quantity" onClick={() => setQty((q) => clamp(q + 1))}>+</button>
        </div>
        <button className="pb-btn pb-btn--primary pb-btn--lg" onClick={add} disabled={out}>
          <span>{out ? "Out of stock" : added ? "Added ✓" : `Add to cart · AED ${(unit * qty).toLocaleString("en-AE")}`}</span>
        </button>
      </div>
      {(p.caseSize || p.minOrder) && (
        <div className="pb-pdp-packs">
          {p.minOrder && p.minOrder > 1 && <span>Minimum order {p.minOrder} units.</span>}
          {p.caseSize && (
            <button type="button" className="pb-chip" onClick={() => setQty(clamp(Math.ceil(qty / p.caseSize!) * p.caseSize! || p.caseSize!))}>
              Round up to full case ({p.caseSize} units)
            </button>
          )}
        </div>
      )}
    </>
  );
}
