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';

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';
}

function formatTimestamp(value: string | null) {
  if (!value) {
    return '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'): { label: string; tone: StatusTone } {
  const lowered = actionType.toLowerCase();

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

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

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

  return { label: '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 [summary, auditTrail] = await Promise.all([
    fetchAnalyticsSummary(token),
    fetchAuditTrail(token, { page: 1, limit: 5 }),
  ]);

  const queueStats = [
    { label: 'Pending Jobs', value: summary.queue.pendingJobs.toLocaleString('en-US'), tone: 'info', icon: 'schedule' },
    { label: 'Processing', value: summary.queue.processingJobs.toLocaleString('en-US'), tone: 'primary', icon: 'autorenew' },
    { label: 'Failed (24H)', 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);
          return {
            timestamp: formatTimestamp(entry.createdAt),
            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;

  const metricData = [
    {
      label: 'API Latency',
      value: `${summary.metrics.apiLatencyMs}ms`,
      meta: summary.health.database === 'ok' ? 'Live' : 'Degraded',
      metaTone: summary.health.database === 'ok' ? 'success' : 'warning',
      icon: 'bar_chart',
      chartTone: 'bars',
      chartHeights: summary.metrics.apiLatencyBars.map((value) => `${value}%`),
    },
    {
      label: 'DB Connections',
      value: summary.metrics.databaseConnectionsEstimate.toLocaleString('en-US'),
      meta: summary.health.database === 'ok' ? 'Active' : 'Down',
      metaTone: summary.health.database === 'ok' ? 'warning' : 'error',
      icon: 'database',
      chartTone: 'progress',
      progress: `${summary.metrics.databaseUsagePercent}%`,
    },
    {
      label: 'Memory Usage',
      value: `${summary.metrics.memoryUsageGbEstimate}GB`,
      meta: 'backend-estimated load',
      metaTone: 'muted',
      icon: 'memory',
      chartTone: 'memory',
      chartHeights: summary.metrics.memoryBars.map((value) => `${value}%`),
    },
  ] as const;

  return (
    <DashboardShell
      currentPath="/dashboard/logs"
      title="Admin Dashboard"
      searchPlaceholder="Search system logs..."
    >
      <section className="analytics-page">
        <header className="analytics-hero">
          <div>
            <p className="page-eyebrow">Operations</p>
            <h1 className="analytics-heading">Activity Logs &amp; Queue Monitor</h1>
            <p className="analytics-copy">
              Real-time surveillance of system processes, background jobs, and administrative actions.
            </p>
          </div>
          <div className="analytics-hero-actions">
            <button type="button" className="analytics-ghost-button">
              <span className="material-symbols-outlined">filter_list</span>
              Filter Logs
            </button>
            <button type="button" className="analytics-ghost-button">
              <span className="material-symbols-outlined">download</span>
              Export CSV
            </button>
          </div>
        </header>

        <section className="analytics-bento">
          <aside className="analytics-side-stack">
            <article className="surface-card analytics-panel">
              <div className="analytics-panel-head">
                <h3>Queue Monitor</h3>
                <span className="analytics-live-chip">
                  <span className="analytics-live-dot" />
                  {summary.health.status === 'ok' ? 'Live' : '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>Worker Health</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}% 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>Queue Throughput</h3>
                <p>
                  System is currently processing {summary.throughput.perMinute.toLocaleString('en-US')} workload points
                  per minute with {summary.throughput.verifiedWebhookRate}% verified webhook traffic.
                </p>
              </div>
            </article>
          </aside>

          <article className="surface-card analytics-table-card">
            <div className="analytics-table-head">
              <h3>Technical Activity Logs</h3>
              <span>Total: {auditTrail.total.toLocaleString('en-US')} events</span>
            </div>
            <div className="analytics-table-scroll">
              <table className="analytics-table">
                <thead>
                  <tr>
                    <th>Timestamp</th>
                    <th>Action</th>
                    <th>User / Service</th>
                    <th>Status</th>
                    <th>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={`Open payload for ${log.action}`}>
                          <span className="material-symbols-outlined">code</span>
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div className="analytics-table-foot">
              <span>
                Showing {liveLogs.length} of {auditTrail.total.toLocaleString('en-US')} logs
              </span>
              <div className="analytics-pagination">
                <button type="button" aria-label="Previous page">
                  <span className="material-symbols-outlined">chevron_left</span>
                </button>
                <button type="button" aria-label="Next page">
                  <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>Live Tail Mode</h3>
            <p>
              Pulling live audit trail, queue jobs, and webhook activity from the backend. Current snapshot includes{' '}
              {summary.totals.totalJobs} jobs and {summary.totals.totalWebhookEvents} webhook events.
            </p>
          </div>
          <button type="button" className="analytics-console-button">
            <span className="material-symbols-outlined">play_circle</span>
            Launch Debug Console
          </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>
  );
}
