"use client";

/**
 * Top of a product page (/products/<slug>): gallery, title, variant picker, price and
 * product details. Markup and classes of the designed product page (/product-details);
 * the variant picker, price and specs are added in the same style.
 *
 * Variants (API reference, "How products work (website)"): one select per attribute,
 * starting from the default variant. Picking a value shows the variant that matches all
 * picked values; when none does, the closest variant with the new value is picked, so a
 * price is always shown. The gallery shows the picked variant's image, then its gallery
 * (or the product's when the variant has none).
 */
import Link from "next/link";
import { Fragment, useMemo, useState } from "react";
import { paragraphs } from "@/app/(site)/_components/pages/parts";
import type { Img } from "@/app/(site)/_lib/content";
import {
  dimensionsText,
  findVariant,
  formatMoney,
  isPossible,
  joinNames,
  quoteHref,
  unitLabel,
  volumeText,
  weightText,
  type ProductPageData,
  type ProductVariant,
} from "@/app/(site)/_lib/products";

const LANG = "en";

const Sep = () => (
  <li aria-hidden="true" className="text-[#c5ccd6]">
    &gt;
  </li>
);

const ThumbArrow = ({ d }: { d: string }) => (
  <svg className="w-3.5 h-3.5" viewBox="0 0 16 16" fill="none" aria-hidden="true">
    <path d={d} stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"></path>
  </svg>
);

/** The variant with `value` for `attr` that keeps most of the other picks. */
function closest(variants: ProductVariant[], picked: Record<string, string>, attr: string, value: string): ProductVariant | undefined {
  let best: ProductVariant | undefined;
  let score = -1;
  for (const v of variants) {
    if (v.attributes[attr] !== value) continue;
    const s = Object.entries(picked).filter(([a, val]) => a !== attr && v.attributes[a] === val).length;
    if (s > score) [best, score] = [v, s];
  }
  return best;
}

