"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import {
  Alert,
  Button,
  Card,
  Col,
  Descriptions,
  Drawer,
  Empty,
  Form,
  InputNumber,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Timeline,
  Tooltip,
  Spin,
  Typography,
  message,
} from "antd";
import type { ColumnsType, TablePaginationConfig } from "antd/es/table";
import { CloudOutlined, DatabaseOutlined } from "@ant-design/icons";

import { fetchSyncJobs, fetchSyncJobEvents, stopSyncJob, fetchRuntimeStatus, startWorkers } from "@/lib/api/caasm";
import type { CaasmSyncJob, CaasmSyncJobEvent, CaasmSyncJobMetadata, RuntimeStatus } from "@/types/models";

const { Title, Paragraph, Text } = Typography;

const statusOptions = [
  { label: "Pending", value: "pending" },
  { label: "Running", value: "running" },
  { label: "Success", value: "success" },
  { label: "Partial success", value: "partial_success" },
  { label: "Failed", value: "failed" },
];

const jobTypeOptions = [
  { label: "Cloud account sync", value: "cloud_account_sync" },
  { label: "GoDaddy sync", value: "godaddy_sync" },
  { label: "Asset refresh", value: "asset_refresh" },
];

const jobTypeLabels: Record<string, string> = {
  cloud_account_sync: "Cloud account sync",
  godaddy_sync: "GoDaddy sync",
  asset_refresh: "Asset refresh",
};

const executionModeOptions = [
  { label: "Queue (Local/Redis)", value: "queue" },
  { label: "Lightweight Agent", value: "serverless" },
];

const jobTypeColors: Record<string, string> = {
  cloud_account_sync: "geekblue",
  godaddy_sync: "purple",
  asset_refresh: "cyan",
};

const EVENT_BATCH_SIZE = 50;

type TelemetryToken = {
  label: string;
  value: string;
  color?: string;
  tooltip?: string;
};

type TelemetryDetail = {
  label: string;
  value: string;
  tooltip?: string;
};

type PartialFailureItem = {
  scope?: string;
  target?: string;
  message?: string;
};

type JobTerminationKind =
  | "execution_timeout"
  | "external_cancellation"
  | "job_stopped"
  | "persist_error"
  | "sync_error";

type JobTerminationInsight = {
  kind: JobTerminationKind;
  tone: "error" | "warning" | "info";
  label: string;
  summary: string;
  impact: string;
  guidance: string;
  sourceLabel?: string;
};

function formatTelemetryValue(value: unknown): string {
  if (typeof value === "number") {
    return Number.isInteger(value) ? String(value) : value.toFixed(2).replace(/\.00$/, "");
  }
  if (typeof value === "boolean") {
    return value ? "Yes" : "No";
  }
  if (Array.isArray(value)) {
    return value
      .map((item) => formatTelemetryValue(item))
      .filter((item) => item !== "—")
      .join(", ");
  }
  if (typeof value === "object" && value !== null) {
    try {
      return JSON.stringify(value);
    } catch {
      return "[object]";
    }
  }
  if (value == null) {
    return "—";
  }
  return String(value);
}

function shortenText(value: string, limit = 72): string {
  if (value.length <= limit) {
    return value;
  }
  return `${value.slice(0, limit - 1)}…`;
}

function humanizeTelemetryKey(key: string): string {
  return key
    .replace(/_/g, " ")
    .replace(/\b\w/g, (char) => char.toUpperCase());
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null;
}

function parsePartialFailures(value: unknown): PartialFailureItem[] {
  if (!Array.isArray(value)) {
    return [];
  }
  return value
    .filter(isRecord)
    .map((item) => ({
      scope: typeof item.scope === "string" ? item.scope : undefined,
      target: typeof item.target === "string" ? item.target : undefined,
      message: typeof item.message === "string" ? item.message : undefined,
    }))
    .filter((item) => item.scope || item.target || item.message);
}

function normalizeMetadataText(value: unknown): string | undefined {
  if (typeof value !== "string") {
    return undefined;
  }
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : undefined;
}

function compareSyncJobEventsDescending(a: CaasmSyncJobEvent, b: CaasmSyncJobEvent): number {
  const aCreatedAt = Date.parse(a.created_at);
  const bCreatedAt = Date.parse(b.created_at);
  if (Number.isFinite(aCreatedAt) && Number.isFinite(bCreatedAt) && aCreatedAt !== bCreatedAt) {
    return bCreatedAt - aCreatedAt;
  }
  if (a.id !== b.id) {
    return b.id - a.id;
  }
  return 0;
}

function sortSyncJobEventsDescending(events: CaasmSyncJobEvent[]): CaasmSyncJobEvent[] {
  return [...events].sort(compareSyncJobEventsDescending);
}

function mergeUniqueSyncJobEvents(
  existing: CaasmSyncJobEvent[],
  incoming: CaasmSyncJobEvent[],
): CaasmSyncJobEvent[] {
  const merged = new Map<number, CaasmSyncJobEvent>();
  for (const event of existing) {
    merged.set(event.id, event);
  }
  for (const event of incoming) {
    merged.set(event.id, event);
  }
  return sortSyncJobEventsDescending(Array.from(merged.values()));
}

function humanizeStatusReason(value: string): string {
  return value
    .replace(/_/g, " ")
    .replace(/\b\w/g, (char) => char.toUpperCase());
}

function formatUppercaseLabel(value?: string): string {
  const normalized = normalizeMetadataText(value);
  return normalized ? normalized.toUpperCase() : "—";
}

function formatExternalCancellationSource(value?: string): string {
  const normalized = normalizeMetadataText(value)?.toLowerCase();
  if (!normalized) {
    return "UNKNOWN_EXTERNAL";
  }

  switch (normalized) {
    case "unknown_external":
      return "UNKNOWN_EXTERNAL";
    case "request_canceled":
    case "request_chain_ended":
      return "REQUEST CHAIN ENDED";
    case "upstream_disconnect":
    case "client_disconnect":
      return "UPSTREAM DISCONNECT";
    case "worker_shutdown":
    case "worker_runtime_shutdown":
    case "runtime_shutdown":
      return "WORKER/RUNTIME SHUTDOWN";
    case "parent_context_canceled":
      return "PARENT CONTEXT CANCELED";
    default:
      return normalized.replace(/_/g, " ").toUpperCase();
  }
}

