import { DashboardShell } from '../../../components/dashboard-shell';
import {
  fetchAnalyticsSummary,
  fetchAuditTrail,
} from '../../../lib/api';
import { requireAuthToken } from '../../../lib/auth';
import {
  analyticsLogs as fallbackAnalyticsLogs,
  analyticsWorkerHealth as fallbackWorkerHealth,
} from '../../../lib/mock-data';
import { getLocale } from '../../../lib/i18n';

type StatusTone = 'success' | 'warning' | 'error';

function statusClassName(tone: StatusTone) {
  if (tone === 'error') return 'analytics-status-pill is-error';
  if (tone === 'warning') return 'analytics-status-pill is-warning';
  return 'analytics-status-pill is-success';
}

function payloadButtonClassName(tone: 'primary' | 'success' | 'error' | 'neutral') {
  if (tone === 'error') return 'analytics-payload-button is-error';
  if (tone === 'success') return 'analytics-payload-button is-success';
  if (tone === 'primary') return 'analytics-payload-button is-primary';
  return 'analytics-payload-button';
}

const analyticsLabels = {
  en: {
    title: 'Admin Dashboard',
    searchPlaceholder: 'Search system logs...',
    operations: 'Operations',
    heading: 'Activity Logs & Queue Monitor',
    copy: 'Real-time surveillance of system processes, background jobs, and administrative actions.',
    filterLogs: 'Filter Logs',
    exportCsv: 'Export CSV',
    queueMonitor: 'Queue Monitor',
    live: 'Live',
    fallback: 'Fallback',
    pendingJobs: 'Pending Jobs',
    processing: 'Processing',
    failed24h: 'Failed (24H)',
    workerHealth: 'Worker Health',
    load: 'Load',
    queueThroughput: 'Queue Throughput',
    throughputA: 'System is currently processing',
    throughputB: 'workload points per minute with',
    throughputC: 'verified webhook traffic.',
    technicalLogs: 'Technical Activity Logs',
    total: 'Total:',
    events: 'events',
    timestamp: 'Timestamp',
    action: 'Action',
    userService: 'User / Service',
    status: 'Status',
    payload: 'Payload',
    openPayload: 'Open payload for',
    showing: 'Showing',
    of: 'of',
    logs: 'logs',
    previousPage: 'Previous page',
    nextPage: 'Next page',
    liveTailMode: 'Live Tail Mode',
    liveTailCopyA: 'Pulling live audit trail, queue jobs, and webhook activity from the backend. Current snapshot includes',
    liveTailCopyB: 'jobs and',
    liveTailCopyC: 'webhook events.',
    launchConsole: 'Launch Debug Console',
    apiLatency: 'API Latency',
    dbConnections: 'DB Connections',
    memoryUsage: 'Memory Usage',
    degraded: 'Degraded',
    active: 'Active',
    down: 'Down',
    backendLoad: 'backend-estimated load',
    pending: 'Pending',
    rejected: 'Rejected',
    approved: 'Approved',
    success: 'Success',
  },
  id: {
    title: 'Dashboard Admin',
    searchPlaceholder: 'Cari log sistem...',
    operations: 'Operasional',
    heading: 'Log Aktivitas & Monitor Queue',
    copy: 'Pantau proses sistem, background job, dan tindakan administratif secara real-time.',
    filterLogs: 'Filter Log',
    exportCsv: 'Export CSV',
    queueMonitor: 'Monitor Queue',
    live: 'Live',
    fallback: 'Fallback',
    pendingJobs: 'Job Tertunda',
    processing: 'Diproses',
    failed24h: 'Gagal (24J)',
    workerHealth: 'Kesehatan Worker',
    load: 'Load',
    queueThroughput: 'Throughput Queue',
    throughputA: 'Sistem sedang memproses',
    throughputB: 'workload point per menit dengan',
    throughputC: 'trafik webhook terverifikasi.',
    technicalLogs: 'Log Aktivitas Teknis',
    total: 'Total:',
    events: 'event',
    timestamp: 'Timestamp',
    action: 'Aksi',
    userService: 'User / Service',
    status: 'Status',
    payload: 'Payload',
    openPayload: 'Buka payload untuk',
    showing: 'Menampilkan',
    of: 'dari',
    logs: 'log',
    previousPage: 'Halaman sebelumnya',
    nextPage: 'Halaman berikutnya',
    liveTailMode: 'Mode Live Tail',
    liveTailCopyA: 'Mengambil audit trail, queue jobs, dan aktivitas webhook langsung dari backend. Snapshot saat ini mencakup',
    liveTailCopyB: 'job dan',
    liveTailCopyC: 'event webhook.',
    launchConsole: 'Buka Debug Console',
    apiLatency: 'Latensi API',
    dbConnections: 'Koneksi DB',
    memoryUsage: 'Penggunaan Memori',
    degraded: 'Menurun',
    active: 'Aktif',
    down: 'Down',
    backendLoad: 'estimasi load backend',
    pending: 'Tertunda',
    rejected: 'Ditolak',
    approved: 'Disetujui',
    success: 'Sukses',
  },
} as const;

