import type { Metadata } from 'next'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import {
  Card,
  CardContent,
} from '@/components/ui/card'
import { CircleDot } from 'lucide-react'
import { DashboardContent } from './dashboard-content'

export const metadata: Metadata = { title: 'Admin Dashboard' }
export const dynamic = 'force-dynamic'

type PageProps = {
  searchParams: Promise<{ edition?: string }>
}

export default async function AdminDashboardPage({ searchParams }: PageProps) {
  let editionId: string | null = null
  let sessionName = 'Admin'

  try {
    const [session, params] = await Promise.all([
      auth(),
      searchParams,
    ])

    editionId = params.edition || null
    sessionName = session?.user?.name || 'Admin'

    if (!editionId) {
      const defaultEdition = await prisma.program.findFirst({
        where: { status: 'ACTIVE' },
        orderBy: { year: 'desc' },
        select: { id: true },
      })
      editionId = defaultEdition?.id || null

      if (!editionId) {
        const anyEdition = await prisma.program.findFirst({
          orderBy: { year: 'desc' },
          select: { id: true },
        })
        editionId = anyEdition?.id || null
      }
    }
  } catch (err) {
    console.error('[AdminDashboard] Page init failed:', err)
  }

  if (!editionId) {
    return (
      <div className="space-y-6">
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <CircleDot className="h-12 w-12 text-muted-foreground/50" />
            <p className="mt-2 font-medium">No edition selected</p>
            <p className="text-sm text-muted-foreground">
              Select an edition from the sidebar to view dashboard
            </p>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <DashboardContent editionId={editionId} sessionName={sessionName} />
    </div>
  )
}