function formatPersistCancellationSource(value?: string): string {
  const normalized = normalizeMetadataText(value)?.toLowerCase();
  if (!normalized) {
    return "DB QUERY CANCELED";
  }

  switch (normalized) {
    case "db_query_deadline_exceeded":
      return "DB QUERY TIMED OUT";
    case "db_query_canceled":
      return "DB QUERY CANCELED";
    default:
      return normalized.replace(/_/g, " ").toUpperCase();
  }
}

function normalizeTerminationKind(value?: unknown): JobTerminationKind | undefined {
  switch (normalizeMetadataText(value)?.toLowerCase()) {
    case "execution_timeout":
      return "execution_timeout";
    case "external_cancellation":
      return "external_cancellation";
    case "job_stopped":
      return "job_stopped";
    case "persist_error":
      return "persist_error";
    case "sync_error":
      return "sync_error";
    default:
      return undefined;
  }
}

function normalizeFailedPhase(value?: unknown): string | undefined {
  const normalized = normalizeMetadataText(value)?.toLowerCase();
  return normalized || undefined;
}

function hasDeadlineExceededError(value?: string): boolean {
  const lower = (value || "").toLowerCase();
  return lower.includes("deadline exceeded") || lower.includes("context deadline exceeded") || lower.includes("timeout");
}

function hasContextCanceledError(value?: string): boolean {
  return (value || "").toLowerCase().includes("context canceled");
}

function classifyJobTermination(job: CaasmSyncJob | null): JobTerminationInsight | null {
  if (!job || job.status !== "failed") {
    return null;
  }

  const metadata = (job.metadata ?? {}) as CaasmSyncJobMetadata;
  const terminationReason = normalizeTerminationKind(metadata.termination_reason);
  const failedPhase = normalizeFailedPhase(metadata.failed_phase);
  const errorMessage = normalizeMetadataText(job.error_message);
  const staleMarkSkippedReason = normalizeMetadataText(metadata.stale_mark_skipped_reason);
  const cancellationSource = normalizeMetadataText(metadata.cancellation_source);
  const contextSource = normalizeMetadataText(metadata.context_source);

  const kind =
    terminationReason ??
    (failedPhase === "persist" ? "persist_error" : undefined) ??
    (hasDeadlineExceededError(errorMessage) || staleMarkSkippedReason === "execution_timeout"
      ? "execution_timeout"
      : hasContextCanceledError(errorMessage)
        ? "external_cancellation"
        : staleMarkSkippedReason === "job_stopped"
          ? "job_stopped"
          : "sync_error");

  switch (kind) {
    case "execution_timeout":
      return {
        kind,
        tone: "warning",
        label: "Execution timeout",
        summary:
          "The job exceeded the configured execution budget and stopped before it could finish a complete snapshot.",
        impact:
          "Stale-mark cleanup was skipped because the run did not produce a complete inventory snapshot.",
        guidance:
          "Increase execution_timeout_minutes, narrow the collection scope, or check worker pressure and account size.",
      };
    case "external_cancellation":
      return {
        kind,
        tone: "warning",
        label: "External cancellation",
        summary: contextSource
          ? `The job lost its execution context while running through ${contextSource}.`
          : "The job lost its execution context to an external cancellation path.",
        impact:
          "Stale-mark cleanup was skipped because the run did not produce a complete inventory snapshot.",
        guidance: cancellationSource && cancellationSource.toLowerCase() !== "unknown_external"
          ? `Known source: ${formatExternalCancellationSource(cancellationSource)}. Check request/ingress timeouts, worker/runtime restarts, and inline fallback paths.`
          : "Source: UNKNOWN_EXTERNAL. Check request/ingress timeouts, worker/runtime restarts, and inline fallback paths.",
        sourceLabel: cancellationSource ? `Cancellation source: ${formatExternalCancellationSource(cancellationSource)}` : undefined,
      };
    case "job_stopped":
      return {
        kind,
        tone: "info",
        label: "Stopped",
        summary: "The job was intentionally stopped before it could finish a complete snapshot.",
        impact:
          "Stale-mark cleanup was skipped because the run did not produce a complete inventory snapshot.",
        guidance: "Rerun only after confirming the stop was expected.",
      };
    case "persist_error":
      const persistSource = cancellationSource ? formatPersistCancellationSource(cancellationSource) : undefined;
      return {
        kind,
        tone: "error",
        label: "Persist error",
        summary: persistSource === "DB QUERY TIMED OUT"
          ? "Collection finished, but a persist-stage database query timed out before the inventory snapshot could be written."
          : "Collection finished, but a persist-stage database query was canceled before the inventory snapshot could be written.",
        impact:
          "Stale-mark cleanup was skipped because the run did not produce a durable inventory snapshot.",
        guidance:
          "Inspect database connectivity, connection-pool pressure, query cancellation, and worker/runtime restarts. Review the persist prefetch counters before retrying this job.",
        sourceLabel: persistSource ? `Persist source: ${persistSource}` : undefined,
      };
    default:
      return {
        kind: "sync_error",
        tone: "error",
        label: "Sync error",
        summary: "The job failed during collection or persistence before it could finish a complete snapshot.",
        impact:
          "Stale-mark cleanup was skipped because the run did not produce a complete inventory snapshot.",
        guidance:
          "Inspect the structured metadata and event timeline for the first failing stage before retrying.",
      };
  }
}

function formatStaleMarkSkipReason(value: unknown): string | null {
  if (typeof value !== "string" || value.trim() === "") {
    return null;
  }
  return humanizeStatusReason(value);
}

function isTrue(value: unknown): boolean {
  return value === true;
}

function formatStageValue(completed: boolean, fallback: string): { value: string; color?: string; tooltip?: string } {
  if (completed) {
    return { value: "Completed", color: "green" };
  }
  return { value: fallback, color: "default" };
}

