import Link from "next/link";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { prisma } from "@/lib/prisma";
import { parseImages } from "@/lib/types";
import { DEFAULT_CHECKOUT_PAUSED_MESSAGE } from "@/lib/site";
import AddToCartForm from "@/components/AddToCartForm";
import ProductCard from "@/components/ProductCard";
import ProductGallery from "@/components/ProductGallery";
import ProductReviews from "@/components/ProductReviews";
import PincodeCheck from "@/components/PincodeCheck";

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params;
  const product = await prisma.product.findUnique({ where: { slug } });
  if (!product) return {};
  return {
    title: product.metaTitle || product.name,
    description: product.metaDescription || product.description.slice(0, 160),
  };
}

export default async function ProductPage({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ error?: string }>;
}) {
  const { slug } = await params;
  const { error } = await searchParams;

  const [product, storeSettings] = await Promise.all([
    prisma.product.findUnique({ where: { slug }, include: { category: true, variants: true } }),
    prisma.storeSettings.findFirst(),
  ]);

  if (!product || !product.active) notFound();
  const salesEnabled = storeSettings?.salesEnabled ?? true;
  const pausedMessage = storeSettings?.checkoutPausedMessage?.trim() || DEFAULT_CHECKOUT_PAUSED_MESSAGE;

  const bulkTiers = await prisma.bulkDiscountTier.findMany({
    where: { active: true, OR: [{ productId: product.id }, { categoryId: product.categoryId }] },
    select: { minQty: true, discountPercent: true },
    orderBy: { minQty: "asc" },
  });

  const images = parseImages(product.images);

  const related = await prisma.product.findMany({
    where: { active: true, categoryId: product.categoryId, id: { not: product.id } },
    include: { category: true, variants: true },
    take: 4,
  });

  return (
    <div className="mx-auto max-w-7xl px-4 py-10 sm:px-6">
      <div className="text-sm text-stone-500">
        <Link href="/shop" className="hover:text-rose-700">Shop</Link>
        {" / "}
        <Link href={`/shop?category=${product.category.slug}`} className="hover:text-rose-700">
          {product.category.name}
        </Link>
      </div>

      <div className="mt-4 grid gap-10 md:grid-cols-2">
        <ProductGallery
          images={images}
          alt={product.name}
          wishlistItem={{
            productId: product.id,
            name: product.name,
            slug: product.slug,
            image: images[0],
            basePrice: product.salePrice ?? product.basePrice,
            minOrderQty: product.minOrderQty,
          }}
        />

        <div>
          <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">{product.name}</h1>
          <p className="mt-3 whitespace-pre-line text-sm leading-relaxed text-stone-600">{product.description}</p>

          <div className="mt-6">
            <AddToCartForm
              productId={product.id}
              slug={product.slug}
              name={product.name}
              images={product.images}
              basePrice={product.basePrice}
              salePrice={product.salePrice}
              categoryDiscountPercent={product.category.discountPercent}
              bulkTiers={bulkTiers}
              minOrderQty={product.minOrderQty}
              personalizable={product.personalizable}
              variants={product.variants}
              stock={product.stock}
              salesEnabled={salesEnabled}
              pausedMessage={pausedMessage}
            />
          </div>

          <div className="mt-4">
            <PincodeCheck />
          </div>
        </div>
      </div>

      <ProductReviews productId={product.id} productSlug={product.slug} error={error} />

      {related.length > 0 && (
        <section className="mt-16">
          <h2 className="font-[family-name:var(--font-heading)] text-xl font-semibold text-stone-800">You may also like</h2>
          <div className="mt-5 grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
            {related.map((p) => (
              <ProductCard key={p.id} product={p} />
            ))}
          </div>
        </section>
      )}
    </div>
  );
}
