import { prisma } from "@/lib/prisma"
import ProductsTable from "./ProductsTable"
import ProductDialog from "./ProductDialog"

type Props = {
  searchParams: Promise<{ page?: string; search?: string; category?: string; stock?: string; sortBy?: string; sortOrder?: string }>
}

export default async function ProductsPage({ searchParams }: Props) {
  const params = await searchParams
  const page = parseInt(params.page || '1')
  const limit = 10
  const search = params.search || ''
  const category = params.category || 'all'
  const stock = params.stock || 'all'
  const sortBy = params.sortBy || 'name'
  const sortOrder = params.sortOrder || 'asc'
  const skip = (page - 1) * limit

  const where: any = {}

  if (search) {
    where.OR = [
      { name: { contains: search, mode: 'insensitive' } },
      { sku: { contains: search, mode: 'insensitive' } },
      { brand: { contains: search, mode: 'insensitive' } },
    ]
  }

  if (category !== 'all') {
    where.category = category
  }

  if (stock === 'low') {
    where.quantity = { gt: 0, lte: 5 }
  } else if (stock === 'out') {
    where.quantity = 0
  } else if (stock === 'normal') {
    where.quantity = { gt: 5 }
  }

  const [products, total] = await Promise.all([
    prisma.product.findMany({
      where,
      orderBy: { [sortBy]: sortOrder as any },
      skip,
      take: limit,
    }),
    prisma.product.count({ where }),
  ])

  const allProducts = await prisma.product.findMany({
    select: { category: true },
  })
  const uniqueCategories = Array.from(new Set(allProducts.map(p => p.category)))

  const totalPages = Math.ceil(total / limit)

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-slate-800">Produits</h1>
          <p className="text-muted-foreground">Gérez votre inventaire</p>
        </div>
        <ProductDialog />
      </div>

      <ProductsTable 
        products={products} 
        categories={uniqueCategories}
        total={total}
        page={page}
        totalPages={totalPages}
      />
    </div>
  )
}