import { createAdminClient } from "@/lib/supabase/admin"
import {
  VerificationQueue,
  type VerificationRequestItem,
} from "@/components/admin/verification-queue"

export const dynamic = "force-dynamic"

// Admin guard is handled by app/admin/layout.tsx. This page simply
// loads every verification request (newest first), joins them against
// the profiles table for display info, and hands the data off to the
// client component that renders the interactive queue.
export default async function AdminVerificationPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string }>
}) {
  const params = await searchParams
  const statusFilter =
    params.status === "approved" ||
    params.status === "rejected" ||
    params.status === "pending"
      ? params.status
      : "pending"

  const admin = createAdminClient()
  const { data: requests, error } = await admin
    .from("verification_requests")
    .select(
      "id, user_id, full_name, aadhaar, mobile, status, rejection_reason, created_at, reviewed_at",
    )
    .eq("status", statusFilter)
    .order("created_at", { ascending: false })
    .limit(200)

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

  // Join profile + auth info for every applicant so the UI can show a
  // name / email / avatar next to each request.
  const userIds = Array.from(new Set((requests ?? []).map((r) => r.user_id)))
  const profileById = new Map<
    string,
    { display_name: string | null; avatar_url: string | null; verified: boolean }
  >()
  const emailById = new Map<string, string>()

  if (userIds.length > 0) {
    const [{ data: profs }, authLookups] = await Promise.all([
      admin
        .from("profiles")
        .select("id, display_name, avatar_url, verified")
        .in("id", userIds),
      // `listUsers` doesn't support an `in` filter, so we call
      // `getUserById` in parallel for each id. User volume per pending
      // page is small (<= 200), so this is fine.
      Promise.all(
        userIds.map((uid) =>
          admin.auth.admin.getUserById(uid).then((res) => ({ uid, res })),
        ),
      ),
    ])
    for (const p of profs ?? []) {
      profileById.set(p.id, {
        display_name: p.display_name ?? null,
        avatar_url: p.avatar_url ?? null,
        verified: !!p.verified,
      })
    }
    for (const { uid, res } of authLookups) {
      const email = res.data?.user?.email
      if (email) emailById.set(uid, email)
    }
  }

  const items: VerificationRequestItem[] = (requests ?? []).map((r) => {
    const p = profileById.get(r.user_id)
    return {
      id: r.id,
      userId: r.user_id,
      fullName: r.full_name,
      aadhaar: r.aadhaar,
      mobile: r.mobile,
      status: r.status as "pending" | "approved" | "rejected",
      rejectionReason: r.rejection_reason,
      createdAt: r.created_at,
      reviewedAt: r.reviewed_at,
      displayName: p?.display_name ?? null,
      avatarUrl: p?.avatar_url ?? null,
      verified: p?.verified ?? false,
      email: emailById.get(r.user_id) ?? null,
    }
  })

  return <VerificationQueue items={items} status={statusFilter} />
}
