import { prisma } from "@/lib/prisma"
import PrescriptionsTable from "./PrescriptionsTable"
import PrescriptionDialog from "./PrescriptionDialog"

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

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

  const where: any = {}

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

  if (visionType !== 'all') {
    where.visions = {
      some: {
        type: visionType
      }
    }
  }

  const [prescriptions, total, clients] = await Promise.all([
    (prisma.prescription.findMany as any)({
      where,
      include: {
        client: true,
        visions: true,
      },
      orderBy: { createdAt: 'desc' },
      skip,
      take: limit,
    }),
    prisma.prescription.count({ where }),
    prisma.client.findMany({
      orderBy: { name: 'asc' }
    })
  ])

  const allVisions = await (prisma as any).vision.findMany({
    select: { type: true },
    distinct: ['type'],
  })
  const uniqueVisionTypes = allVisions.map((v: any) => v.type)

  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">Ordonnances</h1>
          <p className="text-muted-foreground">Gérez les prescriptions optiques</p>
        </div>
        <PrescriptionDialog clients={clients} />
      </div>

      <PrescriptionsTable 
        prescriptions={prescriptions} 
        visionTypes={uniqueVisionTypes} 
        clients={clients}
        total={total}
        page={page}
        totalPages={totalPages}
      />
    </div>
  )
}