import { DashboardShell } from '../../../../components/dashboard-shell';
import { WhatsappSettingsForm } from '../../../../components/whatsapp-settings-form';
import { requireAuthToken } from '../../../../lib/auth';
import { fetchWhatsappSettings } from '../../../../lib/api';
import { getLocale } from '../../../../lib/i18n';

const whatsappLabels = {
  en: {
    settings: 'Settings',
    title: 'WhatsApp API Setting',
    description: 'This page only shows parameters currently supported by the backend: provider, webhook URL, verify token, shared secret/app secret status, connection status, and subscriptions.',
    enabled: 'Enabled',
    disabled: 'Disabled',
    integrationSwitch: 'Integration runtime switch',
    sharedSecretReady: 'Shared secret ready',
    sharedSecretMissing: 'Shared secret missing',
    sharedSecretCopy: 'Generic provider verification',
    metaSignatureReady: 'Meta signature ready',
    metaSignatureInactive: 'Meta signature inactive',
    metaSignatureCopy: 'Meta-specific signature validation',
    accessTokenReady: 'Access token ready',
    accessTokenMissing: 'Access token missing',
    accessTokenCopy: 'Required for outbound message send from Conversations',
    webhookUrlCopy: 'Current webhook destination URL',
    activeSubscriptions: 'active subscriptions',
    noSubscriptions: 'No subscriptions enabled',
    parameterMatchTitle: 'Parameter Match Check',
    parameterMatchCopy: 'Supported by backend: provider, webhookUrl, verifyToken, sharedSecret, appSecret, accessToken, phoneNumberId, isEnabled, subscriptions, and test webhook.',
    parameterMissingCopy: 'Not available yet in backend: sender pool count, latency metrics, and delivery success analytics for this settings page.',
    secretNoteTitle: 'Secret Visibility Note',
    secretNoteCopy: 'The backend does not return original secret values. The edit form can replace secrets, but cannot read them back.',
    configuredNoteCopy: 'Configured status means the secret exists in the backend, while the actual value remains hidden.',
    devSecretNoteCopy: 'Development mode is active, so sensitive values are displayed to help verify local configuration. Production will hide them again.',
    provider: 'Provider',
    verifyToken: 'Verify Token',
    signingSecret: 'Signing Secret',
    signingSecretPlaceholder: 'Leave blank to keep current secret',
    metaAppSecret: 'Meta App Secret',
    metaAppSecretPlaceholder: 'Leave blank to keep current app secret',
    metaAccessToken: 'Meta Access Token',
    metaAccessTokenPlaceholder: 'Leave blank to keep current access token',
    metaPhoneNumberId: 'Meta Phone Number ID',
    phonePlaceholder: 'e.g. 123456789012345',
    enableIntegration: 'Enable WhatsApp integration',
    enableIntegrationCopy: 'Master switch for webhook verification and processing flow.',
    eventSubscriptions: 'Event Subscriptions',
    eventSubscriptionsCopy: 'Select which normalized webhook events should be processed by the backend worker.',
    saving: 'Saving...',
    saveChanges: 'Save Changes',
    settingsUpdated: 'Settings updated.',
    testProvider: 'Test Provider',
    testSenderPhone: 'Test Sender Phone',
    testCopy: 'Test payload will create a message.inbound event, so make sure that subscription is enabled if you want the worker to process it.',
    queueing: 'Queueing...',
    sendTestPayload: 'Send Test Payload',
    testQueued: 'Test webhook queued.',
  },
  id: {
    settings: 'Pengaturan',
    title: 'Pengaturan API WhatsApp',
    description: 'Halaman ini hanya menampilkan parameter yang didukung backend saat ini: provider, URL webhook, verify token, status shared secret/app secret, status koneksi, dan subscription.',
    enabled: 'Aktif',
    disabled: 'Nonaktif',
    integrationSwitch: 'Switch runtime integrasi',
    sharedSecretReady: 'Shared secret siap',
    sharedSecretMissing: 'Shared secret belum ada',
    sharedSecretCopy: 'Verifikasi provider generik',
    metaSignatureReady: 'Signature Meta siap',
    metaSignatureInactive: 'Signature Meta belum aktif',
    metaSignatureCopy: 'Validasi signature khusus Meta',
    accessTokenReady: 'Access token siap',
    accessTokenMissing: 'Access token belum ada',
    accessTokenCopy: 'Diperlukan untuk pengiriman pesan keluar dari Percakapan',
    webhookUrlCopy: 'URL tujuan webhook saat ini',
    activeSubscriptions: 'subscription aktif',
    noSubscriptions: 'Belum ada subscription aktif',
    parameterMatchTitle: 'Pemeriksaan Parameter',
    parameterMatchCopy: 'Didukung backend: provider, webhookUrl, verifyToken, sharedSecret, appSecret, accessToken, phoneNumberId, isEnabled, subscriptions, dan test webhook.',
    parameterMissingCopy: 'Belum tersedia di backend: sender pool count, latency metrics, dan analytics keberhasilan pengiriman khusus halaman settings ini.',
    secretNoteTitle: 'Catatan Visibilitas Secret',
    secretNoteCopy: 'Backend tidak mengembalikan nilai secret asli. Form edit bisa mengganti secret, tetapi tidak bisa membaca ulang nilainya.',
    configuredNoteCopy: 'Status configured berarti secret sudah ada di backend, tetapi nilai aslinya tetap disembunyikan.',
    devSecretNoteCopy: 'Mode development aktif, jadi nilai sensitif ditampilkan untuk membantu verifikasi konfigurasi lokal. Production akan menyembunyikannya kembali.',
    provider: 'Provider',
    verifyToken: 'Verify Token',
    signingSecret: 'Signing Secret',
    signingSecretPlaceholder: 'Kosongkan untuk mempertahankan secret saat ini',
    metaAppSecret: 'Meta App Secret',
    metaAppSecretPlaceholder: 'Kosongkan untuk mempertahankan app secret saat ini',
    metaAccessToken: 'Meta Access Token',
    metaAccessTokenPlaceholder: 'Kosongkan untuk mempertahankan access token saat ini',
    metaPhoneNumberId: 'Meta Phone Number ID',
    phonePlaceholder: 'contoh 123456789012345',
    enableIntegration: 'Aktifkan integrasi WhatsApp',
    enableIntegrationCopy: 'Switch utama untuk verifikasi webhook dan alur pemrosesan.',
    eventSubscriptions: 'Subscription Event',
    eventSubscriptionsCopy: 'Pilih event webhook normalisasi yang harus diproses backend worker.',
    saving: 'Menyimpan...',
    saveChanges: 'Simpan Perubahan',
    settingsUpdated: 'Pengaturan berhasil diperbarui.',
    testProvider: 'Provider Test',
    testSenderPhone: 'Nomor Pengirim Test',
    testCopy: 'Payload test akan membuat event message.inbound, jadi pastikan subscription tersebut aktif jika ingin worker memprosesnya.',
    queueing: 'Mengantrekan...',
    sendTestPayload: 'Kirim Payload Test',
    testQueued: 'Webhook test masuk antrean.',
  },
} as const;