function summarizeStageProgress(metadata?: Record<string, unknown>): TelemetryToken[] {
  if (!metadata) {
    return [];
  }

  const collectionCompleted = isTrue(metadata.collection_completed);
  const persistCompleted = isTrue(metadata.persist_completed);
  const staleMarkCompleted = isTrue(metadata.stale_mark_completed);
  const staleMarkError = typeof metadata.stale_mark_error === "string" ? metadata.stale_mark_error.trim() : "";
  const staleMarkSkippedReason = formatStaleMarkSkipReason(metadata.stale_mark_skipped_reason);

  const stageTokens: TelemetryToken[] = [
    {
      label: "Collection",
      ...formatStageValue(collectionCompleted, "Not completed"),
      tooltip: collectionCompleted
        ? "Collection finished and the collector produced a usable inventory snapshot."
        : "Collection did not finish before the run stopped.",
    },
    {
      label: "Persist",
      ...formatStageValue(persistCompleted, collectionCompleted ? "Not completed" : "Not reached"),
      tooltip: persistCompleted
        ? "Persist finished and the collected inventory was written to the database."
        : collectionCompleted
          ? "Persist did not finish before the run stopped."
          : "Persist was never reached because collection did not complete.",
    },
    {
      label: "Stale mark",
      value: staleMarkCompleted
        ? "Completed"
        : staleMarkError
          ? "Failed"
          : staleMarkSkippedReason
            ? `Skipped (${staleMarkSkippedReason})`
            : persistCompleted
              ? "Not run"
              : "Not reached",
      color: staleMarkCompleted ? "green" : staleMarkError ? "red" : staleMarkSkippedReason ? "gold" : "default",
      tooltip: staleMarkCompleted
        ? "Historical assets were reconciled after the sync completed successfully."
        : staleMarkError
          ? staleMarkError
          : staleMarkSkippedReason
            ? "Historical assets were intentionally left intact until the next successful sync."
            : persistCompleted
              ? "Stale-mark cleanup was not run for this job."
              : "Stale-mark cleanup was not reached.",
    },
  ];

  return stageTokens;
}

function formatJobStatusLabel(value: string): string {
  return value.replace(/_/g, " ").toUpperCase();
}

function extractThrottleSignal(metadata?: Record<string, unknown>): {
  detected: boolean;
  target?: string;
} {
  if (!metadata) {
    return { detected: false };
  }
  if (typeof metadata.throttle_state === "string" && metadata.throttle_state.trim() !== "") {
    return {
      detected: true,
      target: typeof metadata.throttle_target === "string" ? metadata.throttle_target : undefined,
    };
  }
  const partialFailures = Array.isArray(metadata.partial_failures) ? metadata.partial_failures : [];
  for (const issue of partialFailures) {
    if (!issue || typeof issue !== "object") {
      continue;
    }
    const candidate = issue as Record<string, unknown>;
    const signal = [candidate.message, candidate.target, candidate.scope]
      .filter((value): value is string => typeof value === "string" && value.trim() !== "")
      .join(" ")
      .toLowerCase();
    if (signal.includes("throttl") || signal.includes("rate exceeded") || signal.includes("too many request")) {
      return {
        detected: true,
        target: typeof candidate.target === "string" ? candidate.target : undefined,
      };
    }
  }
  return { detected: false };
}

function summarizeJobMetadata(metadata?: Record<string, unknown>): TelemetryToken[] {
  if (!metadata) {
    return [];
  }

  const tokens: TelemetryToken[] = [];
  const executionMode = typeof metadata.execution_mode === "string" ? metadata.execution_mode : "queue";
  const failedPhase = normalizeFailedPhase(metadata.failed_phase);
  const outcome = normalizeTerminationKind(metadata.termination_reason) ?? (failedPhase === "persist" ? "persist_error" : undefined);
  tokens.push({
    label: "Mode",
    value: executionMode === "serverless" ? "Lightweight Agent" : "Queue",
    color: executionMode === "serverless" ? "purple" : "cyan",
  });

  if (typeof metadata.provider === "string" && metadata.provider.trim() !== "") {
    tokens.push({ label: "Provider", value: metadata.provider.toUpperCase(), color: "blue" });
  }
  if (outcome) {
    tokens.push({
      label: "Outcome",
      value: formatUppercaseLabel(outcome),
      color: outcome === "sync_error" || outcome === "persist_error" ? "red" : "gold",
    });
  }
  if (typeof metadata.cancellation_source === "string" && metadata.cancellation_source.trim() !== "") {
    tokens.push({
      label: "Cancel source",
      value: formatExternalCancellationSource(metadata.cancellation_source),
      color: "orange",
    });
  }
  if (typeof metadata.context_source === "string" && metadata.context_source.trim() !== "") {
    tokens.push({
      label: "Context",
      value: formatUppercaseLabel(metadata.context_source),
      color: "cyan",
    });
  }
  if (typeof metadata.execution_timeout_minutes === "number" && Number.isFinite(metadata.execution_timeout_minutes)) {
    tokens.push({
      label: "Execution timeout",
      value: `${metadata.execution_timeout_minutes} min`,
      color: "purple",
    });
  }
  if (typeof metadata.account_name === "string" && metadata.account_name.trim() !== "") {
    tokens.push({ label: "Account", value: metadata.account_name });
  }
  if (metadata.completed_with_warnings === true) {
    tokens.push({
      label: "Warnings",
      value: "Present",
      color: "gold",
      tooltip: "Collector completed, but part of the inventory was skipped or degraded.",
    });
  }
  if (typeof metadata.partial_failure_count === "number" && Number.isFinite(metadata.partial_failure_count)) {
    const count = metadata.partial_failure_count;
    tokens.push({
      label: "Partial Failures",
      value: String(count),
      color: count > 0 ? "orange" : "default",
      tooltip: `${count} collector step${count === 1 ? "" : "s"} completed with warnings instead of a full success.`,
    });
  }
  const throttleSignal = extractThrottleSignal(metadata);
  if (throttleSignal.detected) {
    tokens.push({
      label: "Throttle",
      value: throttleSignal.target ? `Detected (${throttleSignal.target})` : "Detected",
      color: "orange",
      tooltip: "AWS API throttling was detected during this run, even if the final job status was not a hard failure.",
    });
  }
  const staleMarkSkipReason = formatStaleMarkSkipReason(metadata.stale_mark_skipped_reason);
  if (staleMarkSkipReason) {
    tokens.push({
      label: "Stale Mark",
      value: `Skipped (${staleMarkSkipReason})`,
      color: "volcano",
      tooltip: "Stale-mark cleanup was intentionally skipped because the job did not produce a complete inventory snapshot.",
    });
  }
  if (typeof metadata.persist_asset_count === "number" && Number.isFinite(metadata.persist_asset_count)) {
    tokens.push({
      label: "Persist assets",
      value: String(metadata.persist_asset_count),
      color: "volcano",
    });
  }
  if (
    typeof metadata.persist_prefetch_hit_count === "number" &&
    typeof metadata.persist_prefetch_miss_count === "number"
  ) {
    const chunks =
      typeof metadata.persist_prefetch_chunk_count === "number" && Number.isFinite(metadata.persist_prefetch_chunk_count)
        ? ` / ${metadata.persist_prefetch_chunk_count} chunk${metadata.persist_prefetch_chunk_count === 1 ? "" : "s"}`
        : "";
    tokens.push({
      label: "Prefetch",
      value: `${metadata.persist_prefetch_hit_count} hit / ${metadata.persist_prefetch_miss_count} miss${chunks}`,
      color: "orange",
      tooltip: "Persist-stage existing-asset prefetch summary used to avoid per-asset native-id lookups.",
    });
  }
  if (metadata.priority != null) {
    tokens.push({ label: "Priority", value: formatTelemetryValue(metadata.priority) });
  }
  if (typeof metadata.throttle_state === "string" && metadata.throttle_state.trim() !== "") {
    tokens.push({ label: "Throttle", value: metadata.throttle_state, color: "orange" });
  }
  if (typeof metadata.slowdown_source === "string" && metadata.slowdown_source.trim() !== "") {
    tokens.push({ label: "Slowdown", value: metadata.slowdown_source, color: "magenta" });
  }
  if (typeof metadata.coordination_state === "string" && metadata.coordination_state.trim() !== "") {
    tokens.push({ label: "Coordination", value: metadata.coordination_state, color: "gold" });
  }
  if (typeof metadata.circuit_breaker_state === "string" && metadata.circuit_breaker_state.trim() !== "") {
    tokens.push({ label: "Circuit", value: metadata.circuit_breaker_state, color: "red" });
  }

  return tokens;
}

