import type { Metadata } from "next"
import type { JSX } from "react"
import { getTranslations } from "next-intl/server"

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 { DataChangeLogView } from "@/modules/audit/components/data-change-log-view"
import { AuditLogExportButton } from "@/modules/audit/components/audit-log-export-button"
import { AuditErrorBoundary } from "@/modules/audit/components/audit-error-boundary"
import type { DataChangeAction } from "@/modules/audit/types"

export async function generateMetadata(): Promise<Metadata> {
  const t = await getTranslations("audit")
  return {
    title: `${t("dataChanges.title")} - Next_Edu`,
    description: t("dataChanges.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> {
  const t = await getTranslations("audit")
  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 userId = getSearchParam(params, "userId") ?? undefined
  const startDate = getSearchParam(params, "startDate") ?? undefined
  const endDate = getSearchParam(params, "endDate") ?? undefined

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

  const exportParams: Record<string, string> = {}
  if (tableName) exportParams.tableName = tableName
  if (action) exportParams.action = action
  if (userId) exportParams.userId = userId
  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">{t("dataChanges.title")}</h2>
          <p className="text-muted-foreground">{t("dataChanges.description")}</p>
        </div>
        <AuditLogExportButton exportType="dataChange" params={exportParams} />
      </div>
      <AuditErrorBoundary>
        <DataChangeLogView
          items={result.items}
          page={result.page}
          pageSize={result.pageSize}
          total={result.total}
          totalPages={result.totalPages}
          tableOptions={tableOptions}
          stats={stats}
        />
      </AuditErrorBoundary>
    </div>
  )
}
