import { prisma } from "@/lib/prisma"
import InvoicesTable from "./InvoicesTable"

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

export default async function InvoicesPage({ searchParams }: Props) {
  const params = await searchParams
  const page = parseInt(params.page || '1')
  const limit = 10
  const search = params.search || ''
  const status = params.status || 'all'
  const payment = params.payment || 'all'
  const sortBy = params.sortBy || 'createdAt'
  const sortOrder = params.sortOrder || 'desc'
  const skip = (page - 1) * limit

  const where: any = {}

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

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

  if (payment !== 'all') {
    where.paymentMethod = payment
  }

  const [invoices, total] = await Promise.all([
    prisma.invoice.findMany({
      where,
      include: {
        client: true,
        seller: true,
      },
      orderBy: sortBy.includes('.') 
        ? { [sortBy.split('.')[0]]: { [sortBy.split('.')[1]]: sortOrder } }
        : { [sortBy]: sortOrder },
      skip,
      take: limit,
    }),
    prisma.invoice.count({ where }),
  ])

  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">Factures</h1>
          <p className="text-muted-foreground">Gérez vos factures et reçus</p>
        </div>
      </div>

      <InvoicesTable 
        invoices={invoices as any}
        total={total}
        page={page}
        totalPages={totalPages}
      />
    </div>
  )
}