import { redirect } from 'next/navigation';
import { getCurrentUser } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import UsersTable from '@/components/admin/UsersTable';

export const dynamic = 'force-dynamic';

export default async function AdminUsersPage() {
  const me = await getCurrentUser();
  if (!me) redirect('/auth/login');
  if (!me.isAdmin) redirect('/main/dashboard');

  const users = await prisma.user.findMany({
    select: {
      id: true,
      email: true,
      name: true,
      isAdmin: true,
      createdAt: true,
      lastLoginAt: true,
      _count: { select: { sessions: true, workouts: true } },
    },
    orderBy: { createdAt: 'asc' },
  });

  // Serialize Date -> string for the client component boundary.
  const usersForClient = users.map((u) => ({
    id: u.id,
    email: u.email,
    name: u.name,
    isAdmin: u.isAdmin,
    createdAt: u.createdAt.toISOString(),
    lastLoginAt: u.lastLoginAt ? u.lastLoginAt.toISOString() : null,
    sessionCount: u._count.sessions,
    workoutCount: u._count.workouts,
  }));

  return (
    <div className="min-h-screen bg-[#0A0A0A]">
      <div className="border-b border-zinc-800 px-4 py-4 sm:px-6">
        <div className="max-w-4xl mx-auto">
          <h1 className="text-2xl font-bold text-white">Users</h1>
          <p className="text-zinc-500 text-sm mt-1">
            Admin only. Manage accounts on this Proof of Work instance.
          </p>
        </div>
      </div>

      <div className="max-w-4xl mx-auto px-4 py-6 sm:px-6">
        <UsersTable users={usersForClient} currentUserId={me.id} />
      </div>
    </div>
  );
}
