import { Suspense } from 'react'
import { prisma } from '@/lib/prisma'

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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { FileSpreadsheet, BarChart3, Users, ClipboardList } from 'lucide-react'
import { formatDateOnly } from '@/lib/utils'

async function ReportsContent() {
  // Get rounds with evaluation stats
  const rounds = await prisma.round.findMany({
    include: {
      program: {
        select: {
          name: true,
        },
      },
      _count: {
        select: {
          projects: true,
          assignments: true,
        },
      },
      assignments: {
        select: {
          id: true,
          evaluation: {
            select: { id: true, status: true },
          },
        },
      },
    },
    orderBy: { createdAt: 'desc' },
  })

  // Calculate completion stats for each round
  const roundStats = rounds.map((round) => {
    const totalAssignments = round._count.assignments
    const completedEvaluations = round.assignments.filter(
      (a) => a.evaluation?.status === 'SUBMITTED'
    ).length
    const completionRate =
      totalAssignments > 0
        ? Math.round((completedEvaluations / totalAssignments) * 100)
        : 0

    return {
      ...round,
      totalAssignments,
      completedEvaluations,
      completionRate,
    }
  })

  // Calculate totals
  const totalProjects = roundStats.reduce((acc, r) => acc + r._count.projects, 0)
  const totalAssignments = roundStats.reduce(
    (acc, r) => acc + r.totalAssignments,
    0
  )
  const totalEvaluations = roundStats.reduce(
    (acc, r) => acc + r.completedEvaluations,
    0
  )

  if (rounds.length === 0) {
    return (
      <Card>
        <CardContent className="flex flex-col items-center justify-center py-12 text-center">
          <FileSpreadsheet className="h-12 w-12 text-muted-foreground/50" />
          <p className="mt-2 font-medium">No data to report</p>
          <p className="text-sm text-muted-foreground">
            Reports will appear here once rounds are created
          </p>
        </CardContent>
      </Card>
    )
  }

  return (
    <div className="space-y-6">
      {/* Quick Stats */}
      <div className="grid gap-4 sm: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">Total Rounds</CardTitle>
            <BarChart3 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{rounds.length}</div>
            <p className="text-xs text-muted-foreground">
              {rounds.filter((r) => r.status === 'ACTIVE').length} active
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Projects</CardTitle>
            <ClipboardList className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalProjects}</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">Assignments</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalAssignments}</div>
            <p className="text-xs text-muted-foreground">Total assignments</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>
            <FileSpreadsheet className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalEvaluations}</div>
            <p className="text-xs text-muted-foreground">Completed</p>
          </CardContent>
        </Card>
      </div>

      {/* Rounds Table - Desktop */}
      <Card className="hidden md:block">
        <CardHeader>
          <CardTitle>Round Reports</CardTitle>
          <CardDescription>Progress overview for each round</CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Round</TableHead>
                <TableHead>Program</TableHead>
                <TableHead>Projects</TableHead>
                <TableHead>Progress</TableHead>
                <TableHead>Status</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {roundStats.map((round) => (
                <TableRow key={round.id}>
                  <TableCell>
                    <div>
                      <p className="font-medium">{round.name}</p>
                      {round.votingEndAt && (
                        <p className="text-sm text-muted-foreground">
                          Ends: {formatDateOnly(round.votingEndAt)}
                        </p>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>{round.program.name}</TableCell>
                  <TableCell>{round._count.projects}</TableCell>
                  <TableCell>
                    <div className="min-w-[120px] space-y-1">
                      <div className="flex justify-between text-sm">
                        <span>
                          {round.completedEvaluations}/{round.totalAssignments}
                        </span>
                        <span className="text-muted-foreground">
                          {round.completionRate}%
                        </span>
                      </div>
                      <Progress value={round.completionRate} className="h-2" />
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge
                      variant={
                        round.status === 'ACTIVE'
                          ? 'default'
                          : round.status === 'CLOSED'
                            ? 'secondary'
                            : 'outline'
                      }
                    >
                      {round.status}
                    </Badge>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Rounds Cards - Mobile */}
      <div className="space-y-4 md:hidden">
        <h2 className="text-lg font-semibold">Round Reports</h2>
        {roundStats.map((round) => (
          <Card key={round.id}>
            <CardContent className="pt-4 space-y-3">
              <div className="flex items-center justify-between">
                <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.name}</p>
              {round.votingEndAt && (
                <p className="text-xs text-muted-foreground">
                  Ends: {formatDateOnly(round.votingEndAt)}
                </p>
              )}
              <div className="flex items-center justify-between text-sm">
                <span>{round._count.projects} projects</span>
                <span className="text-muted-foreground">
                  {round.completedEvaluations}/{round.totalAssignments} evaluations
                </span>
              </div>
              <div className="space-y-1">
                <div className="flex justify-between text-sm">
                  <span>Progress</span>
                  <span className="text-muted-foreground">{round.completionRate}%</span>
                </div>
                <Progress value={round.completionRate} className="h-2" />
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  )
}

function ReportsSkeleton() {
  return (
    <div className="space-y-6">
      <div className="grid gap-4 sm: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-16 w-full" />
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  )
}

export default function ObserverReportsPage() {
  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">Reports</h1>
        <p className="text-muted-foreground">
          View evaluation progress and statistics
        </p>
      </div>

      {/* Content */}
      <Suspense fallback={<ReportsSkeleton />}>
        <ReportsContent />
      </Suspense>
    </div>
  )
}