function summarizeJobState(job: CaasmSyncJob | null): {
  tone: "error" | "warning" | "info";
  label: string;
  detail: string;
} | null {
  if (!job) {
    return null;
  }

  const metadata = job.metadata ?? {};
  const slowdownSource = typeof metadata.slowdown_source === "string" ? metadata.slowdown_source : undefined;
  const throttleSignal = extractThrottleSignal(metadata);
  const collectionCompleted = isTrue(metadata.collection_completed);
  const persistCompleted = isTrue(metadata.persist_completed);
  const staleMarkError = typeof metadata.stale_mark_error === "string" ? metadata.stale_mark_error.trim() : "";
  const staleMarkSkippedReason = formatStaleMarkSkipReason(metadata.stale_mark_skipped_reason);

  if (staleMarkError) {
    return {
      tone: "warning",
      label: "Stale-mark cleanup failed",
      detail:
        "Collection and persist finished, but stale-mark cleanup failed. Historical assets were left intact so the next successful sync can reconcile them.",
    };
  }

  if (slowdownSource === "circuit_breaker" || metadata.circuit_breaker_state != null) {
    return {
      tone: "warning",
      label: "Circuit breaker active",
      detail: "The job was slowed or deferred because the circuit breaker tripped for this worker, account, or service scope.",
    };
  }

  if (slowdownSource === "coordination_guard" || metadata.coordination_state != null) {
    return {
      tone: "warning",
      label: "Deferred by runtime guard",
      detail:
        job.error_message ||
        "Runtime coordination is delaying or rejecting duplicate work while the shared pressure cap or account lock is under load.",
    };
  }

  if (slowdownSource === "throttle" || slowdownSource === "aws_throttle" || metadata.throttle_state != null || throttleSignal.detected) {
    return {
      tone: "warning",
      label: "AWS throttling detected",
      detail:
        job.error_message ||
        "The collector hit AWS API throttling or completed with throttle-related partial failures. Inspect the event timeline before retrying.",
    };
  }

  if (job.status === "failed") {
    const termination = classifyJobTermination(job);
    if (termination) {
      const detailParts = [termination.summary, termination.impact, termination.guidance];
      if (termination.sourceLabel) {
        detailParts.splice(2, 0, termination.sourceLabel);
      }
      return {
        tone: termination.tone,
        label: termination.label,
        detail: detailParts.join(" "),
      };
    }
    if (collectionCompleted || persistCompleted || staleMarkSkippedReason) {
      return {
        tone: "warning",
        label: "Job failed before cleanup completed",
        detail:
          job.error_message ||
          "This run stopped early. Historical assets were intentionally left intact and will be reconciled on the next successful sync.",
      };
    }
    return {
      tone: "error",
      label: "Job failed",
      detail: job.error_message || "This sync job ended in failure. Open the log timeline to inspect the first failure signal.",
    };
  }

  if (job.status === "partial_success") {
    if (staleMarkSkippedReason) {
      return {
        tone: "warning",
        label: "Job completed with warnings",
        detail:
          job.error_message ||
          "The collector completed but stale-mark cleanup was intentionally skipped. Historical assets stay intact until the next successful sync.",
      };
    }
    return {
      tone: "warning",
      label: "Job completed with warnings",
      detail:
        job.error_message ||
        "The collector completed but skipped part of the inventory. Review the event timeline before trusting full coverage.",
    };
  }

  if (job.status === "running") {
    return {
      tone: "info",
      label: "Job in progress",
      detail: "Open the log timeline to inspect the current collector or runtime state.",
    };
  }

  return null;
}

