import { DashboardShell } from '../../../../components/dashboard-shell';
import { SecuritySessionCard } from '../../../../components/security-session-card';
import { TwoFactorSettingsCard } from '../../../../components/two-factor-settings-card';
import { fetchCurrentSession, fetchTwoFactorStatus } from '../../../../lib/api';
import { requireAuthToken } from '../../../../lib/auth';
import { getLocale } from '../../../../lib/i18n';

const securityLabels = {
  en: {
    title: 'Security',
    settings: 'Settings',
    description: 'Harden production authentication with TOTP, backup recovery codes, and safer admin sessions.',
    jwtAuth: 'JWT Auth',
    jwtAuthCopy: 'Login and protected routes are active',
    webhookVerification: 'Webhook Verification',
    webhookVerificationCopy: 'Verify token, shared secret, and Meta signature are available',
    queueRetry: 'Queue Retry',
    queueRetryCopy: 'Webhook jobs can be retried and recorded in logs',
    twoFactorTitle: 'Two-Factor Authentication',
    twoFactorCopy: 'Protect admin login with a time-based code from Google Authenticator, 1Password, or another TOTP app.',
    status: 'Status',
    enabled: 'Enabled',
    disabled: 'Disabled',
    confirmedAt: 'Confirmed At',
    notEnabled: 'Not enabled',
    backupCodesRemaining: 'Backup Codes Remaining',
    preparing: 'Preparing...',
    startSetup: 'Start 2FA Setup',
    recoveryCodesCopy: 'Save these codes now. Each code can only be used once for emergency login.',
    manualEntryKey: 'Manual Entry Key',
    otpauthUrl: 'OTPAuth URL',
    verificationCode: 'Verification Code',
    verifying: 'Verifying...',
    confirmEnable: 'Confirm and Enable 2FA',
    backupRecoveryCodes: 'Backup Recovery Codes',
    regenerateCodeLabel: 'Current 2FA Code to Regenerate Backup Codes',
    regenerating: 'Regenerating...',
    regenerateCodes: 'Regenerate Backup Codes',
    newBackupRecoveryCodes: 'New Backup Recovery Codes',
    current2faCode: 'Current 2FA Code',
    disabling: 'Disabling...',
    disable2fa: 'Disable 2FA',
    scanQrAlt: 'Scan this QR code in your authenticator app',
    sessionEyebrow: 'Session',
    sessionTitle: 'Current Admin Session',
    sessionCopy: 'BizOne currently enforces a single active admin session. A fresh login rotates tokens and replaces the previous session.',
    sessionBadge: 'Single Session Policy',
    signedInAs: 'Signed in as',
    accessIssued: 'Access token issued',
    accessExpires: 'Access token expires',
    refreshExpires: 'Refresh token expires',
    currentIp: 'Current IP',
    lastLogin: 'Last successful login',
    unavailable: 'Unavailable',
    notAvailable: 'Not available',
    signOutRevoke: 'Sign Out and Revoke Session',
    revokeCopy: 'Use this if you suspect account exposure. Signing out here invalidates the active refresh token and forces a fresh login.',
  },
  id: {
    title: 'Keamanan',
    settings: 'Pengaturan',
    description: 'Perkuat autentikasi produksi dengan TOTP, kode pemulihan cadangan, dan sesi admin yang lebih aman.',
    jwtAuth: 'JWT Auth',
    jwtAuthCopy: 'Login dan protected routes aktif',
    webhookVerification: 'Verifikasi Webhook',
    webhookVerificationCopy: 'Verify token, shared secret, dan Meta signature tersedia',
    queueRetry: 'Retry Queue',
    queueRetryCopy: 'Job webhook dapat di-retry dan tercatat di logs',
    twoFactorTitle: 'Autentikasi Dua Faktor',
    twoFactorCopy: 'Lindungi login admin dengan kode berbasis waktu dari Google Authenticator, 1Password, atau aplikasi TOTP lain.',
    status: 'Status',
    enabled: 'Aktif',
    disabled: 'Nonaktif',
    confirmedAt: 'Dikonfirmasi Pada',
    notEnabled: 'Belum aktif',
    backupCodesRemaining: 'Sisa Kode Cadangan',
    preparing: 'Menyiapkan...',
    startSetup: 'Mulai Setup 2FA',
    recoveryCodesCopy: 'Simpan kode ini sekarang. Setiap kode hanya bisa dipakai sekali untuk login darurat.',
    manualEntryKey: 'Kunci Manual',
    otpauthUrl: 'URL OTPAuth',
    verificationCode: 'Kode Verifikasi',
    verifying: 'Memverifikasi...',
    confirmEnable: 'Konfirmasi dan Aktifkan 2FA',
    backupRecoveryCodes: 'Kode Pemulihan Cadangan',
    regenerateCodeLabel: 'Kode 2FA Saat Ini untuk Membuat Ulang Kode Cadangan',
    regenerating: 'Membuat ulang...',
    regenerateCodes: 'Buat Ulang Kode Cadangan',
    newBackupRecoveryCodes: 'Kode Pemulihan Cadangan Baru',
    current2faCode: 'Kode 2FA Saat Ini',
    disabling: 'Menonaktifkan...',
    disable2fa: 'Nonaktifkan 2FA',
    scanQrAlt: 'Pindai kode QR ini di aplikasi authenticator Anda',
    sessionEyebrow: 'Sesi',
    sessionTitle: 'Sesi Admin Saat Ini',
    sessionCopy: 'BizOne saat ini menerapkan satu sesi admin aktif. Login baru akan memutar token dan mengganti sesi sebelumnya.',
    sessionBadge: 'Kebijakan Satu Sesi',
    signedInAs: 'Login sebagai',
    accessIssued: 'Access token diterbitkan',
    accessExpires: 'Access token kedaluwarsa',
    refreshExpires: 'Refresh token kedaluwarsa',
    currentIp: 'IP Saat Ini',
    lastLogin: 'Login berhasil terakhir',
    unavailable: 'Tidak tersedia',
    notAvailable: 'Tidak tersedia',
    signOutRevoke: 'Keluar dan Cabut Sesi',
    revokeCopy: 'Gunakan ini jika Anda mencurigai akun terekspos. Keluar dari sini akan membatalkan refresh token aktif dan memaksa login ulang.',
  },
} as const;

export default async function SecuritySettingsPage() {
  const token = await requireAuthToken();
  const locale = await getLocale();
  const labels = securityLabels[locale];
  const [status, session] = await Promise.all([fetchTwoFactorStatus(token), fetchCurrentSession(token)]);

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

      <section className="dashboard-two-column">
        <article className="surface-card">
          <div className="metric-stack">
            <div>
              <strong>{labels.jwtAuth}</strong>
              <span>{labels.jwtAuthCopy}</span>
            </div>
            <div>
              <strong>{labels.webhookVerification}</strong>
              <span>{labels.webhookVerificationCopy}</span>
            </div>
            <div>
              <strong>{labels.queueRetry}</strong>
              <span>{labels.queueRetryCopy}</span>
            </div>
          </div>
        </article>

        <TwoFactorSettingsCard status={status} labels={labels} />
      </section>

      <section className="dashboard-two-column-bottom">
        <SecuritySessionCard session={session} labels={labels} />
      </section>
    </DashboardShell>
  );
}