function formatTimestamp(value: string | null, labels: Record<string, string>) {
  if (!value) {
    return labels.pending;
  }

  return new Date(value).toLocaleString('sv-SE', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
}

function actorBadge(name: string) {
  return name
    .split(/[\s_.-]+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase() || '')
    .join('') || 'SY';
}

function inferActorKind(name: string) {
  const lowered = name.toLowerCase();
  if (lowered.includes('queue') || lowered.includes('system') || lowered.includes('scheduler')) {
    return { actorKind: 'service' as const, actorIcon: 'robot_2' };
  }

  if (lowered.includes('ip:') || lowered.includes('http') || lowered.includes('webhook')) {
    return { actorKind: 'network' as const, actorIcon: 'public' };
  }

  return { actorKind: 'user' as const, actorBadge: actorBadge(name) };
}

function mapAuditStatus(actionType: string, severity: 'default' | 'alert', labels: Record<string, string>): { label: string; tone: StatusTone } {
  const lowered = actionType.toLowerCase();

  if (severity === 'alert' || lowered.includes('fail') || lowered.includes('reject')) {
    return { label: labels.rejected, tone: 'error' };
  }

  if (lowered.includes('retry') || lowered.includes('pending') || lowered.includes('queue')) {
    return { label: labels.pending, tone: 'warning' };
  }

  if (lowered.includes('approve')) {
    return { label: labels.approved, tone: 'success' };
  }

  return { label: labels.success, tone: 'success' };
}

function mapPayloadTone(tone: StatusTone): 'primary' | 'success' | 'error' | 'neutral' {
  if (tone === 'error') return 'error';
  if (tone === 'warning') return 'neutral';
  return 'primary';
}

export default async function LogsPage() {
  const token = await requireAuthToken();
  const locale = await getLocale();
  const labels = analyticsLabels[locale];

  const [summary, auditTrail] = await Promise.all([
    fetchAnalyticsSummary(token),
    fetchAuditTrail(token, { page: 1, limit: 5 }),
  ]);

  const queueStats = [
    { label: labels.pendingJobs, value: summary.queue.pendingJobs.toLocaleString('en-US'), tone: 'info', icon: 'schedule' },
    { label: labels.processing, value: summary.queue.processingJobs.toLocaleString('en-US'), tone: 'primary', icon: 'autorenew' },
    { label: labels.failed24h, value: summary.queue.failedJobs24h.toLocaleString('en-US'), tone: 'error', icon: 'error_outline' },
  ] as const;

  const liveWorkerHealth = summary.workers.length > 0 ? summary.workers : fallbackWorkerHealth;

  const liveLogs =
    auditTrail.items.length > 0
      ? auditTrail.items.map((entry) => {
          const status = mapAuditStatus(entry.actionType, entry.severity, labels);
          return {
            timestamp: formatTimestamp(entry.createdAt, labels),
            action: entry.actionType.toUpperCase().replaceAll(' ', '_'),
            detail: entry.details,
            actor: entry.actorName,
            ...inferActorKind(entry.actorName),
            status: status.label,
            statusTone: status.tone,
            payloadTone: mapPayloadTone(status.tone),
          };
        })
      : fallbackAnalyticsLogs.map((log) => ({
          ...log,
          status: log.statusTone === 'error' ? labels.rejected : log.statusTone === 'warning' ? labels.pending : labels.success,
        }));

  const metricData = [
    {
      label: labels.apiLatency,
      value: `${summary.metrics.apiLatencyMs}ms`,
      meta: summary.health.database === 'ok' ? labels.live : labels.degraded,
      metaTone: summary.health.database === 'ok' ? 'success' : 'warning',
      icon: 'bar_chart',
      chartTone: 'bars',
      chartHeights: summary.metrics.apiLatencyBars.map((value) => `${value}%`),
    },
    {
      label: labels.dbConnections,
      value: summary.metrics.databaseConnectionsEstimate.toLocaleString('en-US'),
      meta: summary.health.database === 'ok' ? labels.active : labels.down,
      metaTone: summary.health.database === 'ok' ? 'warning' : 'error',
      icon: 'database',
      chartTone: 'progress',
      progress: `${summary.metrics.databaseUsagePercent}%`,
    },
    {
      label: labels.memoryUsage,
      value: `${summary.metrics.memoryUsageGbEstimate}GB`,
      meta: labels.backendLoad,
      metaTone: 'muted',
      icon: 'memory',
      chartTone: 'memory',
      chartHeights: summary.metrics.memoryBars.map((value) => `${value}%`),
    },
  ] as const;

  return (
    <DashboardShell
      currentPath="/dashboard/logs"
      title={labels.title}
      searchPlaceholder={labels.searchPlaceholder}
    >
      <section className="analytics-page">
        <header className="analytics-hero">
          <div>
            <p className="page-eyebrow">{labels.operations}</p>
            <h1 className="analytics-heading">{labels.heading}</h1>
            <p className="analytics-copy">
              {labels.copy}
            </p>
          </div>
          <div className="analytics-hero-actions">
            <button type="button" className="analytics-ghost-button">
              <span className="material-symbols-outlined">filter_list</span>
              {labels.filterLogs}
            </button>
            <button type="button" className="analytics-ghost-button">
              <span className="material-symbols-outlined">download</span>
              {labels.exportCsv}
            </button>
          </div>
        </header>

        <section className="analytics-bento">
          <aside className="analytics-side-stack">
            <article className="surface-card analytics-panel">
              <div className="analytics-panel-head">
                <h3>{labels.queueMonitor}</h3>
                <span className="analytics-live-chip">
                  <span className="analytics-live-dot" />
                  {summary.health.status === 'ok' ? labels.live : labels.fallback}
                </span>
              </div>
              <div className="analytics-queue-stack">
                {queueStats.map((item) => (
                  <div key={item.label} className={`analytics-queue-card is-${item.tone}`}>
                    <div>
                      <p>{item.label}</p>
                      <strong>{item.value}</strong>
                    </div>
                    <span className={`material-symbols-outlined analytics-queue-icon ${item.icon === 'autorenew' ? 'is-spinning' : ''}`}>
                      {item.icon}
                    </span>
                  </div>
                ))}
              </div>
              <div className="analytics-worker-health">
                <h4>{labels.workerHealth}</h4>
                <div className="analytics-worker-list">
                  {liveWorkerHealth.map((worker) => (
                    <div key={worker.name} className="analytics-worker-item">
                      <div className="analytics-worker-meta">
                        <span>{worker.name}</span>
                        <strong className={`is-${worker.tone}`}>{worker.load}% {labels.load}</strong>
                      </div>
                      <div className="analytics-progress-track">
                        <div className={`analytics-progress-fill is-${worker.tone}`} style={{ width: `${worker.load}%` }} />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </article>

            <article className="analytics-throughput-card">
              <div className="analytics-throughput-icon">
                <span className="material-symbols-outlined">bolt</span>
              </div>
              <div>
                <h3>{labels.queueThroughput}</h3>
                <p>
                  {labels.throughputA} {summary.throughput.perMinute.toLocaleString('en-US')} {labels.throughputB}{' '}
                  {summary.throughput.verifiedWebhookRate}% {labels.throughputC}
                </p>
              </div>
            </article>
          </aside>

          <article className="surface-card analytics-table-card">
            <div className="analytics-table-head">
              <h3>{labels.technicalLogs}</h3>
              <span>{labels.total} {auditTrail.total.toLocaleString('en-US')} {labels.events}</span>
            </div>
            <div className="analytics-table-scroll">
              <table className="analytics-table">
                <thead>
                  <tr>
                    <th>{labels.timestamp}</th>
                    <th>{labels.action}</th>
                    <th>{labels.userService}</th>
                    <th>{labels.status}</th>
                    <th>{labels.payload}</th>
                  </tr>
                </thead>
                <tbody>
                  {liveLogs.map((log) => (
                    <tr key={`${log.timestamp}-${log.action}`}>
                      <td className="analytics-table-time">{log.timestamp}</td>
                      <td>
                        <div className="analytics-action-cell">
                          <strong>{log.action}</strong>
                          <span>{log.detail}</span>
                        </div>
                      </td>
                      <td>
                        <div className="analytics-actor-cell">
                          {log.actorKind === 'user' ? (
                            <span className="analytics-actor-badge">{log.actorBadge}</span>
                          ) : (
                            <span className="material-symbols-outlined analytics-actor-icon">{log.actorIcon}</span>
                          )}
                          <span>{log.actor}</span>
                        </div>
                      </td>
                      <td>
                        <span className={statusClassName(log.statusTone)}>{log.status}</span>
                      </td>
                      <td>
                        <button type="button" className={payloadButtonClassName(log.payloadTone)} aria-label={`${labels.openPayload} ${log.action}`}>
                          <span className="material-symbols-outlined">code</span>
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div className="analytics-table-foot">
              <span>
                {labels.showing} {liveLogs.length} {labels.of} {auditTrail.total.toLocaleString('en-US')} {labels.logs}
              </span>
              <div className="analytics-pagination">
                <button type="button" aria-label={labels.previousPage}>
                  <span className="material-symbols-outlined">chevron_left</span>
                </button>
                <button type="button" aria-label={labels.nextPage}>
                  <span className="material-symbols-outlined">chevron_right</span>
                </button>
              </div>
            </div>
          </article>
        </section>

        <section className="analytics-live-tail">
          <div className="analytics-live-tail-icon">
            <span className="material-symbols-outlined">terminal</span>
          </div>
          <div className="analytics-live-tail-copy">
            <h3>{labels.liveTailMode}</h3>
            <p>
              {labels.liveTailCopyA} {summary.totals.totalJobs} {labels.liveTailCopyB} {summary.totals.totalWebhookEvents}{' '}
              {labels.liveTailCopyC}
            </p>
          </div>
          <button type="button" className="analytics-console-button">
            <span className="material-symbols-outlined">play_circle</span>
            {labels.launchConsole}
          </button>
        </section>

        <section className="analytics-metrics-grid">
          {metricData.map((metric) => (
            <article key={metric.label} className="surface-card analytics-metric-card">
              <div className="analytics-metric-head">
                <span>{metric.label}</span>
                <span className="material-symbols-outlined">{metric.icon}</span>
              </div>
              <div className="analytics-metric-value">
                <strong>{metric.value}</strong>
                <span className={`is-${metric.metaTone}`}>{metric.meta}</span>
              </div>

              {metric.chartTone === 'progress' ? (
                <div className="analytics-progress-track analytics-metric-progress">
                  <div className="analytics-progress-fill is-warning" style={{ width: metric.progress }} />
                </div>
              ) : (
                <div className={`analytics-mini-bars ${metric.chartTone === 'memory' ? 'is-memory' : ''}`}>
                  {metric.chartHeights.map((height, index) => (
                    <span
                      key={`${metric.label}-${index}`}
                      className={index >= 4 && metric.chartTone === 'bars' ? 'is-primary' : ''}
                      style={{ height }}
                    />
                  ))}
                </div>
              )}
            </article>
          ))}
        </section>
      </section>
    </DashboardShell>
  );
}