function summarizeEventMetadata(event: CaasmSyncJobEvent): {
  category: string;
  tokens: TelemetryToken[];
  details: TelemetryDetail[];
} {
  const metadata = event.metadata ?? {};
  const lowerMessage = event.message.toLowerCase();
  const failedPhase = normalizeFailedPhase(metadata.failed_phase);
  const terminationReason = normalizeTerminationKind(metadata.termination_reason);
  const eventOutcome = terminationReason ?? (failedPhase === "persist" ? "persist_error" : undefined);
  let category = "Collector event";
  const tokens: TelemetryToken[] = [];
  const consumedKeys = new Set<string>();

  const consume = (key: string, label: string, color?: string, formatter?: (value: unknown) => string) => {
    const value = metadata[key];
    if (value == null || value === "") {
      return;
    }
    consumedKeys.add(key);
    tokens.push({
      label,
      value: formatter ? formatter(value) : formatTelemetryValue(value),
      color,
    });
  };

  if (eventOutcome) {
    category = formatUppercaseLabel(eventOutcome);
    consume("termination_reason", "Outcome", event.type === "error" ? "red" : "gold", (value) =>
      formatUppercaseLabel(typeof value === "string" ? value : undefined),
    );
    consume("failed_phase", "Failed phase", "red", (value) =>
      formatUppercaseLabel(typeof value === "string" ? value : undefined),
    );
    consume("cancellation_source", "Cancel source", "orange", (value) =>
      formatExternalCancellationSource(typeof value === "string" ? value : undefined),
    );
    consume("context_source", "Context", "cyan", (value) =>
      formatUppercaseLabel(typeof value === "string" ? value : undefined),
    );
    consume("execution_timeout_minutes", "Execution timeout", "purple", (value) => `${formatTelemetryValue(value)} min`);
    if (eventOutcome === "persist_error") {
      consume("persist_completed", "Persist", "red", (value) => (value === true ? "Completed" : "Incomplete"));
      consume("persist_asset_count", "Persist assets", "volcano");
      consume("persist_prefetch_native_id_count", "Prefetch native IDs", "orange");
      consume("persist_prefetch_chunk_count", "Prefetch chunks", "orange");
      consume("persist_prefetch_hit_count", "Prefetch hits", "orange");
      consume("persist_prefetch_miss_count", "Prefetch misses", "orange");
    }
  } else if (metadata.slowdown_source === "circuit_breaker" || metadata.circuit_breaker_state != null) {
    category = "Circuit breaker";
    consume("slowdown_source", "Slowdown", "magenta");
    consume("service", "Service", "orange");
    consume("region", "Region");
    consume("circuit_breaker_state", "Circuit", "red");
    consume("cool_off_sec", "Cool-off", "red", (value) => `${formatTelemetryValue(value)} sec`);
  } else if (lowerMessage.includes("throttle")) {
    category = "AWS throttling";
    consume("slowdown_source", "Slowdown", "magenta");
    consume("service", "Service", "orange");
    consume("region", "Region");
    consume("attempt", "Attempt");
    consume("backoff_ms", "Backoff", "orange", (value) => `${formatTelemetryValue(value)} ms`);
    consume("circuit_breaker_state", "Circuit", "red");
  } else if (lowerMessage.includes("time budget") || metadata.remaining_ms != null) {
    category = "Configured budget";
    consume("slowdown_source", "Slowdown", "magenta");
    consume("region", "Region");
    consume("remaining_ms", "Remaining", "gold", (value) => `${formatTelemetryValue(value)} ms`);
    consume("budget_state", "Budget", "gold");
  } else if (metadata.coordination_state != null || metadata.slowdown_source === "coordination_guard" || lowerMessage.includes("worker") || lowerMessage.includes("queue")) {
    category = "Runtime coordination";
    consume("slowdown_source", "Slowdown", "magenta");
    consume("mode", "Mode", "blue");
    consume("priority", "Priority");
    consume("coordination_state", "Coordination", "gold");
    consume("runtime_cap", "Runtime cap");
    consume("active_running_jobs", "Running jobs");
  } else if (metadata.service != null && metadata.operation != null) {
    category = "AWS API call";
    consume("service", "Service", "blue");
    consume("operation", "Operation");
    consume("region", "Region");
    consume("duration_ms", "Duration", undefined, (value) => `${formatTelemetryValue(value)} ms`);
  } else {
    consume("provider", "Provider", "blue");
    consume("mode", "Mode", "cyan");
  }

  const partialFailures = parsePartialFailures(metadata.partial_failures);
  if (partialFailures.length > 0) {
    consumedKeys.add("partial_failures");
  }

  const remainder: Record<string, unknown> = {};
  for (const [key, value] of Object.entries(metadata)) {
    if (!consumedKeys.has(key)) {
      remainder[key] = value;
    }
  }

  const details: TelemetryDetail[] = Object.entries(remainder).map(([key, value]) => ({
    label: humanizeTelemetryKey(key),
    value: formatTelemetryValue(value),
    tooltip: typeof value === "string" ? value : undefined,
  }));
  if (partialFailures.length > 0) {
    for (const [index, issue] of partialFailures.entries()) {
      details.push({
        label: `Failure ${index + 1}`,
        value: [issue.scope, issue.target, issue.message].filter(Boolean).join(" | "),
        tooltip: issue.message,
      });
    }
  }

  return {
    category,
    tokens,
    details,
  };
}

