import type { Metadata } from "next"
import type { JSX } from "react"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getSearchParam, type SearchParams } from "@/shared/lib/utils"
import {
  getDataChangeLogs,
  getDataChangeStats,
  getDataChangeTableOptions,
} from "@/modules/audit/data-access"
import { DataChangeLogTable } from "@/modules/audit/components/data-change-log-table"
import { AuditLogExportButton } from "@/modules/audit/components/audit-log-export-button"
import type { DataChangeAction } from "@/modules/audit/types"

export const metadata: Metadata = {
  title: "数据变更日志 - Next_Edu",
  description: "追踪系统所有数据变更（增删改），保障合规",
}

export const dynamic = "force-dynamic"

const isValidDataChangeAction = (v?: string): v is DataChangeAction =>
  v === "create" || v === "update" || v === "delete"

export default async function DataChangeLogsPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  await requirePermission(Permissions.AUDIT_LOG_READ)

  const params = await searchParams
  const page = Number(getSearchParam(params, "page") ?? "1") || 1
  const tableName = getSearchParam(params, "tableName") ?? undefined
  const actionParam = getSearchParam(params, "action")
  const action = isValidDataChangeAction(actionParam) ? actionParam : undefined
  const startDate = getSearchParam(params, "startDate") ?? undefined
  const endDate = getSearchParam(params, "endDate") ?? undefined

  const [result, tableOptions, stats] = await Promise.all([
    getDataChangeLogs({ page, tableName, action, startDate, endDate }),
    getDataChangeTableOptions(),
    getDataChangeStats(),
  ])

  const exportParams: Record<string, string> = {}
  if (tableName) exportParams.tableName = tableName
  if (action) exportParams.action = action
  if (startDate) exportParams.startDate = startDate
  if (endDate) exportParams.endDate = endDate

  return (
    <div className="flex h-full flex-col space-y-8 p-8">
      <div className="flex items-start justify-between gap-4">
        <div className="space-y-1">
          <h2 className="text-2xl font-bold tracking-tight">数据变更日志</h2>
          <p className="text-muted-foreground">
            追踪系统所有数据变更（增删改），保障合规。
          </p>
        </div>
        <AuditLogExportButton exportType="dataChange" params={exportParams} />
      </div>
      <DataChangeLogTable
        items={result.items}
        page={result.page}
        pageSize={result.pageSize}
        total={result.total}
        totalPages={result.totalPages}
        tableOptions={tableOptions}
        stats={stats}
      />
    </div>
  )
}