export function ProductDetail({ p }: { p: ProductPageData }) {
  const first = p.variants.find((v) => v.id === p.defaultVariantId) ?? p.variants[0];
  const [picked, setPicked] = useState<Record<string, string>>(first?.attributes ?? {});
  const variant = findVariant(p.variants, picked) ?? first;

  const images = useMemo(() => {
    const own = variant?.gallery.length ? variant.gallery : p.gallery;
    const list = [variant?.image ?? p.thumbnail, ...own].filter((x): x is Img => !!x?.url);
    return list.filter((img, i) => list.findIndex((x) => x.url === img.url) === i);
  }, [variant, p.gallery, p.thumbnail]);
  // The picked image, per variant: switching variants shows the new variant's first image.
  const [shown, setShown] = useState<{ variant?: string; index: number }>({ index: 0 });
  const active = shown.variant === variant?.id ? Math.min(shown.index, images.length - 1) : 0;
  const show = (index: number) => setShown({ variant: variant?.id, index });
  const main = images[active] ?? p.thumbnail;

  const pick = (attr: string, value: string) => {
    const next = { ...picked, [attr]: value };
    if (findVariant(p.variants, next)) return setPicked(next);
    const v = closest(p.variants, picked, attr, value);
    if (v) setPicked({ ...v.attributes });
  };

  const onRequest = p.priceVisibility === "on-request";
  const selling = variant?.sellingPrice;
  const market = variant?.marketPrice;
  const { group, category } = p.breadcrumb ?? { group: null, category: null };
  const specs = [
    ["Size", dimensionsText(variant?.dimensions ?? null)],
    ["Weight", weightText(variant?.weight ?? null)],
    ["Available volume", volumeText(p.volumeMt)],
    ["Minimum order", p.moq ? `${p.moq.value} ${unitLabel(p.moq.unit)}` : null],
  ].filter((s): s is [string, string] => !!s[1]);

  return (
    <section className="product-detail-section" data-product-live="">
      <div className="w-full max-w-[1180px] mx-auto px-6" data-reveal="">
        <div className="product-detail-layout">
          <div className="product-detail-gallery">
            <div className="product-detail-gallery-main">
              {main?.url && <img id="product-main-image" src={main.url} alt={main.alt ?? p.name} width="560" height="420" loading="eager" />}
            </div>
            {images.length > 1 && (
              <div className="product-detail-thumbs" aria-label="Product image thumbnails">
                <button type="button" className="product-detail-thumb-nav" aria-label="Previous thumbnail" disabled={active === 0} onClick={() => show(active - 1)}>
                  {" "}
                  <ThumbArrow d="M10 3L5 8l5 5" />{" "}
                </button>{" "}
                <div className="product-detail-thumb-list">
                  {images.map((img, i) => (
                    <Fragment key={img.url}>
                      {i > 0 && " "}
                      <button type="button" className={`product-detail-thumb${i === active ? " is-active" : ""}`} aria-label={`View image ${i + 1}`} aria-pressed={i === active} onClick={() => show(i)}>
                        {" "}
                        <img src={img.url} alt="" width="72" height="72" loading="lazy" />{" "}
                      </button>
                    </Fragment>
                  ))}
                </div>{" "}
                <button type="button" className="product-detail-thumb-nav" aria-label="Next thumbnail" disabled={active >= images.length - 1} onClick={() => show(active + 1)}>
                  {" "}
                  <ThumbArrow d="M6 3l5 5-5 5" />{" "}
                </button>
              </div>
            )}
          </div>
          <div className="product-detail-intro">
            <nav className="product-detail-breadcrumb" aria-label="Breadcrumb">
              <ol>
                <li>
                  <Link href="/">Home</Link>
                </li>
                <Sep />
                <li>
                  <Link href="/product-services">Products</Link>
                </li>
                <Sep />
                {group && (
                  <>
                    <li>
                      <Link href={`/global-agriculture?category=${encodeURIComponent(group.slug)}`}>{group.name}</Link>
                    </li>
                    <Sep />
                  </>
                )}
                <li className="text-ink font-medium" aria-current="page">
                  {p.name}
                </li>
              </ol>
            </nav>
            <div className="product-detail-header">
              <div className="product-detail-header-text">
                <h1 className="product-detail-title">{p.name}</h1>
                {category && (
                  <p className="product-detail-category">
                    <strong>Category:</strong> {category.name}
                  </p>
                )}
              </div>
              {p.files.map((f) => (
                <Fragment key={f.url}>
                  {" "}
                  <a href={f.url} className="product-detail-download" download target="_blank" rel="noopener">
                    {" "}
                    <svg viewBox="0 0 20 20" fill="none" aria-hidden="true">
                      <path d="M10 3v9M6 9l4 4 4-4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"></path>
                      <path d="M4 14v2a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1v-2" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"></path>
                    </svg>{" "}
                    {f.label}{" "}
                  </a>
                </Fragment>
              ))}
            </div>
            <div className="product-detail-buy">
              {!onRequest && selling != null && (
                <p className="product-detail-price">
                  {market != null && market > selling && <s>{formatMoney(market, p.currency, LANG)}</s>} <strong>{formatMoney(selling, p.currency, LANG)}</strong>{" "}
                  <span>/ {unitLabel(p.priceUnit)}</span>
                </p>
              )}
              {p.attributes.length > 0 && (
                <div className="product-detail-options">
                  {p.attributes.map((a) => (
                    <label key={a.slug} className="product-detail-option">
                      <span>{a.name}</span>
                      <select value={picked[a.slug] ?? ""} onChange={(e) => pick(a.slug, e.target.value)}>
                        {a.values.map((v) => (
                          <option key={v.slug} value={v.slug}>
                            {v.label}
                            {isPossible(p.variants, picked, a.slug, v.slug) ? "" : " (changes other options)"}
                          </option>
                        ))}
                      </select>
                    </label>
                  ))}
                </div>
              )}
              {(variant?.sku || specs.length > 0) && (
                <dl className="product-detail-specs">
                  {variant?.sku && (
                    <div>
                      <dt>SKU</dt>
                      <dd>{variant.sku}</dd>
                    </div>
                  )}
                  {specs.map(([label, value]) => (
                    <div key={label}>
                      <dt>{label}</dt>
                      <dd>{value}</dd>
                    </div>
                  ))}
                </dl>
              )}
              <Link href={quoteHref(p.slug, variant?.sku)} className="product-detail-quote">
                Request a quote
              </Link>
            </div>
            <hr className="product-detail-divider" />
          </div>
          <div className="product-detail-body">
            <h2 className="product-detail-heading">Product Details</h2>
            <div className="product-detail-meta">
              {p.origin.length > 0 && (
                <span className="product-detail-meta-item">
                  Origin : <strong>{joinNames(p.origin.map((o) => o.name))}</strong>
                </span>
              )}
              {p.certifications.map((c) => (
                <Fragment key={c.slug}>
                  {" "}
                  <span className="product-detail-meta-item">
                    <strong>{c.name}</strong>
                  </span>
                </Fragment>
              ))}
              {p.details.map((d, i) => (
                <Fragment key={i}>
                  {" "}
                  <span className="product-detail-meta-item">
                    {d.label}: <strong>&nbsp;{d.text}</strong>
                  </span>
                </Fragment>
              ))}
            </div>
            {p.description && (
              <div className="product-detail-content">
                {paragraphs(p.description).map((para, i) => (
                  <p key={i} className="product-detail-desc">
                    {para}
                  </p>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
