import Image from 'next/image';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import type { Metadata } from 'next';
import { getProductDetail } from '@/lib/catalog';
import { getCurrentAccount } from '@/lib/account';
import { ROUTES, productRoute, vendorStorefrontRoute } from '@/lib/routes';
import { ProductCard } from '@/components/shop/product-card';
import { ProductQuantityAddToCart } from '@/components/shop/product-quantity-add-to-cart';
import { InquiryForm } from '@/components/shop/inquiry-form';
import { getSiteSettings, formatPrice } from '@/lib/site-settings';

// Product slugs are admin-managed and can change at any time, so this page
// is rendered on demand (per request) rather than pre-built at deploy time —
// no generateStaticParams here.

export async function generateMetadata({ params }: { params: { slug: string } }): Promise<Metadata> {
  const detail = await getProductDetail(params.slug);
  if (!detail) return { title: 'Product Not Found' };
  return { title: detail.product.name };
}

export default async function ProductDetailsPage({ params }: { params: { slug: string } }) {
  const detail = await getProductDetail(params.slug);

  if (!detail) {
    notFound();
  }

  const { product, related: relatedProducts } = detail;
  const [account, settings] = await Promise.all([
    product.buyable ? Promise.resolve(null) : getCurrentAccount(),
    getSiteSettings(),
  ]);

  return (
    <>
      {/* Breadcrumb */}
      <div className="border-b border-navy-100 bg-beige py-4">
        <div className="container-page">
          <nav aria-label="Breadcrumb" className="flex flex-wrap items-center gap-2 text-xs text-navy-600">
            <Link href={ROUTES.home} className="hover:text-gold-600">Home</Link>
            <span aria-hidden="true">/</span>
            <Link href={ROUTES.shop} className="hover:text-gold-600">Shop</Link>
            <span aria-hidden="true">/</span>
            <Link
              href={`${ROUTES.shop}?category=${encodeURIComponent(product.category)}`}
              className="hover:text-gold-600"
            >
              {product.category}
            </Link>
            <span aria-hidden="true">/</span>
            <span className="font-medium text-navy-800">{product.name}</span>
          </nav>
        </div>
      </div>

      <section className="py-12">
        <div className="container-page grid gap-10 lg:grid-cols-2">
          {/* Image */}
          <div className="overflow-hidden rounded-lg bg-beige">
            <Image
              src={product.image}
              alt={product.name}
              width={800}
              height={800}
              priority
              className="aspect-square w-full object-cover"
            />
          </div>

          {/* Details */}
          <div>
            <p className="text-xs font-medium uppercase tracking-wide text-gold-600">{product.category}</p>
            <h1 className="mt-2 text-3xl font-serif font-bold text-navy-800">{product.name}</h1>
            <p className="mt-2 text-sm text-navy-600">
              by <span className="font-medium text-navy-800">{product.artisan}</span>
            </p>

            <div className="mt-5 flex items-baseline gap-3">
              <span className="text-2xl font-bold text-navy-800">{formatPrice(product.price, settings.currency)}</span>
            </div>

            <p className="mt-5 text-sm leading-relaxed text-navy-600">{product.description}</p>

            <dl className="mt-6 grid grid-cols-2 gap-4 border-y border-navy-100 py-5 text-sm">
              <div>
                <dt className="text-navy-400">SKU</dt>
                <dd className="font-medium text-navy-800">{product.sku}</dd>
              </div>
              <div>
                <dt className="text-navy-400">Category</dt>
                <dd className="font-medium text-navy-800">{product.category}</dd>
              </div>
              <div>
                <dt className="text-navy-400">Artisan</dt>
                <dd className="font-medium text-navy-800">{product.artisan}</dd>
              </div>
              <div>
                <dt className="text-navy-400">Availability</dt>
                <dd className="font-medium text-gold-600">In Stock</dd>
              </div>
            </dl>

            {product.buyable ? (
              <div className="flex flex-wrap items-center gap-4">
                <ProductQuantityAddToCart
                  productId={product.id}
                  slug={product.slug}
                  name={product.name}
                  price={product.price}
                  image={product.image}
                />
                <button
                  type="button"
                  aria-label="Add to wishlist"
                  className="flex h-10 w-10 items-center justify-center rounded-md border border-navy-100 text-navy-800 hover:text-gold-600"
                >
                  <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth={1.8}>
                    <path d="M12 21s-7-4.5-9.5-9A5.5 5.5 0 0 1 12 6a5.5 5.5 0 0 1 9.5 6c-2.5 4.5-9.5 9-9.5 9Z" />
                  </svg>
                </button>
              </div>
            ) : account ? (
              <InquiryForm productId={product.id} redirectTo={productRoute(product.slug)} />
            ) : (
              <div className="mt-6 rounded-md border border-navy-100 bg-beige px-4 py-3 text-sm text-navy-700">
                This item is sold directly by an independent artisan shop.{' '}
                <Link
                  href={`${ROUTES.login}?redirect=${encodeURIComponent(productRoute(product.slug))}`}
                  className="font-semibold text-gold-600 hover:text-gold-700"
                >
                  Sign in to send an inquiry
                </Link>
                .
              </div>
            )}
            {product.bulkEnabled && (
              <Link
                href={`${ROUTES.bulkOrders}?product=${encodeURIComponent(product.slug)}`}
                className="mt-4 flex w-fit items-center gap-2 rounded-md border border-gold-500 px-4 py-2 text-sm font-semibold text-navy-800 hover:bg-gold-50"
              >
                Buying in quantity? Request a bulk quote &rarr;
              </Link>
            )}
            {product.vendorStoreSlug && (
              <Link
                href={vendorStorefrontRoute(product.vendorStoreSlug)}
                className="mt-3 inline-block text-xs font-semibold text-navy-500 hover:text-gold-600"
              >
                Visit this seller&apos;s storefront &rarr;
              </Link>
            )}
          </div>
        </div>
      </section>

      {/* Related products */}
      {relatedProducts.length > 0 && (
        <section className="border-t border-navy-100 bg-beige py-12">
          <div className="container-page">
            <h2 className="text-2xl font-serif font-bold text-navy-800">You May Also Like</h2>
            <div className="mt-6 grid grid-cols-2 gap-6 sm:grid-cols-3 xl:grid-cols-4">
              {relatedProducts.map((relatedProduct) => (
                <ProductCard key={relatedProduct.slug} product={relatedProduct} currency={settings.currency} />
              ))}
            </div>
          </div>
        </section>
      )}
    </>
  );
}
