import type { JSX } from "react"
import Link from "next/link"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { Badge } from "@/shared/components/ui/badge"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import { ListPagination, computePagination, paginate } from "@/shared/components/ui/list-pagination"
import { formatDate } from "@/shared/lib/utils"
import { type SearchParams } from "@/shared/lib/search-params"
import { getHomeworkAssignmentReviewList } from "@/modules/homework/data-access"
import { Inbox } from "lucide-react"
import { getTeacherIdForMutations } from "@/modules/classes/data-access"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getTranslations } from "next-intl/server"

export const dynamic = "force-dynamic"

const PAGE_SIZE = 10

export default async function SubmissionsPage({ searchParams }: { searchParams: Promise<SearchParams> }): Promise<JSX.Element> {
  const sp = await searchParams
  const ctx = await requirePermission(Permissions.HOMEWORK_GRADE)
  const t = await getTranslations("examHomework")
  const creatorId = await getTeacherIdForMutations()
  const assignments = await getHomeworkAssignmentReviewList({ creatorId, scope: ctx.dataScope })
  const hasAssignments = assignments.length > 0

  // 分页计算
  const { page } = computePagination(sp, PAGE_SIZE)
  const total = assignments.length
  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
  const currentPage = Math.min(page, totalPages)
  const pagedAssignments = paginate(assignments, currentPage, PAGE_SIZE)

  return (
    <div className="h-full flex-1 flex-col space-y-8 p-8 md:flex">
      <div className="flex items-center justify-between space-y-2">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">{t("homework.submissions.title")}</h1>
          <p className="text-muted-foreground">
            {t("homework.submissions.description")}
          </p>
        </div>
      </div>

      {!hasAssignments ? (
        <EmptyState
          title={t("homework.list.empty")}
          description={t("homework.submissions.emptyDescription")}
          icon={Inbox}
        />
      ) : (
        <div className="rounded-md border bg-card">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t("homework.submissions.columns.assignment")}</TableHead>
                <TableHead>{t("homework.list.columns.status")}</TableHead>
                <TableHead>{t("homework.list.columns.dueAt")}</TableHead>
                <TableHead className="text-right">{t("homework.grade.targets")}</TableHead>
                <TableHead className="text-right">{t("homework.grade.submittedCount")}</TableHead>
                <TableHead className="text-right">{t("homework.grade.gradedCount")}</TableHead>
                <TableHead className="text-right">{t("homework.list.columns.submissionRate")}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {pagedAssignments.map((a) => {
                const submissionRate = a.targetCount > 0 ? (a.submittedCount / a.targetCount) * 100 : 0
                return (
                  <TableRow key={a.id}>
                    <TableCell className="font-medium">
                      <Link
                        href={`/teacher/homework/assignments/${a.id}/submissions`}
                        className="hover:underline line-clamp-2 max-w-[240px]"
                      >
                        {a.title}
                      </Link>
                      {a.sourceExamTitle ? (
                        <div className="text-xs text-muted-foreground truncate max-w-[200px]">{a.sourceExamTitle}</div>
                      ) : (
                        <div className="text-xs text-muted-foreground italic">{t("homework.submissions.quickAssignment")}</div>
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline" className="capitalize">
                        {a.status}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-muted-foreground tabular-nums">{a.dueAt ? formatDate(a.dueAt) : "-"}</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">
                      {a.targetCount > 0 ? `${submissionRate.toFixed(0)}%` : "-"}
                    </TableCell>
                  </TableRow>
                )
              })}
            </TableBody>
          </Table>
          <ListPagination
            page={currentPage}
            pageSize={PAGE_SIZE}
            total={total}
            totalPages={totalPages}
            basePath="/teacher/homework/submissions"
            searchParams={sp}
            itemLabel={t("homework.list.pagination.itemLabel")}
          />
        </div>
      )}
    </div>
  )
}
