import { AppShell } from "@/components/app-shell"
import { SiteHeader } from "@/components/site-header"
import { requireStaffSession } from "@/lib/auth-server"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { prisma } from "@/lib/prisma"
import { AdminClientsManager, type AdminClient } from "@/components/admin/clients/admin-clients-manager"

export const runtime = "nodejs"
export const dynamic = "force-dynamic"

export default async function AdminClientsPage() {
  const session = await requireStaffSession()
  const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID

  const users = await prisma.user.findMany({
    where: {
      tenantId,
      role: { in: ["MANAGER", "COLLABORATOR"] },
    },
    include: {
      company: {
        select: {
          id: true,
          name: true,
        },
      },
    },
    orderBy: { createdAt: "desc" },
  })

  const emails = users.map((user) => user.email)
  const authUsers = await prisma.authUser.findMany({
    where: { email: { in: emails } },
    select: { id: true, email: true, updatedAt: true, createdAt: true },
  })

  const sessions = await prisma.authSession.findMany({
    where: { userId: { in: authUsers.map((auth) => auth.id) } },
    orderBy: { updatedAt: "desc" },
    select: { userId: true, updatedAt: true },
  })

  const sessionByUserId = new Map<string, Date>()
  for (const sessionRow of sessions) {
    if (!sessionByUserId.has(sessionRow.userId)) {
      sessionByUserId.set(sessionRow.userId, sessionRow.updatedAt)
    }
  }

  const authByEmail = new Map<string, { id: string; updatedAt: Date; createdAt: Date }>()
  for (const authUser of authUsers) {
    authByEmail.set(authUser.email.toLowerCase(), {
      id: authUser.id,
      updatedAt: authUser.updatedAt,
      createdAt: authUser.createdAt,
    })
  }

  const initialClients: AdminClient[] = users.map((user) => {
    const auth = authByEmail.get(user.email.toLowerCase())
    const lastSeenAt = auth ? sessionByUserId.get(auth.id) ?? auth.updatedAt : null
    const normalizedRole = user.role === "MANAGER" ? "MANAGER" : "COLLABORATOR"
    return {
      id: user.id,
      email: user.email,
      name: user.name ?? user.email,
      role: normalizedRole,
      companyId: user.companyId ?? null,
      companyName: user.company?.name ?? null,
      tenantId: user.tenantId,
      createdAt: user.createdAt.toISOString(),
      updatedAt: user.updatedAt.toISOString(),
      authUserId: auth?.id ?? null,
      lastSeenAt: lastSeenAt ? lastSeenAt.toISOString() : null,
    }
  })

  return (
    <AppShell
      header={<SiteHeader title="Clientes" lead="Gerencie colaboradores e gestores vinculados às empresas." />}
    >
      <div className="mx-auto w-full max-w-7xl px-4 pb-12 lg:px-8">
        <AdminClientsManager initialClients={initialClients} />
      </div>
    </AppShell>
  )
}
