import type { JSX } from "react"
import Link from "next/link"
import { notFound } from "next/navigation"
import { getTranslations } from "next-intl/server"
import { getHomeworkSubmissionDetails } from "@/modules/homework/data-access"
import { HomeworkGradingView } from "@/modules/homework/components/homework-grading-view"
import { Button } from "@/shared/components/ui/button"
import { ScanLine } from "lucide-react"
import { formatDate } from "@/shared/lib/utils"
import { AiClientProvider } from "@/modules/ai/context/ai-client-provider"
import { createCoreAiClientService } from "@/modules/ai/context/create-ai-client-service"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"

export const dynamic = "force-dynamic"

export default async function HomeworkSubmissionGradingPage({ params }: { params: Promise<{ submissionId: string }> }): Promise<JSX.Element> {
  const { submissionId } = await params
  await requirePermission(Permissions.HOMEWORK_GRADE)
  const t = await getTranslations("examHomework")
  const submission = await getHomeworkSubmissionDetails(submissionId)

  if (!submission) return notFound()

  const aiClientService = createCoreAiClientService()

  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>
              {t("homework.grade.student")}: <span className="font-medium text-foreground">{submission.studentName}</span>
            </span>
            <span aria-hidden="true">•</span>
            <span className="tabular-nums">{t("homework.grade.submitted")}: {submission.submittedAt ? formatDate(submission.submittedAt) : "-"}</span>
            <span aria-hidden="true">•</span>
            <span className="capitalize">{t("homework.grade.status")}: {submission.status}</span>
          </div>
        </div>
        <Button asChild variant="outline" size="sm">
          <Link href={`/teacher/homework/submissions/${submissionId}/scan-grading`}>
            <ScanLine className="mr-2 h-4 w-4" />
            {t("homework.grade.scanGrading")}
          </Link>
        </Button>
      </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>
  )
}
