import { prisma } from "@/lib/prisma"
import SuppliersTable from "./SuppliersTable"
import SupplierDialog from "./SupplierDialog"

type Props = {
  searchParams: Promise<{ page?: string; search?: string }>
}

export default async function SuppliersPage({ searchParams }: Props) {
  const params = await searchParams
  const page = parseInt(params.page || '1')
  const limit = 10
  const search = params.search || ''
  const skip = (page - 1) * limit

  const where = search ? {
    OR: [
      { name: { contains: search, mode: 'insensitive' as const } },
      { phone: { contains: search } },
      { email: { contains: search, mode: 'insensitive' as const } },
      { address: { contains: search, mode: 'insensitive' as const } },
    ]
  } : {}

  const [suppliers, total] = await Promise.all([
    prisma.supplier.findMany({
      where,
      include: {
        products: true,
      },
      orderBy: { name: 'asc' },
      skip,
      take: limit,
    }),
    prisma.supplier.count({ where }),
  ])

  const suppliersWithCount = suppliers.map(supplier => ({
    ...supplier,
    productsCount: supplier.products.length,
  }))

  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">Fournisseurs</h1>
          <p className="text-muted-foreground">Gérez vos fournisseurs</p>
        </div>
        <SupplierDialog />
      </div>

      <SuppliersTable 
        suppliers={suppliersWithCount}
        total={total}
        page={page}
        totalPages={totalPages}
      />
    </div>
  )
}