import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";

import { ProductGrid } from "@/components/products/ProductGrid";
import { ProductImage } from "@/components/products/ProductImage";
import { ProductPurchasePanel } from "@/components/cart/ProductPurchasePanel";
import { RatingStars } from "@/components/ui/RatingStars";
import { getProductById, getProductViews, getProducts } from "@/lib/products";
import { formatPrice, getStockLevel, STOCK_LABELS } from "@/lib/format";

/** Pre-render every product page at build time. */
export async function generateStaticParams() {
  const products = await getProducts();
  return products.map((product) => ({ id: String(product.id) }));
}

export async function generateMetadata({
  params,
}: PageProps<"/products/[id]">): Promise<Metadata> {
  const { id } = await params;
  const product = await getProductById(Number.parseInt(id, 10));

  if (!product) return { title: "Product not found" };

  return {
    title: product.name,
    description: product.description,
  };
}

export default async function ProductDetailPage({ params }: PageProps<"/products/[id]">) {
  const { id } = await params;
  const productId = Number.parseInt(id, 10);

  if (!Number.isInteger(productId)) notFound();

  const product = await getProductById(productId);
  if (!product) notFound();

  const stockLevel = getStockLevel(product.stock);

  return (
    <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
      <nav aria-label="Breadcrumb" className="mb-6 text-sm">
        <ol className="flex flex-wrap items-center gap-1.5 text-slate-500">
          <li>
            <Link href="/" className="hover:text-indigo-700 focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:outline-none">
              Home
            </Link>
          </li>
          <li aria-hidden="true">/</li>
          <li>
            <Link href="/products" className="hover:text-indigo-700 focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:outline-none">
              Products
            </Link>
          </li>
          <li aria-hidden="true">/</li>
          <li>
            <Link
              href={`/products?category=${encodeURIComponent(product.category)}`}
              className="hover:text-indigo-700 focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:outline-none"
            >
              {product.category}
            </Link>
          </li>
          <li aria-hidden="true">/</li>
          <li className="truncate text-slate-900" aria-current="page">
            {product.name}
          </li>
        </ol>
      </nav>

      <div className="grid gap-10 lg:grid-cols-2">
        <div className="overflow-hidden rounded-3xl border border-slate-200 bg-white">
          <ProductImage
            product={product}
            sizes="(min-width: 1024px) 50vw, 100vw"
            loading="eager"
            className="rounded-none"
          />
        </div>

        <div>
          <div className="flex flex-wrap items-center gap-2">
            <span className="rounded-full bg-indigo-50 px-3 py-1 text-xs font-semibold text-indigo-700">
              {product.category}
            </span>
            <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-600">
              {product.subcategory}
            </span>
            <span
              className={`rounded-full px-3 py-1 text-xs font-semibold ${
                stockLevel === "in-stock"
                  ? "bg-emerald-50 text-emerald-700"
                  : stockLevel === "low-stock"
                    ? "bg-amber-100 text-amber-900"
                    : "bg-slate-200 text-slate-700"
              }`}
            >
              {STOCK_LABELS[stockLevel]}
            </span>
          </div>

          <h1 className="mt-4 text-2xl font-bold tracking-tight text-slate-900 sm:text-3xl">
            {product.name}
          </h1>

          <p className="mt-2 text-sm text-slate-500">
            Brand:{" "}
            <Link
              href={`/products?brand=${encodeURIComponent(product.brand)}`}
              className="font-medium text-slate-700 underline-offset-2 hover:text-indigo-700 hover:underline focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:outline-none"
            >
              {product.brand}
            </Link>
          </p>

          <div className="mt-3">
            <RatingStars rating={product.rating} />
          </div>

          <p className="mt-5 text-lg leading-relaxed text-slate-700">{product.description}</p>

          <p className="mt-6 text-3xl font-bold text-slate-900">{formatPrice(product.price)}</p>
          <p className="mt-1 text-sm text-slate-500">
            {product.stock > 0
              ? `${product.stock} available — ships from our warehouse`
              : "Currently unavailable, check back soon"}
          </p>

          <div className="mt-7">
            <ProductPurchasePanel product={product} />
          </div>

          <div className="mt-8">
            <h2 className="text-sm font-semibold tracking-wide text-slate-900 uppercase">Tags</h2>
            <ul className="mt-3 flex flex-wrap gap-2">
              {product.tags.map((tag) => (
                <li key={tag}>
                  <Link
                    href={`/products?q=${encodeURIComponent(tag)}`}
                    className="inline-block rounded-full border border-slate-300 px-3 py-1 text-xs text-slate-600 transition-colors hover:border-indigo-300 hover:bg-indigo-50 hover:text-indigo-700 focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:outline-none"
                  >
                    {tag}
                  </Link>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>

      <section aria-labelledby="more-like-this" className="mt-16">
        <div className="flex flex-wrap items-end justify-between gap-3">
          <h2 id="more-like-this" className="text-xl font-bold text-slate-900">
            More in {product.category}
          </h2>
          <Link
            href={`/products?category=${encodeURIComponent(product.category)}`}
            className="text-sm font-semibold text-indigo-700 hover:text-indigo-900 focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:outline-none"
          >
            View all {product.category}
          </Link>
        </div>
        <RelatedProducts currentId={product.id} category={product.category} />
      </section>
    </div>
  );
}

async function RelatedProducts({ currentId, category }: { currentId: number; category: string }) {
  const related = (await getProductViews())
    .filter((product) => product.category === category && product.id !== currentId)
    .slice(0, 4);

  if (related.length === 0) return null;

  return (
    <div className="mt-6">
      <ProductGrid products={related} />
    </div>
  );
}
