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 { getLoginLogs } from "@/modules/audit/data-access"
import { LoginLogView } from "@/modules/audit/components/login-log-view"
import { AuditLogExportButton } from "@/modules/audit/components/audit-log-export-button"
import { AuditErrorBoundary } from "@/modules/audit/components/audit-error-boundary"
import type { LoginLogAction, LoginLogStatus } from "@/modules/audit/types"

export async function generateMetadata(): Promise<Metadata> {
  const t = await getTranslations("audit")
  return {
    title: `${t("loginLogs.title")} - Next_Edu`,
    description: t("loginLogs.description"),
  }
}

export const dynamic = "force-dynamic"

const isValidLoginLogAction = (v?: string): v is LoginLogAction =>
  v === "signin" || v === "signout" || v === "signup"

const isValidLoginLogStatus = (v?: string): v is LoginLogStatus =>
  v === "success" || v === "failure"

export default async function LoginLogsPage({
  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 actionParam = getSearchParam(params, "action")
  const action = isValidLoginLogAction(actionParam) ? actionParam : undefined
  const statusParam = getSearchParam(params, "status")
  const status = isValidLoginLogStatus(statusParam) ? statusParam : undefined
  const userId = getSearchParam(params, "userId") ?? undefined
  const startDate = getSearchParam(params, "startDate") ?? undefined
  const endDate = getSearchParam(params, "endDate") ?? undefined

  const result = await getLoginLogs({ page, action, status, userId, startDate, endDate })

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