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

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 } from "@/modules/attendance/data-access"
import { AttendanceFilters } from "@/modules/attendance/components/attendance-filters"
import { AttendanceRecordList } from "@/modules/attendance/components/attendance-record-list"
import type { AttendanceStatus } from "@/modules/attendance/types"

export const metadata: Metadata = {
  title: "考勤总览 - Next_Edu",
  description: "查看全校所有班级的考勤记录",
}

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 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,
  })

  return (
    <div className="h-full flex-1 flex-col space-y-8 p-8 md:flex">
      <div className="flex items-center justify-between space-y-2">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">考勤总览</h2>
          <p className="text-muted-foreground">查看全校所有班级的考勤记录。</p>
        </div>
        <Button asChild variant="outline">
          <Link href="/teacher/attendance/stats">
            <BarChart3 className="mr-2 h-4 w-4" />
            统计分析
          </Link>
        </Button>
      </div>

      <AttendanceFilters classes={classOptions} />

      {result.items.length === 0 && !classId && !status && !date ? (
        <EmptyState
          title="暂无考勤记录"
          description="系统中尚未产生任何考勤记录。"
          icon={ClipboardList}
        />
      ) : (
        <AttendanceRecordList records={result.items} />
      )}
    </div>
  )
}
