import type { JSX } from "react"
import { Suspense } from "react"
import type { ReactNode } from "react"
import Link from "next/link"
import { notFound } from "next/navigation"
import { getHomeworkAssignmentAnalytics } from "@/modules/homework/stats-service"
import { HomeworkAssignmentExamContentCard } from "@/modules/homework/components/homework-assignment-exam-content-card"
import { HomeworkAssignmentQuestionErrorOverviewCard } from "@/modules/homework/components/homework-assignment-question-error-overview-card"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Skeleton } from "@/shared/components/ui/skeleton"
import { SectionErrorBoundary } from "@/shared/components/section-error-boundary"
import { formatDate } from "@/shared/lib/utils"
import { ArrowLeft, Users, Calendar, BarChart3, CheckCircle2 } from "lucide-react"
import { requirePermission } from "@/shared/lib/auth-guard"
import { getTranslations } from "next-intl/server"
import { Permissions } from "@/shared/types/permissions"

export const dynamic = "force-dynamic"

export default async function HomeworkAssignmentDetailPage({ params }: { params: Promise<{ id: string }> }): Promise<JSX.Element> {
  const { id } = await params
  await requirePermission(Permissions.HOMEWORK_CREATE)
  const t = await getTranslations("examHomework")
  const analytics = await getHomeworkAssignmentAnalytics(id)

  if (!analytics) return notFound()

  const { assignment, questions, gradedSampleCount } = analytics

  return (
    <div className="flex flex-col min-h-full">
      {/* Header */}
      <div className="border-b bg-background px-8 py-5">
        <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
          <div className="min-w-0 flex flex-col gap-2">
            <Button asChild variant="ghost" size="sm" className="w-fit">
              <Link href="/teacher/homework/assignments">
                <ArrowLeft className="mr-2 h-4 w-4" aria-hidden="true" />
                {t("homework.result.backToList")}
              </Link>
            </Button>
            <div className="flex items-center gap-3">
              <h1 className="text-2xl font-bold tracking-tight text-foreground line-clamp-2">{assignment.title}</h1>
              <Badge variant={assignment.status === "published" ? "default" : "secondary"} className="capitalize">
                {assignment.status}
              </Badge>
            </div>
            <p className="text-muted-foreground text-sm max-w-2xl">{assignment.description || t("homework.take.noDescription")}</p>
          </div>

          <div className="flex items-center gap-3 mt-2 md:mt-0">
            <Button asChild variant="outline" className="shadow-sm">
              <Link href={`/teacher/homework/assignments/${assignment.id}/submissions`}>
                <Users className="h-4 w-4 mr-2" aria-hidden="true" />
                {t("homework.detail.viewSubmissions")}
              </Link>
            </Button>
          </div>
        </div>

        {/* Quick Stats Row */}
        <div className="flex flex-wrap gap-x-8 gap-y-2 mt-6 text-sm">
          <div className="flex items-center gap-2 text-muted-foreground">
            <Calendar className="h-4 w-4" aria-hidden="true" />
            <span>{t("homework.detail.dueLabel")}: <span className="font-medium text-foreground tabular-nums">{assignment.dueAt ? formatDate(assignment.dueAt) : t("homework.detail.noDueDate")}</span></span>
          </div>
          <div className="flex items-center gap-2 text-muted-foreground">
            <Users className="h-4 w-4" aria-hidden="true" />
            <span>{t("homework.grade.targets")}: <span className="font-medium text-foreground tabular-nums">{assignment.targetCount}</span></span>
          </div>
          <div className="flex items-center gap-2 text-muted-foreground">
            <CheckCircle2 className="h-4 w-4" aria-hidden="true" />
            <span>{t("homework.detail.submissionsLabel")}: <span className="font-medium text-foreground tabular-nums">{assignment.submissionCount}</span></span>
          </div>
          <div className="flex items-center gap-2 text-muted-foreground">
            <BarChart3 className="h-4 w-4" aria-hidden="true" />
            <span>{t("homework.grade.gradedCount")}: <span className="font-medium text-foreground tabular-nums">{gradedSampleCount}</span></span>
          </div>
        </div>
      </div>

      <div className="flex-1 p-8 space-y-8 bg-muted/5">
        {/* Analytics Section - wrapped with SectionErrorBoundary + Suspense for graceful degradation */}
        <section className="space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold tracking-tight">{t("homework.detail.performanceAnalytics")}</h2>
          </div>
          <SectionErrorBoundary namespace="examHomework">
            <Suspense fallback={<AnalyticsSkeleton />}>
              <HomeworkAssignmentQuestionErrorOverviewCard questions={questions} gradedSampleCount={gradedSampleCount} />
            </Suspense>
          </SectionErrorBoundary>
        </section>

        {/* Content Section */}
        <section className="space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold tracking-tight">{t("homework.detail.assignmentContent")}</h2>
          </div>
          <HomeworkAssignmentExamContentCard
            structure={assignment.structure}
            questions={questions}
            gradedSampleCount={gradedSampleCount}
          />
        </section>
      </div>
    </div>
  )
}

/**
 * Analytics 区块加载骨架屏。
 */
function AnalyticsSkeleton(): ReactNode {
  return (
    <div className="space-y-3">
      <Skeleton className="h-8 w-full" />
      {Array.from({ length: 4 }).map((_, i) => (
        <Skeleton key={i} className="h-12 w-full" />
      ))}
    </div>
  )
}
