import { Search } from 'lucide-react';
import type { Prisma } from '@prisma/client';
import { prisma } from '@/lib/prisma';
import { requireRole } from '@/lib/auth/dal';
import { ROLES, type Role } from '@/lib/auth/roles';
import { getMessages } from '@/i18n/server';
import { ShellPage } from '@/components/layout/DashboardPage';
import { UserRow } from '@/components/admin/UserRow';
import { cn } from '@/lib/cn';

const PAGE_SIZE = 100;

export default async function UsersPage({ searchParams }: PageProps<'/admin/pengguna'>) {
  const me = await requireRole(['SUPER_ADMIN'], '/admin/pengguna');
  const all = await getMessages();
  const t = all.admin.users;
  const sp = await searchParams;
  const q = typeof sp.q === 'string' ? sp.q.trim().slice(0, 80) : '';
  const role = ROLES.includes(sp.peran as Role) ? (sp.peran as Role) : undefined;

  const where: Prisma.UserWhereInput = {
    ...(role && { role }),
    ...(q && { OR: [{ name: { contains: q } }, { email: { contains: q } }] }),
  };
  const [users, counts] = await Promise.all([
    prisma.user.findMany({
      where,
      orderBy: [{ role: 'asc' }, { createdAt: 'desc' }],
      take: PAGE_SIZE,
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        isActive: true,
        lastLoginAt: true,
        _count: { select: { reports: true } },
      },
    }),
    prisma.user.groupBy({ by: ['role'], _count: { _all: true } }),
  ]);
  const countFor = (r: Role) => counts.find((c) => c.role === r)?._count._all ?? 0;
  const total = counts.reduce((n, c) => n + c._count._all, 0);

  const filterHref = (r?: Role) => {
    const params = new URLSearchParams();
    if (q) params.set('q', q);
    if (r) params.set('peran', r);
    const s = params.toString();
    return s ? `/admin/pengguna?${s}` : '/admin/pengguna';
  };

  return (
    <ShellPage>
      <p className="eyebrow text-subtle">Super Admin</p>
      <h1 className="mt-4 text-[32px] leading-tight font-semibold tracking-[-0.02em] text-ink">{t.title}</h1>
      <p className="mt-2 max-w-lg text-[15px] text-muted">
        {t.text}
      </p>

      <div className="mt-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <nav aria-label={t.filter} className="no-scrollbar -mx-1 flex gap-1 overflow-x-auto">
          {[undefined, ...ROLES].map((r) => (
            <a
              key={r ?? 'all'}
              href={filterHref(r)}
              aria-current={role === r ? 'page' : undefined}
              className={cn(
                'rounded-full px-3.5 py-1.5 text-[13px] font-medium whitespace-nowrap transition-colors',
                role === r ? 'bg-ink text-white' : 'text-muted hover:text-ink',
              )}
            >
              {r ? all.layout.roles[r] : t.all} <span className="opacity-60 tabular-nums">{r ? countFor(r) : total}</span>
            </a>
          ))}
        </nav>

        <form role="search" className="relative sm:w-72">
          {role && <input type="hidden" name="peran" value={role} />}
          <Search className="pointer-events-none absolute top-1/2 left-4 size-4 -translate-y-1/2 text-subtle" aria-hidden />
          <label htmlFor="q" className="sr-only">
            {t.search}
          </label>
          <input
            id="q"
            name="q"
            type="search"
            defaultValue={q}
            placeholder={t.searchPlaceholder}
            className="h-10 w-full rounded-full bg-surface pr-4 pl-10 text-[13px] text-ink ring-1 ring-line placeholder:text-subtle focus:ring-2 focus:ring-ink/70 focus:outline-none"
          />
        </form>
      </div>

      {users.length === 0 ? (
        <p className="mt-6 rounded-card bg-surface px-6 py-12 text-center text-sm text-muted shadow-card ring-1 ring-line/70">
          {t.none}
        </p>
      ) : (
        <ul className="mt-6 divide-y divide-line overflow-hidden rounded-card bg-surface shadow-card ring-1 ring-line/70">
          {users.map((u) => (
            <UserRow
              key={u.id}
              isSelf={u.id === me.id}
              user={{
                id: u.id,
                name: u.name,
                email: u.email,
                role: u.role,
                isActive: u.isActive,
                reports: u._count.reports,
                lastLoginAt: u.lastLoginAt?.toISOString() ?? null,
              }}
            />
          ))}
        </ul>
      )}
      {users.length === PAGE_SIZE && (
        <p className="mt-4 text-center text-[13px] text-muted">
          {t.capped(PAGE_SIZE)}
        </p>
      )}
    </ShellPage>
  );
}
