import { Suspense } from "react"
import type { ReactNode } from "react"
import Link from "next/link"
import { getTranslations } from "next-intl/server"
import { Award, Trophy, Medal, Clock, ChevronRight } from "lucide-react"

import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Skeleton } from "@/shared/components/ui/skeleton"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { SectionErrorBoundary } from "@/shared/components/section-error-boundary"
import { cn, formatDate } from "@/shared/lib/utils"

import { getExcellentSubmissions } from "../data-access"

/**
 * P3-1：优秀作业展示
 *
 * 在作业详情页向学生展示班级优秀样例，激发学习动力。
 *
 * 设计原则：
 * - 服务端组件，直接调用 data-access，避免多余 action 往返。
 * - 通过 SectionErrorBoundary + Suspense 实现错误与加载边界。
 * - 仅展示姓名，不展示学号，保护学生隐私。
 * - 按得分率降序排列，前三名分别用金/银/铜徽章标识。
 *
 * 安全：调用方（页面）必须已通过 requirePermission() 校验，
 * 本组件接收已过滤的 scope 参数。
 */
interface ExcellentSubmissionsProps {
  assignmentId: string
  /** 最低得分百分比阈值（默认 80） */
  minPercentage?: number
  /** 返回数量上限（默认 10） */
  limit?: number
  /** 是否以教师视角展示（显示学生姓名；学生视角默认匿名） */
  revealStudentName?: boolean
}

const RANK_ICONS = [Trophy, Medal, Award] as const
const RANK_STYLES = [
  "bg-amber-50 text-amber-700 dark:bg-amber-950 dark:text-amber-300",
  "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300",
  "bg-orange-50 text-orange-700 dark:bg-orange-950 dark:text-orange-300",
] as const

export async function ExcellentSubmissions({
  assignmentId,
  minPercentage = 80,
  limit = 10,
  revealStudentName = true,
}: ExcellentSubmissionsProps): Promise<ReactNode> {
  const t = await getTranslations("examHomework")

  const items = await getExcellentSubmissions({
    assignmentId,
    minPercentage,
    limit,
  })

  return (
    <Card className="w-full">
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-3">
        <div className="space-y-1">
          <CardTitle className="flex items-center gap-2 text-base">
            <Trophy className="h-4 w-4 text-amber-500" />
            {t("homework.excellent.title")}
          </CardTitle>
          <p className="text-xs text-muted-foreground">
            {t("homework.excellent.description", { minPercentage })}
          </p>
        </div>
      </CardHeader>
      <CardContent>
        {items.length === 0 ? (
          <EmptyState
            icon={Award}
            title={t("homework.excellent.empty")}
            description={t("homework.excellent.emptyHint")}
            className="h-[200px]"
          />
        ) : (
          <ul className="space-y-2" aria-label={t("homework.excellent.title")}>
            {items.map((item, idx) => {
              const rank = idx + 1
              const RankIcon = RANK_ICONS[rank - 1] ?? null
              const rankStyle = RANK_STYLES[rank - 1] ?? "bg-muted text-muted-foreground"
              const displayName = revealStudentName
                ? item.studentName
                : t("homework.excellent.studentAnon")
              const submittedDate = item.submittedAt ? formatDate(item.submittedAt) : ""

              return (
                <li key={item.submissionId}>
                  <Link
                    href={`/teacher/homework/submissions/${item.submissionId}`}
                    className="flex items-center gap-3 rounded-md border p-3 transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                  >
                    {/* 排名徽章 */}
                    <div
                      className={cn(
                        "flex h-9 w-9 shrink-0 items-center justify-center rounded-full",
                        rankStyle
                      )}
                      aria-label={t("homework.excellent.rank", { rank })}
                    >
                      {RankIcon ? (
                        <RankIcon className="h-4 w-4" />
                      ) : (
                        <span className="text-xs font-semibold">{rank}</span>
                      )}
                    </div>

                    {/* 学生信息 + 提交时间 */}
                    <div className="flex min-w-0 flex-1 flex-col gap-0.5">
                      <div className="flex items-center gap-2">
                        <span className="truncate text-sm font-medium">{displayName}</span>
                        {item.isLate && (
                          <Badge
                            variant="outline"
                            className="h-5 shrink-0 gap-1 px-1.5 text-[10px] text-orange-600"
                          >
                            <Clock className="h-3 w-3" />
                            {t("homework.excellent.lateTag")}
                          </Badge>
                        )}
                      </div>
                      {submittedDate && (
                        <span className="text-xs text-muted-foreground">
                          {t("homework.excellent.submittedAt", { date: submittedDate })}
                        </span>
                      )}
                    </div>

                    {/* 分数 + 得分率 */}
                    <div className="flex shrink-0 items-center gap-3">
                      <div className="text-right">
                        <div className="text-sm font-semibold tabular-nums">
                          {t("homework.excellent.scoreValue", {
                            score: item.totalScore,
                            max: item.maxScore,
                          })}
                        </div>
                        <div className="text-xs text-muted-foreground tabular-nums">
                          {t("homework.excellent.percentage", { value: item.percentage })}
                        </div>
                      </div>
                      <ChevronRight className="h-4 w-4 text-muted-foreground" />
                    </div>
                  </Link>
                </li>
              )
            })}
          </ul>
        )}
      </CardContent>
    </Card>
  )
}

/**
 * 骨架屏 —— 数据加载时展示。
 */
function ExcellentSubmissionsSkeleton(): ReactNode {
  return (
    <Card className="w-full">
      <CardHeader className="pb-3">
        <Skeleton className="h-5 w-40" />
        <Skeleton className="mt-1 h-3 w-64" />
      </CardHeader>
      <CardContent className="space-y-2">
        {Array.from({ length: 3 }).map((_, i) => (
          <div key={i} className="flex items-center gap-3 rounded-md border p-3">
            <Skeleton className="h-9 w-9 rounded-full" />
            <div className="flex-1 space-y-1">
              <Skeleton className="h-3 w-24" />
              <Skeleton className="h-2 w-32" />
            </div>
            <Skeleton className="h-8 w-16" />
          </div>
        ))}
      </CardContent>
    </Card>
  )
}

/**
 * 带边界的优秀作业展示组件。
 *
 * 包裹 SectionErrorBoundary + Suspense，防止单个区块错误导致整页崩溃。
 * 使用示例：
 *
 * ```tsx
 * <ExcellentSubmissionsWithBoundary assignmentId={id} />
 * ```
 */
export function ExcellentSubmissionsWithBoundary(
  props: ExcellentSubmissionsProps
): ReactNode {
  return (
    <SectionErrorBoundary namespace="examHomework">
      <Suspense fallback={<ExcellentSubmissionsSkeleton />}>
        <ExcellentSubmissions {...props} />
      </Suspense>
    </SectionErrorBoundary>
  )
}
