import { DashboardShell } from '../../../components/dashboard-shell';
import { RolesPermissionsBoard } from '../../../components/roles-permissions-board';
import { requireAuthToken } from '../../../lib/auth';
import { fetchAuditTrail, fetchRoles } from '../../../lib/api';
import { getLocale } from '../../../lib/i18n';

const rolesLabels = {
  en: {
    accessControl: 'Access Control',
    title: 'Roles & Permissions',
    description: 'Configure access levels and granular permissions for campaigns, analytics, settings, and audit visibility.',
    minuteAgo: 'min ago',
    hourAgo: 'hour ago',
    hoursAgo: 'hours ago',
    dayAgo: 'day ago',
    daysAgo: 'days ago',
    view: 'View',
    createEdit: 'Create/Edit',
    delete: 'Delete',
    manageAll: 'Manage All',
    editingNow: 'Editing Now',
    roles: 'Roles',
    noRoles: 'No roles available',
    noRolesCopy: 'Create the first role to start defining access permissions.',
    createRole: 'Create Role',
    hideRoleForm: 'Hide Role Form',
    createNewRole: 'Create New Role',
    newRole: 'New Role',
    createProfile: 'Create a custom access profile',
    createProfileCopy: 'Define a clear role name and a short summary so your team can understand the scope immediately.',
    roleName: 'Role name',
    roleNamePlaceholder: 'Reporting Only',
    roleNameHelp: 'Use a short operational name like Viewer, QA Reviewer, or Billing Admin.',
    summary: 'Summary',
    summaryPlaceholder: 'Read-only access to analytics, campaign stats, and webhook summaries.',
    summaryHelp: 'Describe what this role can access and the boundaries it should keep.',
    cancel: 'Cancel',
    saveRole: 'Save Role',
    custom: 'Custom',
    customSummary: 'Custom role for a focused operational access policy.',
    roleNameRequired: 'Role name is required.',
    failedSave: 'Failed to save role',
    failedCreate: 'Failed to create role',
    changesDiscarded: 'Changes discarded.',
    permissionSavedPrefix: 'Permission matrix for',
    permissionSavedSuffix: 'saved.',
    roleCreatedPrefix: 'Role',
    roleCreatedSuffix: 'created and opened for editing.',
    usersAssigned: 'users assigned',
    editing: 'Editing',
    edit: 'Edit',
    permissionMatrix: 'Permission Matrix',
    viewing: 'Viewing',
    toggleCopy: 'Toggle permissions below, then save the matrix to persist your changes.',
    readonlyCopy: 'This matrix is read-only until you click Edit on the selected role card.',
    discard: 'Discard',
    saveChanges: 'Save Changes',
    editRole: 'Edit Role',
    modulePermission: 'Module / Permission',
    on: 'On',
    off: 'Off',
    auditTrail: 'Audit Trail',
    recentChanges: 'Recent Changes',
    viewAll: 'View All',
    noRoleChanges: 'No role changes yet',
    noRoleChangesCopy: 'Role create and edit actions will appear here once they are recorded.',
    securityGuidance: 'Security Guidance',
    needHelp: 'Need help?',
    helpCopy: 'Learn how to set granular access boundaries for enterprise teams with higher security requirements.',
    documentation: 'Documentation',
    permission_campaigns_label: 'Manage Campaigns',
    permission_campaigns_description: 'Broadcasts and outbound campaign controls.',
    permission_analytics_label: 'View Analytics',
    permission_analytics_description: 'KPI, trends, and performance dashboards.',
    permission_settings_label: 'Edit Settings',
    permission_settings_description: 'Providers, secrets, and environment-facing settings.',
    permission_billing_label: 'Billing & Invoices',
    permission_billing_description: 'Plan usage, invoices, and billing visibility.',
    permission_users_label: 'User Management',
    permission_users_description: 'Team invitations, account status, and access administration.',
    permission_contacts_label: 'Contacts',
    permission_contacts_description: 'Customer directory and segmentation access.',
    permission_templates_label: 'Templates',
    permission_templates_description: 'Message templates and approval workflow access.',
    permission_audit_label: 'Audit Trail',
    permission_audit_description: 'Administrative activity and security visibility.',
  },
  id: {
    accessControl: 'Kontrol Akses',
    title: 'Peran & Izin',
    description: 'Atur level akses dan izin granular untuk kampanye, analytics, pengaturan, dan visibilitas audit.',
    minuteAgo: 'menit lalu',
    hourAgo: 'jam lalu',
    hoursAgo: 'jam lalu',
    dayAgo: 'hari lalu',
    daysAgo: 'hari lalu',
    view: 'Lihat',
    createEdit: 'Buat/Edit',
    delete: 'Hapus',
    manageAll: 'Kelola Semua',
    editingNow: 'Sedang Diedit',
    roles: 'Peran',
    noRoles: 'Belum ada peran',
    noRolesCopy: 'Buat peran pertama untuk mulai menentukan izin akses.',
    createRole: 'Buat Peran',
    hideRoleForm: 'Tutup Form Peran',
    createNewRole: 'Buat Peran Baru',
    newRole: 'Peran Baru',
    createProfile: 'Buat profil akses khusus',
    createProfileCopy: 'Tentukan nama peran dan ringkasan singkat agar tim langsung memahami cakupannya.',
    roleName: 'Nama peran',
    roleNamePlaceholder: 'Hanya Laporan',
    roleNameHelp: 'Gunakan nama operasional singkat seperti Viewer, QA Reviewer, atau Billing Admin.',
    summary: 'Ringkasan',
    summaryPlaceholder: 'Akses baca saja ke analytics, statistik kampanye, dan ringkasan webhook.',
    summaryHelp: 'Jelaskan akses peran ini dan batasan yang perlu dijaga.',
    cancel: 'Batal',
    saveRole: 'Simpan Peran',
    custom: 'Kustom',
    customSummary: 'Peran kustom untuk kebijakan akses operasional tertentu.',
    roleNameRequired: 'Nama peran wajib diisi.',
    failedSave: 'Gagal menyimpan peran',
    failedCreate: 'Gagal membuat peran',
    changesDiscarded: 'Perubahan dibatalkan.',
    permissionSavedPrefix: 'Matriks izin untuk',
    permissionSavedSuffix: 'berhasil disimpan.',
    roleCreatedPrefix: 'Peran',
    roleCreatedSuffix: 'dibuat dan dibuka untuk diedit.',
    usersAssigned: 'pengguna ditetapkan',
    editing: 'Mengedit',
    edit: 'Edit',
    permissionMatrix: 'Matriks Izin',
    viewing: 'Melihat',
    toggleCopy: 'Ubah izin di bawah, lalu simpan matriks untuk menyimpan perubahan.',
    readonlyCopy: 'Matriks ini hanya baca sampai Anda klik Edit pada card peran yang dipilih.',
    discard: 'Batalkan',
    saveChanges: 'Simpan Perubahan',
    editRole: 'Edit Peran',
    modulePermission: 'Modul / Izin',
    on: 'Aktif',
    off: 'Nonaktif',
    auditTrail: 'Audit Trail',
    recentChanges: 'Perubahan Terbaru',
    viewAll: 'Lihat Semua',
    noRoleChanges: 'Belum ada perubahan peran',
    noRoleChangesCopy: 'Aksi membuat dan mengedit peran akan muncul di sini setelah tercatat.',
    securityGuidance: 'Panduan Keamanan',
    needHelp: 'Butuh bantuan?',
    helpCopy: 'Pelajari cara menetapkan batas akses granular untuk tim enterprise dengan kebutuhan keamanan lebih tinggi.',
    documentation: 'Dokumentasi',
    permission_campaigns_label: 'Kelola Kampanye',
    permission_campaigns_description: 'Kontrol broadcast dan kampanye keluar.',
    permission_analytics_label: 'Lihat Analytics',
    permission_analytics_description: 'KPI, tren, dan dashboard performa.',
    permission_settings_label: 'Edit Pengaturan',
    permission_settings_description: 'Provider, secret, dan pengaturan yang terkait environment.',
    permission_billing_label: 'Billing & Invoice',
    permission_billing_description: 'Visibilitas paket, pemakaian, invoice, dan billing.',
    permission_users_label: 'Manajemen Pengguna',
    permission_users_description: 'Undangan tim, status akun, dan administrasi akses.',
    permission_contacts_label: 'Kontak',
    permission_contacts_description: 'Akses direktori pelanggan dan segmentasi.',
    permission_templates_label: 'Template',
    permission_templates_description: 'Akses template pesan dan alur approval.',
    permission_audit_label: 'Audit Trail',
    permission_audit_description: 'Visibilitas aktivitas admin dan keamanan.',
  },
} as const;

