import Link from "next/link"
import type { Metadata } from "next"
import type { JSX } from "react"
import { BarChart3 } from "lucide-react"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getGrades } from "@/modules/school/data-access"
import { getGradeHomeworkInsights } from "@/modules/classes/data-access"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { StatCard } from "@/shared/components/ui/stat-card"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { formatDate, formatNumber, getSearchParam, type SearchParams } from "@/shared/lib/utils"

export const metadata: Metadata = {
  title: "年级作业洞察 - Next_Edu",
  description: "按年级聚合的作业统计与班级排名",
}

export const dynamic = "force-dynamic"

export default async function AdminGradeInsightsPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  await requirePermission(Permissions.SCHOOL_MANAGE)
  const params = await searchParams
  const gradeId = getSearchParam(params, "gradeId")
  const selected = gradeId && gradeId !== "all" ? gradeId : ""

  // grades 与 insights 无数据依赖，并行查询
  const [grades, insights] = await Promise.all([
    getGrades(),
    selected ? getGradeHomeworkInsights({ gradeId: selected, limit: 50 }) : Promise.resolve(null),
  ])

  return (
    <div className="flex h-full flex-col space-y-8 p-8">
      <div className="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
        <div className="space-y-1">
          <h2 className="text-2xl font-bold tracking-tight">年级作业洞察</h2>
          <p className="text-muted-foreground">按年级聚合的作业统计与班级排名。</p>
        </div>
        <Button asChild variant="outline">
          <Link href="/admin/school/grades">管理年级</Link>
        </Button>
      </div>

      <Card className="shadow-none">
        <CardHeader className="flex flex-row items-center justify-between space-y-0">
          <CardTitle className="text-base">筛选</CardTitle>
          <Badge variant="secondary" className="tabular-nums">
            {grades.length}
          </Badge>
        </CardHeader>
        <CardContent>
          <form
            action="/admin/school/grades/insights"
            method="get"
            className="flex flex-col gap-3 md:flex-row md:items-center"
          >
            <label htmlFor="grade-filter" className="text-sm font-medium">
              年级
            </label>
            <select
              id="grade-filter"
              name="gradeId"
              defaultValue={selected || "all"}
              className="h-10 w-full rounded-md border bg-background px-3 text-sm md:w-80"
            >
              <option value="all">请选择年级</option>
              {grades.map((g) => (
                <option key={g.id} value={g.id}>
                  {g.school.name} / {g.name}
                </option>
              ))}
            </select>
            <Button type="submit" className="md:ml-2">
              应用
            </Button>
          </form>
        </CardContent>
      </Card>

      {!selected ? (
        <EmptyState
          icon={BarChart3}
          title="请选择年级以查看洞察"
          description="选择一个年级，查看最新作业与历史成绩统计。"
          className="h-80 bg-card"
        />
      ) : !insights ? (
        <EmptyState
          icon={BarChart3}
          title="年级未找到"
          description="该年级可能不存在或无可访问数据。"
          className="h-80 bg-card"
        />
      ) : insights.assignments.length === 0 ? (
        <EmptyState
          icon={BarChart3}
          title="该年级暂无作业数据"
          description="尚未向该年级学生布置任何作业。"
          className="h-80 bg-card"
        />
      ) : (
        <div className="space-y-6">
          <div className="grid gap-4 md:grid-cols-4">
            <StatCard
              title="班级数"
              value={insights.classCount}
              description={`${insights.grade.school.name} / ${insights.grade.name}`}
              valueClassName="tabular-nums"
            />
            <StatCard
              title="学生数"
              value={insights.studentCounts.total}
              description={`在读 ${insights.studentCounts.active} • 停用 ${insights.studentCounts.inactive}`}
              valueClassName="tabular-nums"
            />
            <StatCard
              title="总体均分"
              value={formatNumber(insights.overallScores.avg)}
              description="基于已批改作业"
              valueClassName="tabular-nums"
            />
            <StatCard
              title="最新均分"
              value={formatNumber(insights.latest?.scoreStats.avg ?? null)}
              description={insights.latest?.title ?? "-"}
              valueClassName="tabular-nums"
            />
          </div>

          <Card className="shadow-none">
            <CardHeader className="flex flex-row items-center justify-between space-y-0">
              <CardTitle className="text-base">最新作业</CardTitle>
              <Badge variant="secondary" className="tabular-nums">
                {insights.assignments.length}
              </Badge>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/50">
                      <TableHead>作业</TableHead>
                      <TableHead>状态</TableHead>
                      <TableHead>创建时间</TableHead>
                      <TableHead className="text-right">目标数</TableHead>
                      <TableHead className="text-right">提交数</TableHead>
                      <TableHead className="text-right">已批改</TableHead>
                      <TableHead className="text-right">均分</TableHead>
                      <TableHead className="text-right">中位数</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {insights.assignments.map((a) => (
                      <TableRow key={a.assignmentId}>
                        <TableCell className="font-medium">{a.title}</TableCell>
                        <TableCell>
                          <Badge variant="secondary" className="capitalize">
                            {a.status}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-muted-foreground">{formatDate(a.createdAt)}</TableCell>
                        <TableCell className="text-right tabular-nums">{a.targetCount}</TableCell>
                        <TableCell className="text-right tabular-nums">{a.submittedCount}</TableCell>
                        <TableCell className="text-right tabular-nums">{a.gradedCount}</TableCell>
                        <TableCell className="text-right tabular-nums">{formatNumber(a.scoreStats.avg)}</TableCell>
                        <TableCell className="text-right tabular-nums">{formatNumber(a.scoreStats.median)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>

          <Card className="shadow-none">
            <CardHeader className="flex flex-row items-center justify-between space-y-0">
              <CardTitle className="text-base">班级排名</CardTitle>
              <Badge variant="secondary" className="tabular-nums">
                {insights.classes.length}
              </Badge>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/50">
                      <TableHead>班级</TableHead>
                      <TableHead className="text-right">学生数</TableHead>
                      <TableHead className="text-right">最新均分</TableHead>
                      <TableHead className="text-right">上次均分</TableHead>
                      <TableHead className="text-right">Δ</TableHead>
                      <TableHead className="text-right">总体均分</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {insights.classes.map((c) => (
                      <TableRow key={c.class.id}>
                        <TableCell className="font-medium">
                          {c.class.name}
                          {c.class.homeroom ? (
                            <span className="text-muted-foreground"> • {c.class.homeroom}</span>
                          ) : null}
                        </TableCell>
                        <TableCell className="text-right tabular-nums">{c.studentCounts.total}</TableCell>
                        <TableCell className="text-right tabular-nums">{formatNumber(c.latestAvg)}</TableCell>
                        <TableCell className="text-right tabular-nums">{formatNumber(c.prevAvg)}</TableCell>
                        <TableCell className="text-right tabular-nums">{formatNumber(c.deltaAvg)}</TableCell>
                        <TableCell className="text-right tabular-nums">{formatNumber(c.overallScores.avg)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  )
}