export default function SyncJobsPage() {
  const [records, setRecords] = useState<CaasmSyncJob[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 20, total: 0 });
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({
    status: undefined as string | undefined,
    job_type: undefined as string | undefined,
    cloud_account_id: undefined as number | undefined,
    execution_mode: undefined as string | undefined,
  });

  const [drawerVisible, setDrawerVisible] = useState(false);
  const [selectedJob, setSelectedJob] = useState<CaasmSyncJob | null>(null);
  const [events, setEvents] = useState<CaasmSyncJobEvent[]>([]);
  const [eventsLoading, setEventsLoading] = useState(false);
  const [eventsError, setEventsError] = useState<string | null>(null);
  const [eventsLoadingMore, setEventsLoadingMore] = useState(false);
  const [eventsBeforeCursor, setEventsBeforeCursor] = useState<number | null>(null);
  const [eventsHasMore, setEventsHasMore] = useState(false);
  const [expandedEventIds, setExpandedEventIds] = useState<number[]>([]);
  const [runtimeStatus, setRuntimeStatus] = useState<RuntimeStatus | null>(null);
  const [checkingRuntime, setCheckingRuntime] = useState(false);
  const eventsRequestSeq = useRef(0);

  const loadData = useCallback(
    async (page: number, pageSize: number) => {
      setLoading(true);
      try {
        const payload = await fetchSyncJobs({
          page,
          page_size: pageSize,
          status: filters.status,
          job_type: filters.job_type,
          cloud_account_id: filters.cloud_account_id,
          execution_mode: filters.execution_mode,
        });
        setRecords(payload.items ?? []);
        setPagination((prev) => ({ ...prev, total: payload.total ?? prev.total }));
      } catch (error) {
        console.error("Failed to load sync jobs", error);
        message.error("Failed to load jobs");
      } finally {
        setLoading(false);
      }
    },
    [filters],
  );

  const loadEvents = useCallback(
    async (jobId: number, options?: { beforeId?: number; append?: boolean }) => {
      const isAppend = options?.append === true;
      const requestSeq = isAppend ? eventsRequestSeq.current : ++eventsRequestSeq.current;
      if (isAppend) {
        setEventsLoadingMore(true);
      } else {
        setEventsLoading(true);
        setEventsError(null);
        setEvents([]);
        setEventsBeforeCursor(null);
        setEventsHasMore(false);
        setExpandedEventIds([]);
      }

      try {
        const data = await fetchSyncJobEvents(jobId, {
          limit: EVENT_BATCH_SIZE,
          before_id: options?.beforeId,
        });
        if (requestSeq !== eventsRequestSeq.current) {
          return;
        }
        const sorted = sortSyncJobEventsDescending(data || []);
        setEvents((current) => (isAppend ? mergeUniqueSyncJobEvents(current, sorted) : sorted));
        setEventsBeforeCursor(sorted.length > 0 ? sorted[sorted.length - 1].id : null);
        setEventsHasMore(sorted.length === EVENT_BATCH_SIZE);
      } catch (error) {
        if (requestSeq !== eventsRequestSeq.current) {
          return;
        }
        console.error("Failed to load events", error);
        setEventsError("Failed to load events. Please retry.");
        message.error("Failed to load events");
      } finally {
        if (requestSeq === eventsRequestSeq.current) {
          if (isAppend) {
            setEventsLoadingMore(false);
          } else {
            setEventsLoading(false);
          }
        }
      }
    },
    [],
  );

  const handleViewLogs = (job: CaasmSyncJob) => {
    setSelectedJob(job);
    setDrawerVisible(true);
    void loadEvents(job.id);
  };

  const onCloseDrawer = () => {
    setDrawerVisible(false);
  };

  const handleDrawerOpenChange = (open: boolean) => {
    if (open) {
      return;
    }
    eventsRequestSeq.current += 1;
    setSelectedJob(null);
    setEvents([]);
    setEventsError(null);
    setEventsLoading(false);
    setEventsLoadingMore(false);
    setEventsBeforeCursor(null);
    setEventsHasMore(false);
    setExpandedEventIds([]);
  };

  const handleStopJob = async (job: CaasmSyncJob) => {
    try {
      await stopSyncJob(job.id);
      message.success("Job stop signal sent");
      loadData(currentPage, currentPageSize);
    } catch (error) {
      console.error("Failed to stop job", error);
      message.error("Failed to stop job");
    }
  };

  const currentPage = pagination.current ?? 1;
  const currentPageSize = pagination.pageSize ?? 20;

  const checkRuntimeStatus = useCallback(async () => {
    try {
      setCheckingRuntime(true);
      const status = await fetchRuntimeStatus();
      setRuntimeStatus(status);
    } catch (error) {
      console.error("Failed to check runtime status", error);
    } finally {
      setCheckingRuntime(false);
    }
  }, []);

  useEffect(() => {
    loadData(currentPage, currentPageSize);
    checkRuntimeStatus();

    // Poll runtime status every 30 seconds
    const interval = setInterval(checkRuntimeStatus, 30000);
    return () => clearInterval(interval);
  }, [loadData, currentPage, currentPageSize, checkRuntimeStatus]);

  const columns: ColumnsType<CaasmSyncJob> = [
    {
      title: "Job ID",
      dataIndex: "id",
      width: 80,
      render: (value: number) => <span style={{ whiteSpace: "nowrap" }}>{value}</span>,
    },
    {
      title: "Status",
      dataIndex: "status",
      width: 170,
      render: (value: string) => (
        <Tag
          color={value === "success" ? "green" : value === "partial_success" ? "gold" : value === "failed" ? "red" : "default"}
          style={{ whiteSpace: "nowrap", display: "inline-flex", maxWidth: "100%", overflow: "hidden", textOverflow: "ellipsis" }}
        >
          {formatJobStatusLabel(value)}
        </Tag>
      ),
    },
    {
      title: "Job type",
      dataIndex: "job_type",
      width: 220,
      render: (value: string) => (
        <Tag
          color={jobTypeColors[value] ?? "default"}
          style={{ whiteSpace: "nowrap", display: "inline-flex", maxWidth: "100%", overflow: "hidden", textOverflow: "ellipsis" }}
        >
          {jobTypeLabels[value] || value.replace(/_/g, " ")}
        </Tag>
      ),
    },
    {
      title: "Cloud account",
      dataIndex: "cloud_account_id",
      width: 130,
      render: (value: number | undefined) => <span style={{ whiteSpace: "nowrap" }}>{value ?? "N/A"}</span>,
    },
    {
      title: "Created",
      dataIndex: "created_at",
      width: 180,
      render: (value: string) => <span style={{ whiteSpace: "nowrap" }}>{value}</span>,
    },
    {
      title: "Execution Mode",
      dataIndex: "metadata",
      width: 180,
      render: (value: Record<string, unknown> | undefined) => {
        const mode = (value?.execution_mode as string) || "queue";
        const isServerless = mode === "serverless";
        return (
          <Tooltip title={isServerless ? "Executed via lightweight agent (Lambda)" : "Executed via Local Queue"}>
            <Tag icon={isServerless ? <CloudOutlined /> : <DatabaseOutlined />} color={isServerless ? "purple" : "cyan"} style={{ whiteSpace: "nowrap" }}>
              {isServerless ? "LIGHTWEIGHT AGENT" : mode.toUpperCase()}
            </Tag>
          </Tooltip>
        );
      },
    },
    {
      title: "Execution summary",
      dataIndex: "metadata",
      width: 300,
      render: (_: Record<string, unknown> | undefined, record: CaasmSyncJob) => {
        const tokens = summarizeJobMetadata(record.metadata);
        const jobState = summarizeJobState(record);
        if (jobState) {
          tokens.unshift({
            label: "Signal",
            value: jobState.label,
            color: jobState.tone === "error" ? "red" : "orange",
            tooltip: jobState.detail,
          });
        }
        if (tokens.length === 0) {
          return "—";
        }
        return (
          <Space size={[6, 6]} wrap style={{ maxWidth: 280 }}>
            {tokens.map((token) => (
              <Tooltip key={`${token.label}-${token.value}`} title={token.tooltip || `${token.label}: ${token.value}`}>
                <Tag color={token.color} style={{ maxWidth: 260 }}>
                  {token.label}: {token.value}
                </Tag>
              </Tooltip>
            ))}
          </Space>
        );
      },
    },
    {
      title: "Actions",
      key: "actions",
      width: 180,
      fixed: "right",
      render: (_, record) => (
        <Space style={{ whiteSpace: "nowrap" }}>
          <Button type="link" onClick={() => handleViewLogs(record)}>
            View Logs
          </Button>
          {(record.status === "running" || record.status === "queued" || record.status === "pending") && (
            <Button type="link" danger onClick={() => handleStopJob(record)}>
              Stop
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const onFilterChange = (field: string, value: string | number | null) => {
    setFilters((prev) => ({ ...prev, [field]: value ?? undefined }));
    setPagination((prev) => ({ ...prev, current: 1 }));
  };

  const handleTableChange = (pager: TablePaginationConfig) => {
    setPagination((prev) => ({
      ...prev,
      current: pager.current ?? prev.current,
      pageSize: pager.pageSize ?? prev.pageSize,
    }));
  };

  const handleStartWorkersFromBanner = async () => {
    try {
      setCheckingRuntime(true);
      await startWorkers();
      message.success("Worker pool started successfully");
      await checkRuntimeStatus();
    } catch (error) {
      console.error("Failed to start workers", error);
      message.error("Failed to start worker pool");
    } finally {
      setCheckingRuntime(false);
    }
  };

  const selectedJobState = summarizeJobState(selectedJob);
  const selectedJobSummaryTokens = selectedJob ? summarizeJobMetadata(selectedJob.metadata) : [];
  const selectedJobStageTokens = selectedJob ? summarizeStageProgress(selectedJob.metadata) : [];
  const handleLoadOlderEvents = () => {
    if (!selectedJob || eventsLoadingMore || !eventsBeforeCursor) {
      return;
    }
    void loadEvents(selectedJob.id, { beforeId: eventsBeforeCursor, append: true });
  };

  const toggleEventDetails = useCallback((eventId: number) => {
    setExpandedEventIds((current) =>
      current.includes(eventId) ? current.filter((id) => id !== eventId) : [...current, eventId],
    );
  }, []);

  return (
    <Space direction="vertical" size={24} style={{ width: "100%" }}>
      {runtimeStatus && runtimeStatus.kill_switch_enabled && (
        <Alert
          type="error"
          showIcon
          message="Emergency Stop Enabled"
          description={
            <Space direction="vertical" size={4}>
              <span>New sync jobs are blocked and the worker pool stays stopped while the emergency stop is enabled.</span>
              <span>Disable the emergency stop from CAASM Config before starting workers again.</span>
              {runtimeStatus.runtime_pressure_cap ? (
                <span>
                  Current cap: {runtimeStatus.runtime_pressure_cap} active jobs
                  {runtimeStatus.active_job_count != null ? `, currently active: ${runtimeStatus.active_job_count}` : ""}.
                </span>
              ) : null}
            </Space>
          }
          closable
        />
      )}
      {runtimeStatus && !runtimeStatus.kill_switch_enabled && !runtimeStatus.workers_running && (
        <Alert
          type="warning"
          showIcon
          message="Worker Pool Not Running"
          description={
            <Space direction="vertical" size={4}>
              <span>Queued jobs are paused until workers are started. Scheduler control stays separate in CAASM Config.</span>
              {runtimeStatus.runtime_pressure_cap ? (
                <span>
                  Runtime cap {runtimeStatus.runtime_pressure_cap}
                  {runtimeStatus.active_job_count != null ? `, active now ${runtimeStatus.active_job_count}` : ""}.
                </span>
              ) : null}
            </Space>
          }
          action={
            <Button size="small" type="primary" onClick={handleStartWorkersFromBanner} loading={checkingRuntime}>
              Start Workers
            </Button>
          }
          closable
        />
      )}
      {runtimeStatus && !runtimeStatus.kill_switch_enabled && runtimeStatus.scheduler_running === false && (
        <Alert
          type="info"
          showIcon
          message="Scheduler Stopped, Manual Mode Active"
          description={
            <Space direction="vertical" size={4}>
              <span>Scheduled syncs are paused. Manual sync from Cloud Accounts is still available.</span>
            </Space>
          }
          closable
        />
      )}
      <Card>
        <Space direction="vertical" size={8}>
          <Title level={3} style={{ margin: 0 }}>
            Sync jobs
          </Title>
          <Paragraph type="secondary" style={{ marginBottom: 0 }}>
            Monitor collector runs, manual syncs, and cleanup progress. Runtime details and pressure controls are summarized below.
          </Paragraph>
        </Space>
      </Card>

      {runtimeStatus && (
        <Card size="small" title="Runtime coordination">
          <Space size={[8, 8]} wrap>
            <Tag color="blue">Mode: {runtimeStatus.coordination_mode || "db_backed"}</Tag>
            <Tag color={runtimeStatus.pressure_state === "at_capacity" ? "red" : runtimeStatus.pressure_state === "active" ? "gold" : "green"}>
              Pressure: {runtimeStatus.pressure_state || "idle"}
            </Tag>
            <Tag color={runtimeStatus.scheduler_running ? "blue" : "gold"}>
              Scheduler: {runtimeStatus.scheduler_running ? "running" : "stopped"}
            </Tag>
            <Tag color="purple">Worker limit: {runtimeStatus.worker_limit ?? "—"}</Tag>
            <Tag color="geekblue">Runtime cap: {runtimeStatus.runtime_pressure_cap ?? "—"}</Tag>
            <Tag color="cyan">Active jobs: {runtimeStatus.active_job_count ?? "—"}</Tag>
            <Tag color="default">Cap source: {runtimeStatus.runtime_limit_source || "worker_pool_default"}</Tag>
          </Space>
        </Card>
      )}

      <Card title="Filter" style={{ marginBottom: 24 }}>
        <Form layout="vertical">
          <Row gutter={16} align="bottom">
            <Col span={5}>
              <Form.Item label="Status" style={{ marginBottom: 0 }}>
                <Select
                  allowClear
                  style={{ width: "100%" }}
                  options={statusOptions}
                  value={filters.status}
                  onChange={(value) => onFilterChange("status", value)}
                  placeholder="All Statuses"
                />
              </Form.Item>
            </Col>
            <Col span={5}>
              <Form.Item label="Job type" style={{ marginBottom: 0 }}>
                <Select
                  allowClear
                  style={{ width: "100%" }}
                  options={jobTypeOptions}
                  value={filters.job_type}
                  onChange={(value) => onFilterChange("job_type", value)}
                  placeholder="All Types"
                />
              </Form.Item>
            </Col>
            <Col span={5}>
              <Form.Item label="Execution Mode" style={{ marginBottom: 0 }}>
                <Select
                  allowClear
                  style={{ width: "100%" }}
                  options={executionModeOptions}
                  value={filters.execution_mode}
                  onChange={(value) => onFilterChange("execution_mode", value)}
                  placeholder="All Modes"
                />
              </Form.Item>
            </Col>
            <Col span={5}>
              <Form.Item label="Cloud account ID" style={{ marginBottom: 0 }}>
                <InputNumber
                  style={{ width: "100%" }}
                  value={filters.cloud_account_id}
                  onChange={(value) => onFilterChange("cloud_account_id", value ?? null)}
                  placeholder="ID"
                />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item style={{ marginBottom: 0 }}>
                <Button
                  block
                  onClick={() => {
                    setFilters({
                      status: undefined,
                      job_type: undefined,
                      cloud_account_id: undefined,
                      execution_mode: undefined,
                    });
                    setPagination((prev) => ({ ...prev, current: 1 }));
                  }}
                >
                  Clear
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card title="Job List">
        <Table
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={records}
          pagination={{ ...pagination }}
          onChange={handleTableChange}
          scroll={{ x: 1400 }}
        />
      </Card>

      <Drawer
        title={`Job #${selectedJob?.id} Logs`}
        placement="right"
        width={700}
        onClose={onCloseDrawer}
        open={drawerVisible}
        destroyOnHidden
        afterOpenChange={handleDrawerOpenChange}
      >
        {selectedJobState && (
          <Alert
            type={selectedJobState.tone}
            showIcon
            message={selectedJobState.label}
            description={selectedJobState.detail}
            style={{ marginBottom: 16 }}
          />
        )}
        {selectedJob && selectedJobSummaryTokens.length > 0 && (
          <Card size="small" title="Job summary" style={{ marginBottom: 16 }}>
            <Space size={[6, 6]} wrap>
              {selectedJobSummaryTokens.map((token) => (
                <Tooltip key={`job-summary-${token.label}-${token.value}`} title={token.tooltip || `${token.label}: ${token.value}`}>
                  <Tag color={token.color} style={{ maxWidth: 320 }}>
                    {token.label}: {token.value}
                  </Tag>
                </Tooltip>
              ))}
            </Space>
          </Card>
        )}
        {selectedJob && selectedJobStageTokens.length > 0 && (
          <Card size="small" title="Stage progress" style={{ marginBottom: 16 }}>
            <Space size={[6, 6]} wrap>
              {selectedJobStageTokens.map((token) => (
                <Tooltip key={`job-stage-${token.label}-${token.value}`} title={token.tooltip || `${token.label}: ${token.value}`}>
                  <Tag color={token.color} style={{ maxWidth: 320 }}>
                    {token.label}: {token.value}
                  </Tag>
                </Tooltip>
              ))}
            </Space>
          </Card>
        )}
        {eventsLoading ? (
          <div style={{ padding: "32px 0", textAlign: "center" }}>
            <Spin size="large" tip="Loading events..." />
          </div>
        ) : eventsError ? (
          <Alert
            type="error"
            showIcon
            message="Failed to load logs"
            description={eventsError}
            action={
              selectedJob ? (
                <Button type="primary" onClick={() => void loadEvents(selectedJob.id)}>
                  Retry
                </Button>
              ) : null
            }
          />
        ) : events.length === 0 ? (
          <Empty description="No logs available for this job." />
        ) : (
          <Space direction="vertical" size={16} style={{ width: "100%" }}>
            <Space size={[8, 8]} wrap>
              <Tag color="blue">Latest first</Tag>
              <Text type="secondary">
                Showing {events.length} log{events.length === 1 ? "" : "s"}
              </Text>
            </Space>
            <Timeline
              items={events.map((event) => ({
                color: event.type === "error" ? "red" : event.type === "warning" ? "orange" : "blue",
                children: (() => {
                  const telemetry = summarizeEventMetadata(event);
                  const isFailureEvent = event.type === "error" || event.type === "warning";
                  const detailsExpanded = expandedEventIds.includes(event.id);
                  return (
                    <div style={{ maxWidth: "100%", overflow: "hidden" }}>
                      <Space direction="vertical" size={10} style={{ width: "100%" }}>
                        {isFailureEvent ? (
                          <Alert
                            type={event.type === "error" ? "error" : "warning"}
                            showIcon
                            message={telemetry.category}
                            description="This event marks a failure or slowdown signal. The structured summary below surfaces the useful fields without requiring raw JSON scanning."
                          />
                        ) : null}
                        <div>
                          <Text strong style={{ display: "block", marginBottom: 4 }}>
                            {shortenText(event.message, 120)}
                          </Text>
                          <Text type="secondary" style={{ fontSize: 12, display: "block" }}>
                            {event.created_at}
                          </Text>
                        </div>

                        <Space size={[6, 6]} wrap>
                          <Tag color={event.type === "error" ? "red" : event.type === "warning" ? "orange" : "blue"}>{telemetry.category}</Tag>
                          {telemetry.tokens.map((token) => (
                            <Tooltip key={`${event.id}-${token.label}-${token.value}`} title={token.tooltip || `${token.label}: ${token.value}`}>
                              <Tag color={token.color} style={{ maxWidth: 260 }}>
                                {token.label}: {token.value}
                              </Tag>
                            </Tooltip>
                          ))}
                        </Space>
                        {telemetry.details.length > 0 ? (
                          <Space direction="vertical" size={8} style={{ width: "100%" }}>
                            <Button type="link" style={{ padding: 0, alignSelf: "flex-start" }} onClick={() => toggleEventDetails(event.id)}>
                              {detailsExpanded ? "Hide details" : "Show details"}
                            </Button>
                            {detailsExpanded ? (
                              <Card size="small" title="Structured metadata" styles={{ body: { padding: 12 } }}>
                                <Descriptions size="small" column={1} colon={false}>
                                  {telemetry.details.map((detail) => (
                                    <Descriptions.Item key={`${event.id}-${detail.label}`} label={detail.label}>
                                      <Tooltip title={detail.tooltip || detail.value}>
                                        <span>{detail.value}</span>
                                      </Tooltip>
                                    </Descriptions.Item>
                                  ))}
                                </Descriptions>
                              </Card>
                            ) : null}
                          </Space>
                        ) : null}
                      </Space>
                    </div>
                  );
                })(),
              }))}
            />
            {eventsHasMore ? (
              <div style={{ textAlign: "center" }}>
                <Button onClick={handleLoadOlderEvents} loading={eventsLoadingMore}>
                  Load older logs
                </Button>
              </div>
            ) : null}
          </Space>
        )}
      </Drawer>
    </Space>
  );
}
