import type { JSX } from "react"
import { notFound } from "next/navigation"
import { getHomeworkSubmissionDetails } from "@/modules/homework/data-access"
import { HomeworkGradingView } from "@/modules/homework/components/homework-grading-view"
import { formatDate } from "@/shared/lib/utils"
import {
  AiClientProvider,
  type AiClientService,
} from "@/modules/ai/context/ai-client-provider"
import {
  suggestGradingAction,
  aiChatAction,
  suggestSimilarQuestionsAction,
  generateLessonContentAction,
  generateQuestionVariantAction,
  analyzeWeaknessAction,
} from "@/modules/ai/actions"

export const dynamic = "force-dynamic"

/**
 * 构建 AI 客户端服务（Server Action 引用集合）
 *
 * 通过 React Context 注入，客户端组件不直接 import actions，
 * 遵循依赖注入模式，便于测试时替换为 mock。
 */
function createAiClientService(): AiClientService {
  return {
    chat: aiChatAction,
    suggestSimilarQuestions: suggestSimilarQuestionsAction,
    suggestGrading: suggestGradingAction,
    generateLessonContent: generateLessonContentAction,
    generateQuestionVariant: generateQuestionVariantAction,
    analyzeWeakness: analyzeWeaknessAction,
  }
}

export default async function HomeworkSubmissionGradingPage({ params }: { params: Promise<{ submissionId: string }> }): Promise<JSX.Element> {
  const { submissionId } = await params
  const submission = await getHomeworkSubmissionDetails(submissionId)

  if (!submission) return notFound()

  const aiClientService = createAiClientService()

  return (
    <div className="flex h-full flex-col space-y-4 p-6">
      <div className="flex items-center justify-between">
        <div className="min-w-0">
          <h1 className="text-2xl font-bold tracking-tight line-clamp-2">{submission.assignmentTitle}</h1>
          <div className="flex items-center gap-4 text-sm text-muted-foreground mt-1">
            <span>
              Student: <span className="font-medium text-foreground">{submission.studentName}</span>
            </span>
            <span aria-hidden="true">•</span>
            <span className="tabular-nums">Submitted: {submission.submittedAt ? formatDate(submission.submittedAt) : "-"}</span>
            <span aria-hidden="true">•</span>
            <span className="capitalize">Status: {submission.status}</span>
          </div>
        </div>
      </div>

      <AiClientProvider service={aiClientService}>
        <HomeworkGradingView
          submissionId={submission.id}
          studentName={submission.studentName}
          assignmentTitle={submission.assignmentTitle}
          submittedAt={submission.submittedAt}
          status={submission.status}
          totalScore={submission.totalScore}
          answers={submission.answers}
          prevSubmissionId={submission.prevSubmissionId}
          nextSubmissionId={submission.nextSubmissionId}
        />
      </AiClientProvider>
    </div>
  )
}
