import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { UsersTable, type UserRow } from '@/components/console/users-table'
import { PageHeader, Panel, PanelBody, StatCard } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { prisma } from '@/lib/db'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'

export const metadata: Metadata = { title: 'Users' }
export const dynamic = 'force-dynamic'

export default async function UsersPage() {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()

  if (!user?.permissions.has('users.read')) return <PermissionGate />

  const [users, roles] = await Promise.all([
    prisma.user.findMany({
      orderBy: { employeeId: 'asc' },
      include: { roles: { include: { role: { select: { key: true } } } } },
    }),
    prisma.role.findMany({
      orderBy: { level: 'desc' },
      select: { key: true, name: true, nameAr: true },
    }),
  ])

  const rows: UserRow[] = users.map((record) => ({
    id: record.id,
    email: record.email,
    name: record.name,
    nameAr: record.nameAr,
    employeeId: record.employeeId,
    department: record.department,
    departmentAr: record.departmentAr,
    roleKey: record.roles[0]?.role.key ?? 'viewer',
    isActive: record.isActive,
    lastLoginAt: record.lastLoginAt?.getTime() ?? null,
  }))

  const active = rows.filter((row) => row.isActive).length

  return (
    <>
      <PageHeader title={t('users.title')} subtitle={t('users.subtitle')} />

      <div className="grid gap-3 sm:grid-cols-3">
        <StatCard label={t('users.title')} value={formatNumber(locale, rows.length)} />
        <StatCard label={t('users.active')} value={formatNumber(locale, active)} state="normal" />
        <StatCard label={t('roles.title')} value={formatNumber(locale, roles.length)} />
      </div>

      <Panel className="mt-6">
        <PanelBody>
          <UsersTable
            rows={rows}
            roles={roles}
            canManage={user.permissions.has('users.manage')}
            currentUserId={user.id}
          />
        </PanelBody>
      </Panel>
    </>
  )
}
