import { notFound } from "next/navigation"
import Image from "next/image"
import { db } from "@/lib/db"
import { Badge } from "@/components/ui/badge"
import { formatPrice } from "@/lib/utils"
import { AddToCartButton } from "@/components/shop/add-to-cart-button"
import { ProductCard } from "@/components/shop/product-card"
import { productImage } from "@/lib/product-image"
import { normalizeProductArrays } from "@/lib/json-array"
import type { Prisma } from "@prisma/client"

interface Props {
  params: Promise<{ slug: string }>
  searchParams: Promise<{ style?: string; material?: string; category?: string }>
}

export async function generateMetadata({ params }: Props) {
  const { slug } = await params
  const product = await db.product.findUnique({ where: { slug } })
  if (!product) return {}
  return {
    title: product.name,
    description: product.description.slice(0, 160),
  }
}

export default async function ProductPage({ params, searchParams }: Props) {
  const { slug } = await params
  const sp = await searchParams

  const productRaw = await db.product.findUnique({
    where: { slug, active: true },
    include: { category: true, drop: true },
  })

  if (!productRaw) notFound()
  const product = normalizeProductArrays(productRaw)

  const isSoldOut = product.stock === 0
  const mainImage = productImage(product.images, product.materials)

  // Grille "du filtre" : autres articles correspondant aux filtres transmis,
  // sinon même catégorie par défaut.
  const hasFilter = sp.style || sp.material || sp.category
  const relatedWhere: Prisma.ProductWhereInput = {
    active: true,
    slug: { not: slug },
    ...(hasFilter
      ? {
          ...(sp.style ? { styles: { array_contains: sp.style } } : {}),
          ...(sp.material ? { materials: { array_contains: sp.material } } : {}),
          ...(sp.category ? { category: { slug: sp.category } } : {}),
        }
      : { categoryId: product.categoryId }),
  }
  const relatedRaw = await db.product.findMany({
    where: relatedWhere,
    include: { drop: true },
    orderBy: { createdAt: "desc" },
    take: 8,
  })
  const related = relatedRaw.map(normalizeProductArrays)

  return (
    <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-16">
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-16">

        {/* Images */}
        <div className="space-y-3">
          {product.images.length > 0 ? (
            product.images.map((src, i) => (
              <div key={i} className="aspect-square relative bg-[var(--surface)] overflow-hidden">
                <Image
                  src={src}
                  alt={i === 0 ? product.name : `${product.name} ${i + 1}`}
                  fill
                  className="object-cover"
                  priority={i === 0}
                />
              </div>
            ))
          ) : mainImage ? (
            <div className="aspect-square relative bg-[var(--surface)] overflow-hidden">
              <Image src={mainImage} alt={product.name} fill className="object-cover" priority />
            </div>
          ) : (
            <div className="aspect-square bg-[var(--surface)] border border-[var(--border)] flex items-center justify-center">
              <span className="font-mono text-xs text-[var(--text-muted)] uppercase tracking-widest">VALABEL</span>
            </div>
          )}
        </div>

        {/* Info */}
        <div className="lg:sticky lg:top-24 lg:self-start">
          <div className="flex items-center gap-3 mb-4">
            {product.drop?.status === "LIVE" && <Badge variant="drop">Drop Live</Badge>}
            {isSoldOut && <Badge variant="sold">Sold Out</Badge>}
            <span className="font-mono text-xs text-[var(--text-muted)] uppercase tracking-widest">
              {product.category.name}
            </span>
          </div>

          <h1 className="text-3xl md:text-4xl font-heading font-bold uppercase tracking-tight text-[var(--text)] mb-3">
            {product.name}
          </h1>

          <p className="font-mono text-2xl text-[var(--text)] mb-8">
            {formatPrice(product.price)}
          </p>

          <p className="text-[var(--text-secondary)] leading-relaxed mb-8">
            {product.description}
          </p>

          {!isSoldOut && product.sizes.length > 0 && (
            <AddToCartButton product={product} />
          )}

          {isSoldOut && (
            <div className="border border-[var(--border)] p-4 text-center">
              <p className="font-mono text-sm text-[var(--text-muted)] uppercase tracking-widest">
                Sold Out — Rejoins la liste d&rsquo;attente
              </p>
            </div>
          )}

          {/* Details */}
          <div className="mt-10 pt-8 border-t border-[var(--border)] space-y-3">
            <div className="flex justify-between">
              <span className="font-mono text-xs uppercase tracking-widest text-[var(--text-muted)]">Matière</span>
              <span className="text-sm text-[var(--text-secondary)]">Néoprène premium</span>
            </div>
            <div className="flex justify-between">
              <span className="font-mono text-xs uppercase tracking-widest text-[var(--text-muted)]">Origine</span>
              <span className="text-sm text-[var(--text-secondary)]">Belgique</span>
            </div>
            {product.drop && (
              <div className="flex justify-between">
                <span className="font-mono text-xs uppercase tracking-widest text-[var(--text-muted)]">Drop</span>
                <span className="text-sm text-[var(--text-secondary)]">{product.drop.name}</span>
              </div>
            )}
            {product.editionSize && (
              <div className="flex justify-between">
                <span className="font-mono text-xs uppercase tracking-widest text-[var(--text-muted)]">Édition</span>
                <span className="text-sm text-[var(--accent)]">
                  Limitée à {product.editionSize} pièces numérotées
                </span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Grille : les autres articles du filtre */}
      {related.length > 0 && (
        <div className="mt-20 pt-12 border-t border-[var(--border)]">
          <p className="font-mono text-xs uppercase tracking-widest text-[var(--accent)] mb-8">
            Aussi dans ta sélection
          </p>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-x-4 gap-y-12">
            {related.map((p) => (
              <ProductCard
                key={p.id}
                id={p.id}
                name={p.name}
                slug={p.slug}
                price={p.price}
                images={p.images}
                materials={p.materials}
                stock={p.stock}
                drop={p.drop ? { name: p.drop.name, status: p.drop.status } : null}
              />
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
