import { notFound } from 'next/navigation';
import dynamic from 'next/dynamic';
import { prisma } from '@/lib/prisma';
import { toProductDTO } from '@/lib/product';
import { fetchActivePromotions } from '@/lib/promotions';
import ProductCard from '@/components/ProductCard';

const DesignCanvas = dynamic(() => import('@/components/DesignCanvas'), { ssr: false });

export default async function ProductDetailPage({ params }: { params: { slug: string } }) {
  const activePromotions = await fetchActivePromotions();

  const row = await prisma.product.findUnique({ where: { slug: params.slug } });
  if (!row || !row.showOnPersonalised) notFound();

  const product = toProductDTO(row, activePromotions);

  const relatedRows = await prisma.product.findMany({
    where: { category: product.category, showOnPersonalised: true, NOT: { id: product.id } },
    take: 4,
  });
  const related = relatedRows.map((p) => toProductDTO(p, activePromotions));

  return (
    <div className="mx-auto max-w-6xl px-6 py-12">
      <DesignCanvas product={product} />

      {related.length > 0 && (
        <section className="mt-20 border-t border-line pt-12">
          <h2 className="mb-8 font-display text-3xl">You might also like</h2>
          <div className="grid gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-4">
            {related.map((p) => (
              <ProductCard key={p.id} product={p} />
            ))}
          </div>
        </section>
      )}
    </div>
  );
}
