import type { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { Container } from "@/components/Container";
import { Button } from "@/components/Button";
import { Breadcrumbs } from "@/components/Breadcrumbs";
import {
  getPublishedProductBySlug,
  listPublishedProducts,
  formatPrice,
} from "@/lib/store/queries";
import { renderMarkdown } from "@/lib/markdown/render";
import { AddToCartForm } from "@/components/store/AddToCartForm";

export const dynamic = "force-dynamic";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const product = await getPublishedProductBySlug(slug);
  if (!product) return { title: "Product not found" };
  return {
    title: `${product.title} · Store`,
    description: product.shortDescription || undefined,
    openGraph: {
      title: product.title,
      description: product.shortDescription || undefined,
      images: product.coverImage ? [product.coverImage] : undefined,
    },
  };
}

const STOCK_LABEL: Record<string, string> = {
  in_stock: "In stock",
  out_of_stock: "Out of stock",
  preorder: "Pre-order",
  coming_soon: "Coming soon",
};

const STOCK_TONE: Record<string, string> = {
  in_stock: "bg-emerald-50 text-emerald-700 ring-emerald-200",
  out_of_stock: "bg-red-50 text-red-700 ring-red-200",
  preorder: "bg-amber-50 text-amber-800 ring-amber-200",
  coming_soon: "bg-slate-100 text-slate-700 ring-slate-200",
};

