import { createAdminClient } from "@/lib/supabase/admin"
import { AdminUsersTable, type AdminUser } from "@/components/admin/admin-users-table"

export const dynamic = "force-dynamic"

// Registered users — moved out of the Dashboard so admins have a dedicated
// place to search, paginate, and edit accounts without competing with
// metrics on the dashboard.
export default async function AdminUsersListPage({
  searchParams,
}: {
  searchParams: Promise<{ page?: string; q?: string }>
}) {
  const params = await searchParams
  const currentPage = Math.max(1, Number.parseInt(params.page ?? "1", 10) || 1)
  const query = (params.q ?? "").trim().toLowerCase()

  const admin = createAdminClient()
  const perPage = 50
  const usersPageRes = await admin.auth.admin.listUsers({
    page: currentPage,
    perPage,
  })

  const authUsers = usersPageRes.data?.users ?? []
  const userIds = authUsers.map((u) => u.id)

  // Join profile fields (including the `verified` flag so admins can see
  // at a glance who has the blue tick) in a single round-trip.
  const profileById = new Map<
    string,
    {
      age: number | null
      gender: string | null
      country: string | null
      state: string | null
      display_name: string | null
      avatar_url: string | null
      verified: boolean
    }
  >()
  if (userIds.length > 0) {
    const { data: profs } = await admin
      .from("profiles")
      .select("id, display_name, age, gender, country, state, avatar_url, verified")
      .in("id", userIds)
    for (const p of profs ?? []) {
      profileById.set(p.id, {
        display_name: p.display_name ?? null,
        age: p.age ?? null,
        gender: p.gender ?? null,
        country: p.country ?? null,
        state: p.state ?? null,
        avatar_url: p.avatar_url ?? null,
        verified: !!p.verified,
      })
    }
  }

  const mapped: AdminUser[] = authUsers.map((u) => {
    const p = profileById.get(u.id)
    const metaName =
      ((u.user_metadata as Record<string, unknown> | null)?.display_name as string | undefined) ??
      null
    return {
      id: u.id,
      email: u.email ?? "",
      displayName: p?.display_name ?? metaName,
      avatarUrl: p?.avatar_url ?? null,
      createdAt: u.created_at,
      lastSignInAt: u.last_sign_in_at ?? null,
      emailConfirmedAt: u.email_confirmed_at ?? null,
      age: p?.age ?? null,
      gender: p?.gender ?? null,
      country: p?.country ?? null,
      state: p?.state ?? null,
      verified: p?.verified ?? false,
    }
  })

  let filtered = mapped
  if (query) {
    filtered = mapped.filter((u) => {
      const haystack = [u.email, u.displayName, u.country, u.state, u.gender]
        .filter(Boolean)
        .join(" ")
        .toLowerCase()
      return haystack.includes(query)
    })
  }

  const totalLabel = `${filtered.length} on this page`

  if (usersPageRes.error) {
    return (
      <div className="rounded-lg border border-destructive/20 bg-destructive/5 p-4 text-sm text-destructive">
        Failed to load users: {usersPageRes.error.message}
      </div>
    )
  }

  return (
    <AdminUsersTable
      users={filtered}
      page={currentPage}
      perPage={perPage}
      totalLabel={totalLabel}
      initialQuery={params.q ?? ""}
    />
  )
}
