import Link from "next/link"
import { getTranslations } from "next-intl/server"
import { ArrowLeft, CalendarDays } from "lucide-react"

import { getAuthContext } from "@/shared/lib/auth-guard"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { getStudentActiveClass } from "@/modules/classes/data-access"
import { getLeaveRequests } from "@/modules/leave-requests/data-access"
import { LeaveRequestForm } from "@/modules/leave-requests/components/leave-request-form"
import { LeaveRequestList } from "@/modules/leave-requests/components/leave-request-list"

export const dynamic = "force-dynamic"

/**
 * 学生在线请假页面。
 *
 * L-5 功能：
 * - 顶部：请假申请表单（学生本人提交，classId 自动写入当前活跃班级）
 * - 底部：学生本人提交的请假申请列表
 *
 * 学生 scope 为 class_members，data-access 中 buildScopeFilter 返回 1=0，
 * 但通过 currentUserId = requesterId 过滤出本人提交的记录。
 */
export default async function StudentLeavePage() {
  const t = await getTranslations("leave")
  const ctx = await getAuthContext()

  // 并行：学生当前活跃班级 + 本人请假记录
  const [activeClass, leaveResult] = await Promise.all([
    getStudentActiveClass(ctx.userId),
    getLeaveRequests({
      scope: ctx.dataScope,
      currentUserId: ctx.userId,
      page: 1,
      pageSize: 50,
    }),
  ])

  return (
    <div className="p-6 md:p-8 space-y-6">
      <div className="space-y-1">
        <h1 className="text-2xl font-bold tracking-tight">{t("title.student")}</h1>
        <p className="text-sm text-muted-foreground">{t("description.student")}</p>
      </div>

      <Button asChild variant="ghost" size="sm" className="gap-2 -ml-2">
        <Link href="/student/dashboard">
          <ArrowLeft className="h-4 w-4" />
          {t("backToDashboard")}
        </Link>
      </Button>

      {activeClass ? (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <CalendarDays className="h-4 w-4 text-muted-foreground" aria-hidden />
              {t("onlineLeave")}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <LeaveRequestForm
              defaultStudentId={ctx.userId}
              defaultClassId={activeClass.classId}
            />
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="py-10 text-center text-sm text-muted-foreground">
            {t("empty.studentDesc")}
          </CardContent>
        </Card>
      )}

      <div className="space-y-3">
        <h2 className="text-lg font-semibold">{t("onlineLeave")}</h2>
        <LeaveRequestList
          items={leaveResult.items}
          emptyTitle={t("empty.studentTitle")}
          emptyDescription={t("empty.studentDesc")}
        />
      </div>
    </div>
  )
}