export default async function StoreProductPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const [product, allProducts] = await Promise.all([
    getPublishedProductBySlug(slug),
    listPublishedProducts(),
  ]);
  if (!product) notFound();

  const gallery = Array.isArray(product.gallery) ? product.gallery : [];
  const allImages: Array<{ path: string; alt: string | null }> = [];
  if (product.coverImage) {
    allImages.push({
      path: product.coverImage,
      alt: product.coverImageAlt ?? product.title,
    });
  }
  for (const g of gallery) {
    if (g.path) allImages.push({ path: g.path, alt: g.alt ?? product.title });
  }

  const related = allProducts
    .filter((p) => p.id !== product.id)
    .slice(0, 3);

  const descriptionHtml = product.description
    ? renderMarkdown(product.description)
    : "";

  return (
    <>
      <section className="border-b border-[var(--color-line)] bg-white">
        <Container>
          <div className="py-8 md:py-14">
            <Breadcrumbs
              items={[
                { label: "OrthoGlobe Store", href: "/products/store" },
                { label: product.title },
              ]}
            />

            <div className="mt-6 grid gap-12 md:grid-cols-[1fr_1.1fr] md:items-start">
              <div className="flex flex-col gap-4">
                <div className="relative aspect-[4/3] overflow-hidden rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)] shadow-[0_30px_64px_rgba(10,14,40,0.10)]">
                  {allImages[0] ? (
                    <Image
                      src={allImages[0].path}
                      alt={allImages[0].alt ?? product.title}
                      fill
                      sizes="(min-width: 1024px) 560px, 100vw"
                      className="object-cover"
                      priority
                    />
                  ) : null}
                </div>
                {allImages.length > 1 ? (
                  <div className="grid grid-cols-4 gap-3">
                    {allImages.slice(1, 9).map((img, i) => (
                      <div
                        key={`${img.path}-${i}`}
                        className="relative aspect-square overflow-hidden rounded-lg border border-[var(--color-line)] bg-[var(--color-mist)]"
                      >
                        <Image
                          src={img.path}
                          alt={img.alt ?? product.title}
                          fill
                          sizes="(min-width: 1024px) 140px, 25vw"
                          className="object-cover"
                        />
                      </div>
                    ))}
                  </div>
                ) : null}
              </div>

              <div>
                <div className="flex flex-wrap items-center gap-2">
                  <span
                    className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-bold uppercase tracking-wider ring-1 ring-inset ${STOCK_TONE[product.stockStatus] ?? STOCK_TONE.coming_soon}`}
                  >
                    {STOCK_LABEL[product.stockStatus] ?? "—"}
                  </span>
                  {product.memberOnly ? (
                    <span className="inline-flex items-center rounded-full bg-[var(--color-blue)]/10 px-2.5 py-0.5 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)] ring-1 ring-inset ring-[var(--color-blue)]/30">
                      Members only
                    </span>
                  ) : null}
                </div>
                <h1 className="mt-4 font-display text-[40px] font-extrabold leading-[1.05] tracking-[-0.025em] text-[var(--color-ink)] md:text-[52px]">
                  {product.title}
                </h1>
                {product.shortDescription && (
                  <p className="mt-6 text-[18px] leading-[1.55] text-[var(--color-slate)]">
                    {product.shortDescription}
                  </p>
                )}
                <div className="mt-6 font-display text-[32px] font-extrabold text-[var(--color-ink)]">
                  {formatPrice(product.priceMinor, product.currency)}
                </div>
                <div className="mt-8 flex flex-wrap items-center gap-4">
                  {product.stockStatus === "in_stock" ||
                  product.stockStatus === "preorder" ? (
                    <AddToCartForm
                      productId={product.id}
                      label={
                        product.stockStatus === "preorder"
                          ? "Pre-order"
                          : "Add to cart"
                      }
                    />
                  ) : (
                    <Button href="/contact" variant="ghost">
                      Notify me when available
                    </Button>
                  )}
                  <Button href="/products/store" variant="ghost">
                    Back to catalogue
                  </Button>
                  <Button href="/products/store/cart" variant="ghost">
                    View cart →
                  </Button>
                </div>
                {product.sku && (
                  <div className="mt-6 text-[13px] text-[var(--color-slate)]">
                    SKU: {product.sku}
                  </div>
                )}
              </div>
            </div>
          </div>
        </Container>
      </section>

      {descriptionHtml ? (
        <section className="bg-[var(--color-mist)]/30 py-16">
          <Container>
            <div className="mx-auto max-w-3xl">
              <h2 className="font-display text-[24px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
                About this product
              </h2>
              <article
                className="prose prose-slate mt-6 max-w-none text-[16px] leading-relaxed text-[var(--color-slate)]"
                dangerouslySetInnerHTML={{ __html: descriptionHtml }}
              />
            </div>
          </Container>
        </section>
      ) : null}

      {related.length > 0 ? (
        <section className="border-t border-[var(--color-line)] bg-white py-16">
          <Container className="max-w-7xl">
            <h2 className="font-display text-[24px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
              More from the store
            </h2>
            <div className="mt-6 grid gap-6 md:grid-cols-3">
              {related.map((p) => (
                <Link
                  key={p.id}
                  href={`/products/store/${p.slug}`}
                  className="group flex flex-col overflow-hidden rounded-2xl border border-[var(--color-line)] bg-white transition-[border-color,box-shadow] hover:border-[var(--color-blue)] hover:shadow-[0_20px_48px_rgba(30,64,255,0.08)]"
                >
                  <div className="relative aspect-[4/3] w-full bg-[var(--color-mist)]">
                    {p.coverImage && (
                      <Image
                        src={p.coverImage}
                        alt={p.coverImageAlt ?? p.title}
                        fill
                        sizes="(min-width: 1024px) 360px, (min-width: 768px) 50vw, 100vw"
                        className="object-cover"
                      />
                    )}
                  </div>
                  <div className="flex flex-1 flex-col p-5">
                    <h3 className="font-display text-[18px] font-extrabold leading-tight tracking-[-0.01em] text-[var(--color-ink)] group-hover:text-[var(--color-blue)]">
                      {p.title}
                    </h3>
                    <div className="mt-auto flex items-center justify-between pt-4 text-[13px]">
                      <span className="font-semibold text-[var(--color-ink)]">
                        {formatPrice(p.priceMinor, p.currency)}
                      </span>
                      <span className="text-[var(--color-slate)]">
                        {STOCK_LABEL[p.stockStatus] ?? "Coming soon"}
                      </span>
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          </Container>
        </section>
      ) : null}
    </>
  );
}
