import { listUsers, listTenants } from '@/db/admin-queries';
import { toggleUsuario } from './actions';
import { CrearReformistaForm } from './CrearReformistaForm';

export const dynamic = 'force-dynamic';

export default async function UsuariosPage() {
  const [users, tenants] = await Promise.all([listUsers(), listTenants()]);
  const empresaDe = new Map(tenants.map((t) => [t.id, t.nombreEmpresa]));
  return (
    <div className="flex flex-col gap-8">
      <h1 className="text-2xl font-black tracking-tight text-black">Usuarios</h1>
      <CrearReformistaForm />
      <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead><tr className="border-b border-gray-200 text-left text-xs uppercase tracking-wide text-gray-400">
            <th className="px-4 py-3">Email</th><th className="px-4 py-3">Rol</th>
            <th className="px-4 py-3">Empresa</th><th className="px-4 py-3">Estado</th><th className="px-4 py-3"></th>
          </tr></thead>
          <tbody>
            {users.map((u) => (
              <tr key={u.id} className="border-b border-gray-100 last:border-0">
                <td className="px-4 py-3 font-medium text-black">{u.email}</td>
                <td className="px-4 py-3 text-gray-600">{u.role}</td>
                <td className="px-4 py-3 text-gray-600">{u.tenantId ? empresaDe.get(u.tenantId) ?? '—' : '—'}</td>
                <td className="px-4 py-3 text-gray-600">{u.status}</td>
                <td className="px-4 py-3 text-right">
                  {u.role !== 'admin' && (
                    <form action={toggleUsuario}>
                      <input type="hidden" name="userId" value={u.id} />
                      <input type="hidden" name="next" value={u.status === 'activo' ? 'deshabilitado' : 'activo'} />
                      <button type="submit" className="text-xs font-medium text-gray-500 hover:text-black">
                        {u.status === 'activo' ? 'Deshabilitar' : 'Habilitar'}
                      </button>
                    </form>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
