import { DashboardShell } from '../../../components/dashboard-shell';
import { UsersManagementBoard } from '../../../components/users-management-board';
import { requireAuthToken } from '../../../lib/auth';
import { fetchRoles, fetchUsers } from '../../../lib/api';
import { getLocale } from '../../../lib/i18n';

const userLabels = {
  en: {
    users: 'Users', title: 'User Management', description: 'Manage team access levels, roles, and security permissions.', createUser: 'Create User', totalUsers: 'Total Users', directoryAccounts: 'Directory accounts', pendingInvites: 'Pending Invites', awaitingResponse: 'Awaiting response', activeSessions: 'Active Sessions', currentActivity: 'Current real-time activity', settingsTeam: 'Settings / Team Management', addMember: 'Add New Team Member', inviteCopy: 'Invite a new administrator or support agent to your business dashboard.', profileInformation: 'Profile Information', fullName: 'Full Name', fullNamePlaceholder: 'e.g. Sarah Jenkins', emailAddress: 'Email Address', phoneOptional: 'Phone Number (Optional)', phonePlaceholder: '+1 (555) 000-0000', roleSelection: 'Role Selection', cancel: 'Cancel', creating: 'Creating...', summary: 'Summary', role: 'Role', status: 'Status', supportAgent: 'Support Agent', draftInvitation: 'Draft Invitation', inviteSummary: 'Inviting this user will send a secure email link so they can verify their address and set their own password.', secureOnboarding: 'Secure Onboarding', secureOnboardingCopy: 'Users receive a time-limited invitation link to create their own credentials.', lastActive: 'Last Active', securityActions: 'Security Actions', sendPasswordReset: 'Send Password Reset Link', editUser: 'Edit User', updateAccess: 'Update user access and account status', updateAccessCopy: 'Change display details, role assignment, and lifecycle state without leaving the directory.', unassigned: 'Unassigned', verified: 'Verified', pendingVerification: 'Pending Verification', emailVerification: 'Email verification', lastActivity: 'Last activity', saving: 'Saving...', saveChanges: 'Save Changes', dangerZone: 'Danger Zone', dangerCopy: 'Deleting this user is not enabled yet. For now, use Suspended status to revoke access safely.', deleteUser: 'Delete User', teamMembers: 'Team Members', filter: 'Filter', export: 'Export', searchMembers: 'Search team members', searchPlaceholder: 'Search name or email...', allStatuses: 'All Statuses', allRoles: 'All Roles', reset: 'Reset', nameEmail: 'Name / Email', actions: 'Actions', resendInvite: 'Resend Invite', noUsers: 'No users matched the current filters.', showing: 'Showing', to: 'to', of: 'of', teamMembersLower: 'team members', rolePermissions: 'Role Permissions', rolePermissionsCopy: 'Quick overview of what each team member can access across the WhatsApp Business platform.', pendingInvite: 'Pending invite', never: 'Never', justNow: 'Just now', hourAgo: 'hour ago', hoursAgo: 'hours ago', dayAgo: 'day ago', daysAgo: 'days ago', active: 'Active', invited: 'Invited', inactive: 'Inactive', suspended: 'Suspended', failedLoad: 'Failed to load users', failedInvite: 'Failed to invite user', failedUpdate: 'Failed to update user', failedResend: 'Failed to resend invite', invitationSent: 'Invitation sent to', userInvitedNoEmail: 'User invited, but email was not sent. Activation link:', userUpdated: 'User updated.', invitationResent: 'Invitation resent to', inviteRefreshedNoEmail: 'Invite refreshed, but email was not sent. Activation link:', roleAdminDesc: 'Full system access, including billing, user management, and API settings.', roleEditorDesc: 'Manage broadcasts and message templates, but cannot change system settings.', roleAgentDesc: 'Limited to handling conversations, contacts, and operational response flow.', roleDefaultDesc: 'Operational access based on the assigned role matrix.'
  },
  id: {
    users: 'Pengguna', title: 'Manajemen Pengguna', description: 'Kelola level akses tim, peran, dan izin keamanan.', createUser: 'Buat Pengguna', totalUsers: 'Total Pengguna', directoryAccounts: 'Akun direktori', pendingInvites: 'Undangan Tertunda', awaitingResponse: 'Menunggu respons', activeSessions: 'Sesi Aktif', currentActivity: 'Aktivitas real-time saat ini', settingsTeam: 'Pengaturan / Manajemen Tim', addMember: 'Tambah Anggota Tim', inviteCopy: 'Undang administrator atau support agent baru ke dashboard bisnis Anda.', profileInformation: 'Informasi Profil', fullName: 'Nama Lengkap', fullNamePlaceholder: 'contoh Sarah Jenkins', emailAddress: 'Alamat Email', phoneOptional: 'Nomor Telepon (Opsional)', phonePlaceholder: '+62 812-0000-0000', roleSelection: 'Pilih Peran', cancel: 'Batal', creating: 'Membuat...', summary: 'Ringkasan', role: 'Peran', status: 'Status', supportAgent: 'Support Agent', draftInvitation: 'Draft Undangan', inviteSummary: 'Mengundang user ini akan mengirim link email aman agar mereka dapat memverifikasi alamat dan membuat password sendiri.', secureOnboarding: 'Onboarding Aman', secureOnboardingCopy: 'User menerima link undangan berbatas waktu untuk membuat kredensial sendiri.', lastActive: 'Aktif Terakhir', securityActions: 'Aksi Keamanan', sendPasswordReset: 'Kirim Link Reset Password', editUser: 'Edit Pengguna', updateAccess: 'Perbarui akses dan status akun pengguna', updateAccessCopy: 'Ubah detail tampilan, penetapan peran, dan status lifecycle tanpa meninggalkan direktori.', unassigned: 'Belum ditetapkan', verified: 'Terverifikasi', pendingVerification: 'Menunggu Verifikasi', emailVerification: 'Verifikasi email', lastActivity: 'Aktivitas terakhir', saving: 'Menyimpan...', saveChanges: 'Simpan Perubahan', dangerZone: 'Zona Berisiko', dangerCopy: 'Menghapus user belum diaktifkan. Untuk saat ini, gunakan status Suspended untuk mencabut akses dengan aman.', deleteUser: 'Hapus Pengguna', teamMembers: 'Anggota Tim', filter: 'Filter', export: 'Export', searchMembers: 'Cari anggota tim', searchPlaceholder: 'Cari nama atau email...', allStatuses: 'Semua Status', allRoles: 'Semua Peran', reset: 'Reset', nameEmail: 'Nama / Email', actions: 'Aksi', resendInvite: 'Kirim Ulang Undangan', noUsers: 'Tidak ada pengguna yang cocok dengan filter saat ini.', showing: 'Menampilkan', to: 'hingga', of: 'dari', teamMembersLower: 'anggota tim', rolePermissions: 'Izin Peran', rolePermissionsCopy: 'Ringkasan cepat akses tiap anggota tim di platform WhatsApp Business.', pendingInvite: 'Undangan tertunda', never: 'Belum pernah', justNow: 'Baru saja', hourAgo: 'jam lalu', hoursAgo: 'jam lalu', dayAgo: 'hari lalu', daysAgo: 'hari lalu', active: 'Aktif', invited: 'Diundang', inactive: 'Nonaktif', suspended: 'Ditangguhkan', failedLoad: 'Gagal memuat pengguna', failedInvite: 'Gagal mengundang pengguna', failedUpdate: 'Gagal memperbarui pengguna', failedResend: 'Gagal mengirim ulang undangan', invitationSent: 'Undangan dikirim ke', userInvitedNoEmail: 'Pengguna diundang, tetapi email tidak terkirim. Link aktivasi:', userUpdated: 'Pengguna diperbarui.', invitationResent: 'Undangan dikirim ulang ke', inviteRefreshedNoEmail: 'Undangan diperbarui, tetapi email tidak terkirim. Link aktivasi:', roleAdminDesc: 'Akses penuh sistem, termasuk billing, manajemen pengguna, dan pengaturan API.', roleEditorDesc: 'Mengelola broadcast dan template pesan, tetapi tidak dapat mengubah pengaturan sistem.', roleAgentDesc: 'Terbatas untuk menangani percakapan, kontak, dan alur respons operasional.', roleDefaultDesc: 'Akses operasional berdasarkan matriks peran yang ditetapkan.'
  },
} as const;

export default async function UsersPage() {
  const token = await requireAuthToken();
  const locale = await getLocale();
  const labels = userLabels[locale];
  const [users, roles] = await Promise.all([fetchUsers(token, { page: 1, limit: 10 }), fetchRoles(token)]);

  return (
    <DashboardShell currentPath="/dashboard/users" title={labels.title}>
      <UsersManagementBoard
        labels={labels}
        initialUsers={users.items}
        initialTotal={users.total}
        initialPage={users.page}
        initialPageSize={users.pageSize}
        initialTotalPages={users.totalPages}
        availableRoles={roles.map((role) => ({
          id: role.id,
          name: role.name,
        }))}
      />
    </DashboardShell>
  );
}