function formatRelativeTime(value: string, labels: (typeof rolesLabels)[keyof typeof rolesLabels]) {
  const diff = Date.now() - new Date(value).getTime();
  const minutes = Math.max(1, Math.floor(diff / 60000));

  if (minutes < 60) {
    return `${minutes} ${labels.minuteAgo}`;
  }

  const hours = Math.floor(minutes / 60);
  if (hours < 24) {
    return `${hours} ${hours === 1 ? labels.hourAgo : labels.hoursAgo}`;
  }

  const days = Math.floor(hours / 24);
  return `${days} ${days === 1 ? labels.dayAgo : labels.daysAgo}`;
}

function iconForAction(actionType: string) {
  if (actionType.includes('Created')) return 'add_circle';
  if (actionType.includes('Updated')) return 'person_edit';
  if (actionType.includes('Deleted')) return 'delete';
  return 'history';
}

export default async function RolesPage() {
  const token = await requireAuthToken();
  const locale = await getLocale();
  const labels = rolesLabels[locale];
  const [roles, auditTrail] = await Promise.all([
    fetchRoles(token),
    fetchAuditTrail(token, { limit: 3, module: 'Access Control' }),
  ]);

  return (
    <DashboardShell currentPath="/dashboard/roles" title={labels.title}>
      <section className="page-header">
        <div>
          <p className="page-eyebrow">{labels.accessControl}</p>
          <h1 className="page-heading">{labels.title}</h1>
          <p className="page-copy">{labels.description}</p>
        </div>
      </section>

      <RolesPermissionsBoard
        labels={labels}
        initialRoles={roles.map((role) => ({
          id: role.id,
          name: role.name,
          badge: role.badge,
          tone: role.tone,
          summary: role.summary,
          usersAssigned: role.usersAssigned,
          icon: role.icon,
          permissionRows: role.permissions,
        }))}
        initialAuditHighlights={auditTrail.items.map((item) => ({
          id: item.id,
          icon: iconForAction(item.actionType),
          title: item.actionType,
          description: item.details,
          time: formatRelativeTime(item.createdAt, labels),
        }))}
      />
    </DashboardShell>
  );
}
