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 { EmptyState } from "@/shared/components/ui/empty-state"
import { StatCard } from "@/shared/components/ui/stat-card"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { BarChart3 } from "lucide-react"
import { formatDate } from "@/shared/lib/utils"
import { getParam, type SearchParams } from "@/shared/lib/search-params"

export const dynamic = "force-dynamic"

const formatScore = (v: number | null, digits = 1) => (typeof v === "number" && Number.isFinite(v) ? v.toFixed(digits) : "-")

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

export default async function TeacherGradeInsightsPage({ searchParams }: { searchParams: Promise<SearchParams> }): Promise<JSX.Element> {
  await requirePermission(Permissions.GRADE_RECORD_READ)
  const t = await getTranslations("school")
  const params = await searchParams
  const gradeId = getParam(params, "gradeId")

  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 insights = selected ? await getGradeHomeworkInsights({ gradeId: selected, limit: 50 }) : null

  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("classManagement.grade.insights.title")}</h2>
          <p className="text-muted-foreground">{t("classManagement.grade.insights.description")}</p>
        </div>
        <EmptyState
          icon={BarChart3}
          title={t("classManagement.grade.insights.noGrades")}
          description={t("classManagement.grade.insights.noGradesDescription")}
          className="h-[360px] bg-card"
        />
      </div>
    )
  }

  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("classManagement.grade.insights.title")}</h2>
        <p className="text-muted-foreground">{t("classManagement.grade.insights.description")}</p>
      </div>

      <Card className="shadow-none">
        <CardHeader className="flex flex-row items-center justify-between space-y-0">
          <CardTitle className="text-base">{t("classManagement.grade.insights.filters")}</CardTitle>
          <Badge variant="secondary" className="tabular-nums">
            {grades.length}
          </Badge>
        </CardHeader>
        <CardContent>
          <form action="/management/grade/insights" method="get" className="flex flex-col gap-3 md:flex-row md:items-center">
            <label htmlFor="gradeId" className="text-sm font-medium">{t("classManagement.grade.insights.grade")}</label>
            <select
              id="gradeId"
              name="gradeId"
              defaultValue={selected || "all"}
              className="h-10 w-full rounded-md border bg-background px-3 text-sm md:w-[360px]"
            >
              <option value="all">{t("classManagement.grade.insights.selectGrade")}</option>
              {grades.map((g) => (
                <option key={g.id} value={g.id}>
                  {g.school.name} / {g.name}
                </option>
              ))}
            </select>
            <Button type="submit" className="md:ml-2">
              {t("classManagement.grade.insights.apply")}
            </Button>
          </form>
        </CardContent>
      </Card>

      {!selected ? (
        <EmptyState
          icon={BarChart3}
          title={t("classManagement.grade.insights.selectToView")}
          description={t("classManagement.grade.insights.selectToViewDescription")}
          className="h-[360px] bg-card"
        />
      ) : !insights ? (
        <EmptyState
          icon={BarChart3}
          title={t("classManagement.grade.insights.notFound")}
          description={t("classManagement.grade.insights.notFoundDescription")}
          className="h-[360px] bg-card"
        />
      ) : insights.assignments.length === 0 ? (
        <EmptyState
          icon={BarChart3}
          title={t("classManagement.grade.insights.noData")}
          description={t("classManagement.grade.insights.noDataDescription")}
          className="h-[360px] bg-card"
        />
      ) : (
        <div className="space-y-6">
          <div className="grid gap-4 md:grid-cols-4">
            <StatCard
              title={t("classManagement.grade.insights.classes")}
              value={insights.classCount}
              description={`${insights.grade.school.name} / ${insights.grade.name}`}
              valueClassName="tabular-nums"
            />
            <StatCard
              title={t("classManagement.grade.insights.students")}
              value={insights.studentCounts.total}
              description={`${t("classManagement.grade.insights.active")} ${insights.studentCounts.active} • ${t("classManagement.grade.insights.inactive")} ${insights.studentCounts.inactive}`}
              valueClassName="tabular-nums"
            />
            <StatCard
              title={t("classManagement.grade.insights.overallAvg")}
              value={formatScore(insights.overallScores.avg)}
              description="-"
              valueClassName="tabular-nums"
            />
            <StatCard
              title={t("classManagement.grade.insights.latestAvg")}
              value={formatScore(insights.latest?.scoreStats.avg ?? null)}
              description={insights.latest ? insights.latest.title : "-"}
              valueClassName="tabular-nums"
            />
          </div>

          <Card className="shadow-none">
            <CardHeader className="flex flex-row items-center justify-between space-y-0">
              <CardTitle className="text-base">{t("classManagement.grade.insights.homeworkTimeline")}</CardTitle>
              <Badge variant="secondary" className="tabular-nums">
                {insights.assignments.length}
              </Badge>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/50">
                      <TableHead>{t("classManagement.grade.insights.assignment")}</TableHead>
                      <TableHead>{t("classManagement.grade.insights.status")}</TableHead>
                      <TableHead>{t("classManagement.grade.insights.created")}</TableHead>
                      <TableHead className="text-right">{t("classManagement.grade.insights.targeted")}</TableHead>
                      <TableHead className="text-right">{t("classManagement.grade.insights.submitted")}</TableHead>
                      <TableHead className="text-right">{t("classManagement.grade.insights.graded")}</TableHead>
                      <TableHead className="text-right">{t("classManagement.grade.insights.avg")}</TableHead>
                      <TableHead className="text-right">{t("classManagement.grade.insights.median")}</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {insights.assignments.map((a) => (
                      <TableRow key={a.assignmentId}>
                        <TableCell className="font-medium">{a.title}</TableCell>
                        <TableCell>
                          <Badge variant="secondary" className="capitalize">
                            {a.status}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-muted-foreground">{formatDate(a.createdAt)}</TableCell>
                        <TableCell className="text-right tabular-nums">{a.targetCount}</TableCell>
                        <TableCell className="text-right tabular-nums">{a.submittedCount}</TableCell>
                        <TableCell className="text-right tabular-nums">{a.gradedCount}</TableCell>
                        <TableCell className="text-right tabular-nums">{formatScore(a.scoreStats.avg)}</TableCell>
                        <TableCell className="text-right tabular-nums">{formatScore(a.scoreStats.median)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>

          <Card className="shadow-none">
            <CardHeader className="flex flex-row items-center justify-between space-y-0">
              <CardTitle className="text-base">{t("classManagement.grade.insights.classRanking")}</CardTitle>
              <Badge variant="secondary" className="tabular-nums">
                {insights.classes.length}
              </Badge>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/50">
                      <TableHead>{t("classManagement.grade.insights.class")}</TableHead>
                      <TableHead className="text-right">{t("classManagement.grade.insights.students")}</TableHead>
                      <TableHead className="text-right">{t("classManagement.grade.insights.latestAvgCol")}</TableHead>
                      <TableHead className="text-right">{t("classManagement.grade.insights.prevAvg")}</TableHead>
                      <TableHead className="text-right">{t("classManagement.grade.insights.delta")}</TableHead>
                      <TableHead className="text-right">{t("classManagement.grade.insights.overallAvgCol")}</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {insights.classes.map((c) => (
                      <TableRow key={c.class.id}>
                        <TableCell className="font-medium">
                          {c.class.name}
                          {c.class.homeroom ? <span className="text-muted-foreground"> • {c.class.homeroom}</span> : null}
                        </TableCell>
                        <TableCell className="text-right tabular-nums">{c.studentCounts.total}</TableCell>
                        <TableCell className="text-right tabular-nums">{formatScore(c.latestAvg)}</TableCell>
                        <TableCell className="text-right tabular-nums">{formatScore(c.prevAvg)}</TableCell>
                        <TableCell className="text-right tabular-nums">{formatScore(c.deltaAvg)}</TableCell>
                        <TableCell className="text-right tabular-nums">{formatScore(c.overallScores.avg)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  )
}
