import Link from "next/link"
import type { Metadata } from "next"
import type { JSX } from "react"
import { BarChart3, ClipboardList } from "lucide-react"
import { getTranslations } from "next-intl/server"

import { Button } from "@/shared/components/ui/button"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { requirePermission, getAuthContext } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getSearchParam, type SearchParams } from "@/shared/lib/utils"
import { getAdminClasses } from "@/modules/classes/data-access"
import { getAttendanceRecords, getAttendanceStats } from "@/modules/attendance/data-access"
import { AttendanceFilters } from "@/modules/attendance/components/attendance-filters"
import { AttendanceStatsCards } from "@/modules/attendance/components/attendance-stats-cards"
import { AttendanceRecordList } from "@/modules/attendance/components/attendance-record-list"
import { AttendancePageLayout } from "@/modules/attendance/components/attendance-page-layout"
import type { AttendanceStatus } from "@/modules/attendance/types"

export const dynamic = "force-dynamic"

const isValidAttendanceStatus = (v?: string): v is AttendanceStatus =>
  v === "present" || v === "absent" || v === "late" || v === "early_leave" || v === "excused"

export default async function AdminAttendancePage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  await requirePermission(Permissions.ATTENDANCE_READ)
  const sp = await searchParams
  const ctx = await getAuthContext()
  const t = await getTranslations("attendance")

  const classId = getSearchParam(sp, "classId")
  const statusParam = getSearchParam(sp, "status")
  const status =
    statusParam && statusParam !== "all" && isValidAttendanceStatus(statusParam) ? statusParam : undefined
  const date = getSearchParam(sp, "date")

  const classes = await getAdminClasses()
  const classOptions = classes.map((c) => ({ id: c.id, name: c.name }))

  const result = await getAttendanceRecords({
    scope: ctx.dataScope,
    currentUserId: ctx.userId,
    classId: classId && classId !== "all" ? classId : undefined,
    status,
    date: date && date.length > 0 ? date : undefined,
  })

  const stats = await getAttendanceStats({
    scope: ctx.dataScope,
    currentUserId: ctx.userId,
    classId: classId && classId !== "all" ? classId : undefined,
    date: date && date.length > 0 ? date : undefined,
  })

  const header = (
    <div className="flex items-center justify-between space-y-2">
      <div>
        <h2 className="text-2xl font-bold tracking-tight">{t("title.adminOverview")}</h2>
        <p className="text-muted-foreground">{t("description.adminOverview")}</p>
      </div>
      <Button asChild variant="outline">
        <Link href="/teacher/attendance/stats">
          <BarChart3 className="mr-2 h-4 w-4" />
          {t("actions.stats")}
        </Link>
      </Button>
    </div>
  )

  return (
    <AttendancePageLayout
      header={header}
      stats={<AttendanceStatsCards stats={stats} />}
      filters={<AttendanceFilters classes={classOptions} />}
    >
      {result.items.length === 0 && !classId && !status && !date ? (
        <EmptyState
          title={t("list.empty")}
          description={t("list.emptyDescription")}
          icon={ClipboardList}
        />
      ) : (
        <AttendanceRecordList records={result.items} />
      )}
    </AttendancePageLayout>
  )
}
