import type { Metadata } from "next"
import type { JSX } from "react"
import { notFound } from "next/navigation"
import { getTranslations } from "next-intl/server"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getClassHomeworkInsights, getClassSchedule, getClassStudentSubjectScoresV2, getClassStudents } from "@/modules/classes/data-access"
import { ClassAssignmentsWidget } from "@/modules/classes/components/class-detail/class-assignments-widget"
import { ClassErrorBoundary } from "@/modules/classes/components/class-error-boundary"
import { ClassTrendsWidget } from "@/modules/classes/components/class-detail/class-trends-widget"
import { ClassHeader } from "@/modules/classes/components/class-detail/class-header"
import { ClassOverviewStats } from "@/modules/classes/components/class-detail/class-overview-stats"
import { ClassScheduleWidget } from "@/modules/classes/components/class-detail/class-schedule-widget"
import { ClassStudentsWidget } from "@/modules/classes/components/class-detail/class-students-widget"

export const dynamic = "force-dynamic"

export async function generateMetadata(): Promise<Metadata> {
  const t = await getTranslations("classes")
  return {
    title: `${t("metadata.classDetail")} - Next_Edu`,
    description: t("metadata.classDetail"),
  }
}

export default async function ClassDetailPage({
  params,
}: {
  params: Promise<{ id: string }>
}): Promise<JSX.Element> {
  const { id } = await params
  await requirePermission(Permissions.CLASS_READ)

  // Parallel data fetching
  const [insights, students, schedule, studentScores] = await Promise.all([
    getClassHomeworkInsights({ classId: id, limit: 20 }),
    getClassStudents({ classId: id }),
    getClassSchedule({ classId: id }),
    getClassStudentSubjectScoresV2({ classId: id }),
  ])

  if (!insights) return notFound()

  // Data mapping for widgets
  const assignmentSummaries = insights.assignments.map(a => ({
    id: a.assignmentId,
    title: a.title,
    status: a.status,
    subject: a.subject,
    isActive: a.isActive,
    isOverdue: a.isOverdue,
    dueAt: a.dueAt ? new Date(a.dueAt) : null,
    submittedCount: a.submittedCount,
    targetCount: a.targetCount,
    avgScore: a.scoreStats.avg,
    medianScore: a.scoreStats.median
  }))

  const studentSummaries = students.map(s => ({
    id: s.id,
    name: s.name,
    email: s.email,
    image: s.image,
    status: s.status,
    subjectScores: studentScores.get(s.id) ?? {}
  }))

  // Calculate advanced stats
  const activeAssignments = insights.assignments.filter(a => a.isActive)
  const papersToGrade = activeAssignments.reduce((acc, a) => acc + (a.submittedCount - a.gradedCount), 0)
  const overdueCount = activeAssignments.filter(a => a.isOverdue).length

  const totalSubmissionRate = activeAssignments.length > 0
    ? activeAssignments.reduce((acc, a) => acc + (a.targetCount > 0 ? a.submittedCount / a.targetCount : 0), 0) / activeAssignments.length
    : 0

  return (
    <div className="flex min-h-screen flex-col bg-muted/10">
      <ClassErrorBoundary>
        <ClassHeader
          classId={insights.class.id}
          name={insights.class.name}
          grade={insights.class.grade}
          homeroom={insights.class.homeroom}
          room={insights.class.room}
          schoolName={insights.class.schoolName}
          studentCount={insights.studentCounts.total}
        />

        <div className="flex-1 space-y-6 p-6">
          {/* Key Metrics */}
          <ClassOverviewStats
            averageScore={insights.overallScores.avg}
            submissionRate={totalSubmissionRate * 100}
            papersToGrade={papersToGrade}
            overdueCount={overdueCount}
          />

          <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
            {/* Main Content Area (Left 2/3) */}
            <div className="min-w-0 space-y-6 lg:col-span-2">
              <ClassTrendsWidget assignments={assignmentSummaries} />
              <ClassStudentsWidget
                classId={insights.class.id}
                students={studentSummaries}
              />
            </div>

            {/* Sidebar Area (Right 1/3) */}
            <div className="min-w-0 space-y-6">
              <ClassScheduleWidget classId={insights.class.id} schedule={schedule} />
              <ClassAssignmentsWidget
                classId={insights.class.id}
                assignments={assignmentSummaries}
              />
            </div>
          </div>
        </div>
      </ClassErrorBoundary>
    </div>
  )
}
