import type { Metadata } from 'next'
import { Suspense } from 'react'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'

export const metadata: Metadata = { title: 'Observer Dashboard' }
export const dynamic = 'force-dynamic'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Skeleton } from '@/components/ui/skeleton'
import {
  FolderKanban,
  ClipboardList,
  Users,
  CheckCircle2,
  Eye,
} from 'lucide-react'
import { formatDateOnly } from '@/lib/utils'

async function ObserverDashboardContent() {
  const [
    programCount,
    activeRoundCount,
    projectCount,
    jurorCount,
    evaluationStats,
    recentRounds,
  ] = await Promise.all([
    prisma.program.count(),
    prisma.round.count({ where: { status: 'ACTIVE' } }),
    prisma.project.count(),
    prisma.user.count({ where: { role: 'JURY_MEMBER', status: 'ACTIVE' } }),
    prisma.evaluation.groupBy({
      by: ['status'],
      _count: true,
    }),
    prisma.round.findMany({
      orderBy: { createdAt: 'desc' },
      take: 5,
      include: {
        program: { select: { name: true, year: true } },
        _count: {
          select: {
            projects: true,
            assignments: true,
          },
        },
      },
    }),
  ])

  const submittedCount =
    evaluationStats.find((e) => e.status === 'SUBMITTED')?._count || 0
  const draftCount =
    evaluationStats.find((e) => e.status === 'DRAFT')?._count || 0
  const totalEvaluations = submittedCount + draftCount
  const completionRate =
    totalEvaluations > 0 ? (submittedCount / totalEvaluations) * 100 : 0

  return (
    <>
      {/* Observer Notice */}
      <Card className="border-blue-200 bg-blue-50 dark:border-blue-900 dark:bg-blue-950/30">
        <CardContent className="flex items-center gap-3 py-4">
          <Eye className="h-5 w-5 text-blue-600 dark:text-blue-400" />
          <div>
            <p className="font-medium text-blue-900 dark:text-blue-100">
              Observer Mode
            </p>
            <p className="text-sm text-blue-700 dark:text-blue-300">
              You have read-only access to view platform statistics and reports.
            </p>
          </div>
        </CardContent>
      </Card>

      {/* Stats Grid */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Programs</CardTitle>
            <FolderKanban className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{programCount}</div>
            <p className="text-xs text-muted-foreground">
              {activeRoundCount} active round{activeRoundCount !== 1 ? 's' : ''}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Projects</CardTitle>
            <ClipboardList className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{projectCount}</div>
            <p className="text-xs text-muted-foreground">Across all rounds</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Jury Members</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{jurorCount}</div>
            <p className="text-xs text-muted-foreground">Active members</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Evaluations</CardTitle>
            <CheckCircle2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{submittedCount}</div>
            <div className="mt-2">
              <Progress value={completionRate} className="h-2" />
              <p className="mt-1 text-xs text-muted-foreground">
                {completionRate.toFixed(0)}% completion rate
              </p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Recent Rounds */}
      <Card>
        <CardHeader>
          <CardTitle>Recent Rounds</CardTitle>
          <CardDescription>Overview of the latest voting rounds</CardDescription>
        </CardHeader>
        <CardContent>
          {recentRounds.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <FolderKanban className="h-12 w-12 text-muted-foreground/50" />
              <p className="mt-2 text-sm text-muted-foreground">
                No rounds created yet
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              {recentRounds.map((round) => (
                <div
                  key={round.id}
                  className="flex items-center justify-between rounded-lg border p-4"
                >
                  <div className="space-y-1">
                    <div className="flex items-center gap-2">
                      <p className="font-medium">{round.name}</p>
                      <Badge
                        variant={
                          round.status === 'ACTIVE'
                            ? 'default'
                            : round.status === 'CLOSED'
                              ? 'secondary'
                              : 'outline'
                        }
                      >
                        {round.status}
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      {round.program.year} Edition
                    </p>
                  </div>
                  <div className="text-right text-sm">
                    <p>{round._count.projects} projects</p>
                    <p className="text-muted-foreground">
                      {round._count.assignments} assignments
                    </p>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </>
  )
}

function DashboardSkeleton() {
  return (
    <>
      <Skeleton className="h-20 w-full" />
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        {[...Array(4)].map((_, i) => (
          <Card key={i}>
            <CardHeader className="space-y-0 pb-2">
              <Skeleton className="h-4 w-20" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-8 w-16" />
              <Skeleton className="mt-2 h-3 w-24" />
            </CardContent>
          </Card>
        ))}
      </div>
      <Card>
        <CardHeader>
          <Skeleton className="h-6 w-32" />
          <Skeleton className="h-4 w-48" />
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {[...Array(3)].map((_, i) => (
              <Skeleton key={i} className="h-20 w-full" />
            ))}
          </div>
        </CardContent>
      </Card>
    </>
  )
}

export default async function ObserverDashboardPage() {
  const session = await auth()

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">Dashboard</h1>
        <p className="text-muted-foreground">
          Welcome, {session?.user?.name || 'Observer'}
        </p>
      </div>

      {/* Content */}
      <Suspense fallback={<DashboardSkeleton />}>
        <ObserverDashboardContent />
      </Suspense>
    </div>
  )
}
