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 { getAdminUsers, getAdminUserRoles } from "@/modules/users/data-access"
import { AdminUsersView } from "@/modules/users/components/admin-users-view"

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

export const dynamic = "force-dynamic"

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

  const sp = await searchParams
  const page = Number(getSearchParam(sp, "page") ?? "1") || 1
  const search = getSearchParam(sp, "search") ?? ""
  const role = getSearchParam(sp, "role") ?? ""

  const [result, roleOptions] = await Promise.all([
    getAdminUsers({ page, search: search || undefined, role: role || undefined }),
    getAdminUserRoles(),
  ])

  return (
    <div className="flex h-full flex-col space-y-6 p-8">
      <AdminUsersView
        users={result.items}
        roleOptions={roleOptions}
        page={result.page}
        pageSize={result.pageSize}
        total={result.total}
        totalPages={result.totalPages}
        search={search}
        roleFilter={role}
      />
    </div>
  )
}
