import type { JSX } from "react"
import { Suspense } from "react"
import { getTranslations } from "next-intl/server"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getLessonPlans, getLessonPlanStats } from "@/modules/lesson-preparation/data-access"
import { getSubjectOptions } from "@/modules/school/data-access"
import { LessonPlanList } from "@/modules/lesson-preparation/components/lesson-plan-list"
import { LessonPlanProviderSetup } from "@/modules/lesson-preparation/providers/lesson-plan-provider-setup"
import { ADMIN_ROLE_CONFIG } from "@/modules/lesson-preparation/providers/lesson-plan-provider"
import { Skeleton } from "@/shared/components/ui/skeleton"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"

export const dynamic = "force-dynamic"

export default async function AdminLessonPlansPage(): Promise<JSX.Element> {
  const t = await getTranslations("lessonPreparation")
  // V4 P0-2 修复：页面层补齐 requirePermission 权限校验
  const ctx = await requirePermission(Permissions.LESSON_PLAN_READ)

  // 通过 data-access 层查询，避免 app 层直接访问数据库（P0-1 修复）
  const [items, subjects, stats] = await Promise.all([
    getLessonPlans({}, ctx.dataScope, ctx.userId),
    getSubjectOptions(),
    getLessonPlanStats(),
  ])

  return (
    <div className="p-6 space-y-4">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">{t("admin.title")}</h1>
        <p className="text-muted-foreground">{t("admin.description")}</p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-on-surface-variant">
              {t("admin.stats.total")}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-on-surface-variant">
              {t("admin.stats.published")}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-primary">{stats.published}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-on-surface-variant">
              {t("admin.stats.draft")}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-on-surface-variant">{stats.draft}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-on-surface-variant">
              {t("admin.stats.archived")}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-on-surface-variant">{stats.archived}</div>
          </CardContent>
        </Card>
      </div>

      {/* P0-13 修复：包裹 LessonPlanProviderSetup，注入 admin 角色配置，使筛选功能生效 */}
      <LessonPlanProviderSetup roleConfig={ADMIN_ROLE_CONFIG}>
        <Suspense
          fallback={
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {Array.from({ length: 6 }).map((_, i) => (
                <Skeleton key={i} className="h-[180px] w-full" />
              ))}
            </div>
          }
        >
          <LessonPlanList initialItems={items} subjects={subjects} viewMode="admin" />
        </Suspense>
      </LessonPlanProviderSetup>
    </div>
  )
}