export default async function WhatsappApiSettingsPage() {
  const token = await requireAuthToken();
  const locale = await getLocale();
  const labels = whatsappLabels[locale];
  const settings = await fetchWhatsappSettings(token);
  const activeSubscriptionLabels = settings.availableSubscriptions
    .filter((item) => settings.subscriptions.includes(item.key))
    .map((item) => item.label)
    .join(', ');

  return (
    <DashboardShell currentPath="/dashboard/settings/whatsapp-api" 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="whatsapp-settings-grid">
        <WhatsappSettingsForm
          labels={labels}
          initialValues={{
            provider: settings.provider,
            verifyToken: settings.verifyToken,
            sharedSecret: settings.sharedSecret,
            appSecret: settings.appSecret,
            accessToken: settings.accessToken,
            showSensitiveValues: settings.showSensitiveValues,
            phoneNumberId: settings.phoneNumberId,
            isEnabled: settings.isEnabled,
            subscriptions: settings.subscriptions,
            availableSubscriptions: settings.availableSubscriptions,
          }}
        />

        <article className="surface-card whatsapp-status-card">
          <div className="metric-stack">
            <div>
              <strong>{settings.isEnabled ? labels.enabled : labels.disabled}</strong>
              <span>{labels.integrationSwitch}</span>
            </div>
            <div>
              <strong>{settings.hasSharedSecret ? labels.sharedSecretReady : labels.sharedSecretMissing}</strong>
              <span>{labels.sharedSecretCopy}</span>
            </div>
            <div>
              <strong>{settings.hasAppSecret ? labels.metaSignatureReady : labels.metaSignatureInactive}</strong>
              <span>{labels.metaSignatureCopy}</span>
            </div>
            <div>
              <strong>{settings.hasAccessToken ? labels.accessTokenReady : labels.accessTokenMissing}</strong>
              <span>{labels.accessTokenCopy}</span>
            </div>
            <div>
              <strong>{settings.webhookUrl}</strong>
              <span>{labels.webhookUrlCopy}</span>
            </div>
            <div>
              <strong>{settings.subscriptions.length} {labels.activeSubscriptions}</strong>
              <span>{activeSubscriptionLabels || labels.noSubscriptions}</span>
            </div>
          </div>
        </article>
      </section>

      <section className="whatsapp-notes-grid">
        <article className="surface-card">
          <h2>{labels.parameterMatchTitle}</h2>
          <p>{labels.parameterMatchCopy}</p>
          <p>{labels.parameterMissingCopy}</p>
        </article>
        <article className="surface-card">
          <h2>{labels.secretNoteTitle}</h2>
          <p>{settings.showSensitiveValues ? labels.devSecretNoteCopy : labels.secretNoteCopy}</p>
          <p>{labels.configuredNoteCopy}</p>
        </article>
      </section>
    </DashboardShell>
  );
}
