import type { Metadata } from "next";
import { formatDateTime } from "@/lib/format/format";
import { requirePermission } from "@/server/auth/current-user";
import { db } from "@/server/db";

export const metadata: Metadata = { title: "Usuarios" };

const PAGE_SIZE = 50;

/**
 * Usuarios — Fase 1: listado de solo lectura que valida el RBAC server-side
 * (un ADVISOR o SUPERVISOR recibe 403). El CRUD completo llega con la gestión de usuarios.
 */
export default async function AdminUsersPage() {
  await requirePermission("users.read");

  const users = await db.user.findMany({
    where: { deletedAt: null },
    orderBy: [{ isActive: "desc" }, { name: "asc" }],
    take: PAGE_SIZE,
    select: {
      id: true,
      name: true,
      email: true,
      isActive: true,
      lastLoginAt: true,
      lockedUntil: true,
      role: { select: { name: true } },
    },
  });
  const now = new Date();

  return (
    <div className="mx-auto max-w-5xl space-y-6">
      <h1 className="font-display text-2xl font-bold md:text-3xl">Usuarios</h1>
      <div className="overflow-x-auto rounded-chesco-lg border border-chesco-border bg-chesco-white">
        <table className="w-full text-left text-sm">
          <caption className="sr-only">Usuarios del panel</caption>
          <thead className="bg-chesco-soft-gray text-xs uppercase text-chesco-text-muted">
            <tr>
              <th scope="col" className="px-4 py-3">
                Nombre
              </th>
              <th scope="col" className="px-4 py-3">
                Email
              </th>
              <th scope="col" className="px-4 py-3">
                Rol
              </th>
              <th scope="col" className="px-4 py-3">
                Estado
              </th>
              <th scope="col" className="px-4 py-3">
                Último ingreso
              </th>
            </tr>
          </thead>
          <tbody>
            {users.map((user) => {
              const locked = user.lockedUntil !== null && user.lockedUntil > now;
              return (
                <tr key={user.id} className="border-t border-chesco-border">
                  <td className="px-4 py-3 font-medium">{user.name}</td>
                  <td className="px-4 py-3">{user.email}</td>
                  <td className="px-4 py-3">{user.role.name}</td>
                  <td className="px-4 py-3">
                    {!user.isActive ? "Inactivo" : locked ? "Bloqueado temporalmente" : "Activo"}
                  </td>
                  <td className="px-4 py-3 tabular-nums">
                    {user.lastLoginAt ? formatDateTime(user.lastLoginAt) : "—"}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
