import type { Metadata } from "next"
import type { JSX } from "react"

import { getTranslations } from "next-intl/server"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getTeacherIdForMutations } from "@/modules/classes/data-access"
import { getGradeHomeworkInsights } from "@/modules/classes/data-access"
import { getGradesForStaff } from "@/modules/school/data-access"
import { getGradeDistributionByGradeId } from "@/modules/grades/data-access-analytics"
import { getExamsByGradeId } from "@/modules/exams/data-access"
import { getGradeCoursePlanProgress } from "@/modules/course-plans/data-access"
import { GradeInsightsFilters } from "@/modules/school/components/grade-insights-filters"
import { GradeDistributionPanel } from "@/modules/school/components/grade-dashboard/grade-distribution-panel"
import { GradeHomeworkPanel } from "@/modules/school/components/grade-dashboard/grade-homework-panel"
import { GradeExamsPanel } from "@/modules/school/components/grade-dashboard/grade-exams-panel"
import { GradeProgressPanel } from "@/modules/school/components/grade-dashboard/grade-progress-panel"
import { SchoolErrorBoundary } from "@/modules/school/components/school-error-boundary"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { ChipNav } from "@/shared/components/ui/chip-nav"
import { BarChart3 } from "lucide-react"
import { getParam, type SearchParams } from "@/shared/lib/search-params"

export const dynamic = "force-dynamic"

const TAB_OPTIONS = [
  { id: "distribution", name: "" },
  { id: "homework", name: "" },
  { id: "exams", name: "" },
  { id: "progress", name: "" },
] as const

type TabId = (typeof TAB_OPTIONS)[number]["id"]

const isTabId = (v: string): v is TabId =>
  v === "distribution" || v === "homework" || v === "exams" || v === "progress"

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

export default async function GradeDashboardPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  const ctx = await requirePermission(Permissions.GRADE_RECORD_READ)
  const t = await getTranslations("school")
  const params = await searchParams
  const gradeId = getParam(params, "gradeId")
  const tabRaw = getParam(params, "tab") || "distribution"
  const tab: TabId = isTabId(tabRaw) ? tabRaw : "distribution"

  const teacherId = await getTeacherIdForMutations()
  const grades = await getGradesForStaff(teacherId)
  const allowedIds = new Set(grades.map((g) => g.id))
  const selected = gradeId && gradeId !== "all" && allowedIds.has(gradeId) ? gradeId : ""

  const buildHref = (gId: string): string => {
    const p = new URLSearchParams()
    if (gId && gId !== "all") p.set("gradeId", gId)
    if (tab !== "distribution") p.set("tab", tab)
    const qs = p.toString()
    return qs ? `/management/grade/dashboard?${qs}` : "/management/grade/dashboard"
  }

  const buildTabHref = (tId: string): string => {
    const p = new URLSearchParams()
    if (selected) p.set("gradeId", selected)
    if (tId !== "distribution") p.set("tab", tId)
    const qs = p.toString()
    return qs ? `/management/grade/dashboard?${qs}` : "/management/grade/dashboard"
  }

  const tabOptions = TAB_OPTIONS.map((o) => ({
    id: o.id,
    name: t(`grades.gradeDashboard.tabs.${o.id}` as const),
  }))

  if (grades.length === 0) {
    return (
      <div className="flex h-full flex-col space-y-8 p-8">
        <div className="space-y-1">
          <h2 className="text-2xl font-bold tracking-tight">{t("grades.gradeDashboard.title")}</h2>
          <p className="text-muted-foreground">{t("grades.gradeDashboard.description")}</p>
        </div>
        <EmptyState
          icon={BarChart3}
          title={t("grades.gradeDashboard.selectToView")}
          description={t("grades.gradeDashboard.selectToViewDescription")}
          className="h-[360px] bg-card"
        />
      </div>
    )
  }

  // Fetch data for the active tab only
  let distributionData = null
  let homeworkData = null
  let examsData = null
  let progressData = null

  if (selected) {
    if (tab === "distribution") {
      distributionData = await getGradeDistributionByGradeId({
        gradeId: selected,
        scope: ctx.dataScope,
      })
    } else if (tab === "homework") {
      homeworkData = await getGradeHomeworkInsights({ gradeId: selected, limit: 50 })
    } else if (tab === "exams") {
      examsData = await getExamsByGradeId({ gradeId: selected, scope: ctx.dataScope })
    } else if (tab === "progress") {
      progressData = await getGradeCoursePlanProgress({ gradeId: selected })
    }
  }

  return (
    <div className="flex h-full flex-col space-y-8 p-8">
      <div className="space-y-1">
        <h2 className="text-2xl font-bold tracking-tight">{t("grades.gradeDashboard.title")}</h2>
        <p className="text-muted-foreground">{t("grades.gradeDashboard.description")}</p>
      </div>

      <SchoolErrorBoundary>
        <GradeInsightsFilters
          grades={grades.map((g) => ({ id: g.id, name: g.name, schoolName: g.school.name }))}
          currentGradeId={selected || "all"}
          buildHref={buildHref}
        />

        {!selected ? (
          <EmptyState
            icon={BarChart3}
            title={t("grades.gradeDashboard.selectToView")}
            description={t("grades.gradeDashboard.selectToViewDescription")}
            className="h-[360px] bg-card"
          />
        ) : (
          <div className="space-y-6">
            <ChipNav
              options={tabOptions}
              currentId={tab}
              buildHref={buildTabHref}
            />

            {tab === "distribution" && distributionData && (
              <GradeDistributionPanel data={distributionData} />
            )}
            {tab === "homework" && homeworkData && (
              <GradeHomeworkPanel data={homeworkData} />
            )}
            {tab === "exams" && examsData && (
              <GradeExamsPanel data={examsData} />
            )}
            {tab === "progress" && progressData && (
              <GradeProgressPanel data={progressData} />
            )}

            {/* Fallback: data was null (e.g. homework insights returned null) */}
            {((tab === "distribution" && !distributionData) ||
              (tab === "homework" && !homeworkData) ||
              (tab === "exams" && !examsData) ||
              (tab === "progress" && !progressData)) && (
              <EmptyState
                icon={BarChart3}
                title={t("grades.gradeDashboard.noData")}
                description={t("grades.gradeDashboard.noDataDescription")}
                className="h-[360px] bg-card"
              />
            )}
          </div>
        )}
      </SchoolErrorBoundary>
    </div>
  )
}
