import { Suspense } from "react"
import Link from "next/link"
import { notFound } from "next/navigation"
import {
  CheckCircle,
  Timer,
  DollarSign,
  Hash,
  Code as CodeIcon,
  GitFork,
  Terminal,
  AlertCircle,
  XCircle,
} from "lucide-react"
import { getCallSource } from "@/lib/observability-utils"
import { getTraceData } from "@/app/observability/lib/get-trace-data"
import { HelpButton } from "@/components/observability/help-button"
import { InfoIcon } from "@/components/observability/info-icon"
import { CopyButton } from "@/components/observability/copy-button"

interface TracePageProps {
  params: Promise<{
    trace_id: string
  }>
}

export default async function TracePage(props: TracePageProps) {
  return (
    <Suspense fallback={<TracePageSkeleton />}>
      <TracePageContent params={props.params} />
    </Suspense>
  )
}

function TracePageSkeleton() {
  return (
    <div className="container mx-auto p-6">
      <div className="mb-8">
        <div className="h-4 w-32 bg-gray-200 dark:bg-gray-700 rounded mb-4 animate-pulse" />
        <div className="h-8 w-64 bg-gray-200 dark:bg-gray-700 rounded mb-2 animate-pulse" />
        <div className="h-4 w-96 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" />
      </div>
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 border border-gray-200 dark:border-gray-700 mb-8">
        <div className="grid grid-cols-2 md:grid-cols-6 gap-6">
          {[1, 2, 3, 4, 5, 6].map(i => (
            <div key={i}>
              <div className="h-4 w-16 bg-gray-200 dark:bg-gray-700 rounded mb-2 animate-pulse" />
              <div className="h-7 w-20 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" />
            </div>
          ))}
        </div>
      </div>
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700 mb-8">
        <div className="p-6 border-b border-gray-200 dark:border-gray-700">
          <div className="h-6 w-32 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" />
        </div>
        <div className="p-4 space-y-3">
          {[1, 2, 3].map(i => (
            <div key={i} className="h-12 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" />
          ))}
        </div>
      </div>
    </div>
  )
}

async function TracePageContent({
  params: paramsPromise,
}: {
  params: Promise<{ trace_id: string }>
}) {
  const params = await paramsPromise
  const { trace_id } = params

  // Use prefix matching (first 33 chars) to group multi-model calls that share the same base trace_id
  const tracePrefix = trace_id.substring(0, 33)
  const { rawLlmCalls, errors, optimizationFeatures, optimizationEvent } =
    await getTraceData(tracePrefix)

  const traceSource = getCallSource(optimizationEvent?.event_type || null, null)

  // Extract optimization candidates from optimization_features
  // Also get the origin of each candidate (OPTIMIZE vs OPTIMIZE_LP) and model info
  const optimizationsOrigin =
    (optimizationFeatures?.optimizations_origin as Record<
      string,
      { source: string; model?: string }
    >) || {}

  const allCandidates = optimizationFeatures?.optimizations_post
    ? Object.entries(optimizationFeatures.optimizations_post as Record<string, string>).map(
        ([id, code]) => ({
          id,
          code: typeof code === "string" ? code : "",
          source: optimizationsOrigin[id]?.source || "OPTIMIZE",
          model: optimizationsOrigin[id]?.model,
        }),
      )
    : []

  // Filter candidates by source for display under the correct section
  const optimizationCandidates = allCandidates
    .filter(c => c.source === "OPTIMIZE")
    .map((c, index) => ({ ...c, index: index + 1 }))

  const lineProfilerCandidates = allCandidates
    .filter(c => c.source === "OPTIMIZE_LP")
    .map((c, index) => ({ ...c, index: index + 1 }))

  // Get explanations for candidates if available
  const candidateExplanations =
    (optimizationFeatures?.explanations_post as Record<string, string>) || {}

  // Best candidate (first in ranking) and whether it was used for PR
  const rankingData = optimizationFeatures?.ranking as {
    ranking?: string[]
    explanation?: string
  } | null
  const bestCandidateId = rankingData?.ranking?.[0] ?? null
  const pullRequestRaw = optimizationFeatures?.pull_request
  const usedForPr = Boolean(
    pullRequestRaw != null &&
    typeof pullRequestRaw === "object" &&
    !Array.isArray(pullRequestRaw) &&
    Object.keys(pullRequestRaw as Record<string, unknown>).length > 0,
  )

  // Map candidate ID to rank position (1-based, 1 = best)
  const candidateRankMap = new Map<string, number>()
  if (rankingData?.ranking) {
    rankingData.ranking.forEach((id, index) => {
      candidateRankMap.set(id, index + 1)
    })
  }

  // Sort by call_sequence from context if available, otherwise by created_at
  type LlmCall = {
    id: string
    trace_id: string | null
    call_type: string | null
    model_name: string | null
    status: string
    latency_ms: number | null
    llm_cost: number | null
    total_tokens: number | null
    created_at: Date
    context: unknown
  }

  const llmCalls = (rawLlmCalls as LlmCall[]).sort((a: LlmCall, b: LlmCall) => {
    const seqA = (a.context as { call_sequence?: number } | null)?.call_sequence ?? Infinity
    const seqB = (b.context as { call_sequence?: number } | null)?.call_sequence ?? Infinity
    if (seqA !== seqB) return seqA - seqB
    return new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
  })

  // If no data found, show 404
  if (llmCalls.length === 0 && errors.length === 0) {
    notFound()
  }

  // Calculate summary metrics
  const totalCost = llmCalls.reduce((sum: number, call: LlmCall) => sum + (call.llm_cost ?? 0), 0)
  const totalTokens = llmCalls.reduce(
    (sum: number, call: LlmCall) => sum + (call.total_tokens ?? 0),
    0,
  )
  const failedCalls = llmCalls.filter((c: LlmCall) => c.status === "failed").length

  // Calculate timeline data using Math.min/Math.max to handle out-of-order timestamps
  const timestamps = llmCalls.map((call: LlmCall) => new Date(call.created_at).getTime())
  const minTimestamp = timestamps.length > 0 ? Math.min(...timestamps) : 0
  const maxTimestamp = timestamps.length > 0 ? Math.max(...timestamps) : 0
  const totalDuration = maxTimestamp > minTimestamp ? (maxTimestamp - minTimestamp) / 1000 : 0

  // Status determination - check for partial_success, failed, or success
  const hasPartial = llmCalls.some((c: LlmCall) => c.status === "partial_success")
  const status = failedCalls > 0 ? "Failed" : hasPartial ? "Partial" : "Completed"
  const statusColor =
    failedCalls > 0
      ? "text-red-600 dark:text-red-400"
      : hasPartial
        ? "text-yellow-600 dark:text-yellow-400"
        : "text-green-600 dark:text-green-400"

  // Group calls by call_type
  const groupedCalls = llmCalls.reduce(
    (acc: Record<string, LlmCall[]>, call: LlmCall) => {
      const type = call.call_type || "unknown"
      if (!acc[type]) {
        acc[type] = []
      }
      acc[type].push(call)
      return acc
    },
    {} as Record<string, LlmCall[]>,
  )

  // Get call types in order of first appearance
  const orderedTypes = [...new Set(llmCalls.map((c: LlmCall) => c.call_type || "unknown"))]

  // Create a map of call_type to LLM call for candidate linking
  const callTypeToLlmCall = new Map<string, LlmCall>()
  llmCalls.forEach((call: LlmCall) => {
    if (call.call_type && !callTypeToLlmCall.has(call.call_type)) {
      callTypeToLlmCall.set(call.call_type, call)
    }
  })

  return (
    <div className="container mx-auto p-6">
      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 mb-4">
          <Link
            href="/observability/traces"
            className="hover:text-blue-600 dark:hover:text-blue-400"
          >
            Traces
          </Link>
          <span>/</span>
          <span className="text-gray-900 dark:text-white font-mono">
            {trace_id && trace_id.trim() ? `${trace_id.substring(0, 8)}...` : "N/A"}
          </span>
        </div>
        <div className="flex items-center justify-between gap-4">
          <div className="flex-1">
            <h2 className="text-2xl font-bold tracking-tight text-gray-900 dark:text-white mb-2">
              Trace Details
            </h2>
            <div className="flex items-center gap-2">
              <p className="text-gray-600 dark:text-gray-400 font-mono text-sm">
                {trace_id && trace_id.trim() ? trace_id : "Invalid Trace ID"}
              </p>
              {trace_id && trace_id.trim() && <CopyButton text={trace_id} label="trace ID" />}
            </div>
          </div>
          <HelpButton
            title="Trace Detail Page Guide"
            content={
              <div className="space-y-4 text-sm text-gray-700 dark:text-gray-300">
                <div>
                  <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                    Summary Metrics
                  </h4>
                  <p>
                    View key metrics including status, source, duration, cost, tokens, and number of
                    generated candidates for this optimization request.
                  </p>
                </div>
                <div>
                  <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                    LLM Calls Timeline
                  </h4>
                  <p>
                    All LLM API calls grouped by type. Expand each call to see detailed metrics
                    including tokens, latency, and timestamp. For optimization and line_profiler
                    types, candidates are displayed directly.
                  </p>
                </div>
                <div>
                  <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                    Generated Candidates
                  </h4>
                  <p>
                    Code optimization candidates generated during this trace. Each candidate
                    includes an explanation and the generated code. Use the copy button to copy
                    candidate code.
                  </p>
                </div>
                <div>
                  <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                    Error Handling
                  </h4>
                  <p>
                    If any errors occurred during optimization, they are displayed with severity
                    indicators, error messages, and detailed context for test failures.
                  </p>
                </div>
              </div>
            }
          />
        </div>
      </div>

      {/* Summary Card */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 border border-gray-200 dark:border-gray-700 mb-8">
        <div className="grid grid-cols-2 md:grid-cols-6 gap-6">
          <div>
            <div className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 font-medium mb-2">
              {status === "Completed" ? (
                <CheckCircle className="h-4 w-4" />
              ) : status === "Failed" ? (
                <XCircle className="h-4 w-4" />
              ) : (
                <AlertCircle className="h-4 w-4" />
              )}
              <span>Status</span>
              <InfoIcon content="Overall trace status based on all contained calls" side="top" />
            </div>
            <div className={`text-xl font-bold ${statusColor}`}>{status}</div>
          </div>
          <div>
            <div className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 font-medium mb-2">
              {traceSource.toLowerCase().includes("github") ? (
                <GitFork className="h-4 w-4" />
              ) : (
                <Terminal className="h-4 w-4" />
              )}
              <span>Source</span>
              <InfoIcon content="Where this optimization was triggered from" side="top" />
            </div>
            <div className="text-xl font-bold text-gray-900 dark:text-white">
              <span className="px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded text-sm">
                {traceSource}
              </span>
            </div>
          </div>
          <div>
            <div className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 font-medium mb-2">
              <Timer className="h-4 w-4" />
              <span>Duration</span>
              <InfoIcon content="Total time from first call to last call completion" side="top" />
            </div>
            <div className="text-xl font-bold text-gray-900 dark:text-white">
              {(totalDuration / 1000).toFixed(2)}s
            </div>
          </div>
          <div>
            <div className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 font-medium mb-2">
              <DollarSign className="h-4 w-4" />
              <span>Cost</span>
              <InfoIcon content="Sum of all LLM call costs in this trace" side="top" />
            </div>
            <div className="text-xl font-bold text-gray-900 dark:text-white">
              ${totalCost.toFixed(4)}
            </div>
          </div>
          <div>
            <div className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 font-medium mb-2">
              <Hash className="h-4 w-4" />
              <span>Tokens</span>
              <InfoIcon content="Total tokens (prompt + completion) across all calls" side="top" />
            </div>
            <div className="text-xl font-bold text-gray-900 dark:text-white">
              {totalTokens.toLocaleString()}
            </div>
          </div>
          <div>
            <div className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 font-medium mb-2">
              <CodeIcon className="h-4 w-4" />
              <span>Candidates</span>
              <InfoIcon content="Number of valid optimization candidates generated" side="top" />
            </div>
            <div className="text-xl font-bold text-gray-900 dark:text-white">
              {optimizationCandidates.length}
            </div>
          </div>
        </div>
      </div>

      {/* Unified LLM Calls View */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700 mb-8">
        <div className="p-6 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <h2 className="text-xl font-bold text-gray-900 dark:text-white">LLM Calls</h2>
              <span className="bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 text-sm px-2.5 py-0.5 rounded font-semibold">
                {llmCalls.length}
              </span>
            </div>
            <HelpButton
              title="LLM Calls Timeline"
              content={
                <div className="space-y-4 text-sm text-gray-700 dark:text-gray-300">
                  <div>
                    <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                      Call Sequence
                    </h4>
                    <p>
                      Calls are ordered by sequence number showing the execution order. Each call
                      displays its status, duration, cost, and model used.
                    </p>
                  </div>
                  <div>
                    <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                      Optimization & Line Profiler
                    </h4>
                    <p>
                      For these call types, generated candidates are displayed directly. Each
                      candidate includes the code and an explanation of the optimization.
                    </p>
                  </div>
                  <div>
                    <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                      Expanding Calls
                    </h4>
                    <p>
                      Click any call to expand and see detailed metrics including token usage,
                      latency, and timestamp. Use &quot;View full details&quot; to see prompts and
                      responses.
                    </p>
                  </div>
                </div>
              }
              size="sm"
            />
          </div>
        </div>
        <div className="divide-y divide-gray-200 dark:divide-gray-700">
          {orderedTypes.map(callType => {
            const calls = groupedCalls[callType]
            const isOptimizationType = callType === "optimization"
            const isLineProfilerType = callType === "line_profiler"

            // Get the candidates for this call type
            const candidatesForType = isOptimizationType
              ? optimizationCandidates
              : isLineProfilerType
                ? lineProfilerCandidates
                : []

            // For optimization/line_profiler types, only show candidates (not individual LLM calls)
            const showIndividualCalls = !isOptimizationType && !isLineProfilerType

            // Get the LLM call for this call type to link candidates
            const llmCallForType = callTypeToLlmCall.get(callType)

            return (
              <div key={callType} className="p-4">
                <div className="font-semibold text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                  {callType}
                  {candidatesForType.length > 0 && (
                    <span className="bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 text-xs px-2 py-0.5 rounded font-normal">
                      {candidatesForType.length} candidates
                    </span>
                  )}
                </div>
                {showIndividualCalls && (
                  <div className="space-y-2">
                    {calls.map((call, typeIndex) => {
                      const durationSec = ((call.latency_ms || 0) / 1000).toFixed(2)
                      const statusIcon = call.status === "success" ? "✓" : "✗"
                      const callStatusColor =
                        call.status === "success"
                          ? "text-green-600 dark:text-green-400"
                          : "text-red-600 dark:text-red-400"
                      const ctx = call.context as { call_sequence?: number } | null
                      const callSequence = ctx?.call_sequence

                      return (
                        <details
                          key={call.id}
                          className="group border border-gray-200 dark:border-gray-700 rounded-lg"
                        >
                          <summary className="p-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center justify-between rounded-lg">
                            <div className="flex items-center gap-3 text-sm">
                              <span className="font-mono text-gray-500 dark:text-gray-400 w-8">
                                {callSequence ? `#${callSequence}` : "-"}
                              </span>
                              <span className={`font-mono ${callStatusColor}`}>{statusIcon}</span>
                              <span className="font-medium text-gray-900 dark:text-white">
                                {calls.length > 1 ? `${callType} ${typeIndex + 1}` : callType}
                              </span>
                              <span className="text-gray-500 dark:text-gray-400">
                                {durationSec}s · ${(call.llm_cost || 0).toFixed(4)} ·{" "}
                                {call.model_name}
                              </span>
                            </div>
                            <span className="text-gray-400 group-open:rotate-180 transition-transform">
                              ▼
                            </span>
                          </summary>

                          <div className="px-4 pb-4 pt-2 border-t border-gray-200 dark:border-gray-700 mt-2">
                            {/* Call details */}
                            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-x-6 gap-y-3 text-sm">
                              <div className="flex flex-col">
                                <span className="text-gray-500 dark:text-gray-400 text-xs mb-1">
                                  Tokens
                                </span>
                                <span className="text-gray-900 dark:text-white font-medium">
                                  {call.total_tokens?.toLocaleString() ?? "N/A"}
                                </span>
                              </div>
                              <div className="flex flex-col">
                                <span className="text-gray-500 dark:text-gray-400 text-xs mb-1">
                                  Latency
                                </span>
                                <span className="text-gray-900 dark:text-white font-medium">
                                  {call.latency_ms ? `${call.latency_ms}ms` : "N/A"}
                                </span>
                              </div>
                              <div className="flex flex-col">
                                <span className="text-gray-500 dark:text-gray-400 text-xs mb-1">
                                  Time
                                </span>
                                <span className="text-gray-900 dark:text-white font-medium">
                                  {new Date(call.created_at).toLocaleTimeString()}
                                </span>
                              </div>
                              <div className="flex flex-col sm:col-span-2 lg:col-span-1">
                                <span className="text-gray-500 dark:text-gray-400 text-xs mb-1">
                                  Details
                                </span>
                                <Link
                                  href={`/observability/llm-call/${call.id}`}
                                  className="text-blue-600 dark:text-blue-400 hover:underline text-sm font-medium inline-block"
                                >
                                  View full details →
                                </Link>
                              </div>
                            </div>
                          </div>
                        </details>
                      )
                    })}
                  </div>
                )}
                {/* Show candidates for optimization/line_profiler types */}
                {candidatesForType.length > 0 && (
                  <div className={showIndividualCalls ? "mt-4 ml-4" : ""}>
                    <div className="flex items-center gap-2 mb-3">
                      <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300">
                        Generated Candidates
                      </h4>
                      <InfoIcon
                        content="Code optimization candidates generated from this call. Each includes an explanation and optimized code."
                        side="top"
                      />
                    </div>
                    <div className="space-y-2">
                      {candidatesForType.map(candidate => {
                        const isBest = bestCandidateId != null && candidate.id === bestCandidateId
                        const showUsedForPr = isBest && usedForPr
                        const rank = candidateRankMap.get(candidate.id)
                        return (
                          <details
                            key={candidate.id}
                            className={`rounded-lg border ${
                              isBest
                                ? "border-emerald-500 dark:border-emerald-600 bg-emerald-50/50 dark:bg-emerald-900/20"
                                : "border-gray-200 dark:border-gray-600"
                            }`}
                          >
                            <summary className="p-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center justify-between rounded-lg">
                              <div className="flex items-center gap-2 flex-wrap">
                                <span className="font-medium text-gray-900 dark:text-white">
                                  Candidate {candidate.index}
                                </span>
                                <span className="font-mono text-xs text-gray-500 dark:text-gray-400">
                                  {candidate.id.substring(0, 8)}...
                                </span>
                                {rank != null && (
                                  <span className="bg-indigo-100 dark:bg-indigo-900 text-indigo-800 dark:text-indigo-200 text-xs px-2 py-0.5 rounded font-semibold">
                                    Rank #{rank}
                                  </span>
                                )}
                                {isBest && (
                                  <span className="bg-emerald-100 dark:bg-emerald-900 text-emerald-800 dark:text-emerald-200 text-xs px-2 py-0.5 rounded font-semibold">
                                    Best
                                  </span>
                                )}
                                {showUsedForPr && (
                                  <span className="bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 text-xs px-2 py-0.5 rounded font-semibold">
                                    Used for PR
                                  </span>
                                )}
                                {candidate.model && (
                                  <span className="bg-purple-100 dark:bg-purple-900 text-purple-800 dark:text-purple-200 text-xs px-2 py-0.5 rounded">
                                    {candidate.model}
                                  </span>
                                )}
                              </div>
                              <span className="text-gray-400 text-sm">▼</span>
                            </summary>
                            <div className="p-3 pt-0 border-t border-gray-200 dark:border-gray-600 mt-2 space-y-3">
                              {candidateExplanations[candidate.id] && (
                                <div>
                                  <div className="flex items-center gap-1.5 mb-1">
                                    <CodeIcon className="h-3.5 w-3.5 text-gray-500 dark:text-gray-400" />
                                    <h5 className="text-xs font-medium text-gray-500 dark:text-gray-400">
                                      Explanation
                                    </h5>
                                  </div>
                                  <p className="text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap leading-relaxed">
                                    {candidateExplanations[candidate.id]}
                                  </p>
                                </div>
                              )}
                              <div>
                                <div className="flex items-center justify-between mb-2">
                                  <h5 className="text-xs font-medium text-gray-500 dark:text-gray-400">
                                    Code
                                  </h5>
                                  <CopyButton
                                    text={candidate.code}
                                    label="candidate code"
                                    size="sm"
                                  />
                                </div>
                                <pre className="bg-gray-900 text-gray-100 p-3 rounded-lg overflow-x-auto text-xs font-mono leading-relaxed">
                                  <code>{candidate.code}</code>
                                </pre>
                              </div>
                              {llmCallForType && (
                                <div>
                                  <Link
                                    href={`/observability/llm-call/${llmCallForType.id}`}
                                    className="text-blue-600 dark:text-blue-400 hover:underline text-sm font-medium inline-flex items-center gap-1"
                                  >
                                    View LLM Call Details →
                                  </Link>
                                </div>
                              )}
                            </div>
                          </details>
                        )
                      })}
                    </div>
                  </div>
                )}
              </div>
            )
          })}
        </div>
      </div>

      {/* Ranking explanation — shown when ranker ran */}
      {rankingData?.explanation && (
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700 mb-8">
          <div className="p-6 border-b border-gray-200 dark:border-gray-700">
            <div className="flex items-center gap-2">
              <h2 className="text-xl font-bold text-gray-900 dark:text-white">
                Ranking explanation
              </h2>
              <InfoIcon
                content="Explanation of why candidates were ranked in this order. Rank numbers are shown on each candidate card."
                side="top"
              />
            </div>
          </div>
          <div className="p-6">
            <p className="text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap leading-relaxed">
              {rankingData.explanation}
            </p>
          </div>
        </div>
      )}

      {/* Errors */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700 mb-8">
        <div className="p-6 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3">
            {errors.length > 0 ? (
              <>
                <AlertCircle className="h-5 w-5 text-red-600 dark:text-red-400" />
                <h2 className="text-xl font-bold text-red-600 dark:text-red-400">Errors</h2>
                <span className="bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 text-sm px-2.5 py-0.5 rounded font-semibold">
                  {errors.length}
                </span>
              </>
            ) : (
              <>
                <CheckCircle className="h-5 w-5 text-green-600 dark:text-green-400" />
                <h2 className="text-xl font-bold text-green-600 dark:text-green-400">
                  No Errors Detected
                </h2>
              </>
            )}
          </div>
        </div>
        {errors.length > 0 ? (
          <div className="divide-y divide-gray-200 dark:divide-gray-700">
            {(
              errors as Array<{
                id: string
                error_type: string | null
                severity: string | null
                error_message: string | null
                context: unknown
                created_at: Date
              }>
            ).map(error => {
              const isTestFailure = error.error_type === "test_failure"
              const errorContext = error.context as {
                test_name?: string
                failure_reason?: string
                test_output?: string
                expected?: string
                actual?: string
              } | null

              return (
                <div key={error.id} className="p-6 border-l-4 border-red-500">
                  <div className="flex items-start gap-3">
                    {error.severity === "error" ? (
                      <XCircle className="h-6 w-6 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
                    ) : (
                      <AlertCircle className="h-6 w-6 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" />
                    )}
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <span className="font-semibold text-gray-900 dark:text-white text-base">
                          {error.error_type}
                        </span>
                        <span
                          className={`px-2 py-1 text-xs font-semibold rounded ${
                            error.severity === "error"
                              ? "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300"
                              : "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300"
                          }`}
                        >
                          {error.severity}
                        </span>
                        <span className="text-xs text-gray-500 dark:text-gray-400 ml-auto">
                          {new Date(error.created_at).toLocaleString()}
                        </span>
                      </div>
                      <div className="flex items-start gap-2 mb-3">
                        <p className="text-sm text-gray-700 dark:text-gray-300 flex-1">
                          {error.error_message}
                        </p>
                        <CopyButton
                          text={error.error_message ?? ""}
                          label="error message"
                          size="sm"
                        />
                      </div>
                      {/* Test Failure Details */}
                      {isTestFailure && errorContext && (
                        <div className="mt-3 p-3 bg-red-50 dark:bg-red-900/20 rounded-lg border border-red-200 dark:border-red-800">
                          <h4 className="text-sm font-semibold text-red-800 dark:text-red-300 mb-2">
                            Test Failure Details
                          </h4>
                          {errorContext.test_name && (
                            <div className="mb-2">
                              <span className="text-xs font-medium text-gray-600 dark:text-gray-400">
                                Test:
                              </span>{" "}
                              <span className="text-sm text-gray-900 dark:text-white font-mono">
                                {errorContext.test_name}
                              </span>
                            </div>
                          )}
                          {errorContext.failure_reason && (
                            <div className="mb-2">
                              <span className="text-xs font-medium text-gray-600 dark:text-gray-400">
                                Reason:
                              </span>
                              <p className="text-sm text-gray-900 dark:text-white mt-1 whitespace-pre-wrap">
                                {errorContext.failure_reason}
                              </p>
                            </div>
                          )}
                          {errorContext.expected && (
                            <div className="mb-2">
                              <span className="text-xs font-medium text-gray-600 dark:text-gray-400">
                                Expected:
                              </span>
                              <pre className="text-xs text-gray-900 dark:text-white mt-1 bg-white dark:bg-gray-800 p-2 rounded overflow-x-auto">
                                {String(errorContext.expected)}
                              </pre>
                            </div>
                          )}
                          {errorContext.actual && (
                            <div className="mb-2">
                              <span className="text-xs font-medium text-gray-600 dark:text-gray-400">
                                Actual:
                              </span>
                              <pre className="text-xs text-gray-900 dark:text-white mt-1 bg-white dark:bg-gray-800 p-2 rounded overflow-x-auto">
                                {String(errorContext.actual)}
                              </pre>
                            </div>
                          )}
                          {errorContext.test_output && (
                            <div>
                              <span className="text-xs font-medium text-gray-600 dark:text-gray-400">
                                Test Output:
                              </span>
                              <pre className="text-xs text-gray-900 dark:text-white mt-1 bg-white dark:bg-gray-800 p-2 rounded overflow-x-auto whitespace-pre-wrap">
                                {String(errorContext.test_output)}
                              </pre>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center py-12 text-center">
            <CheckCircle className="h-16 w-16 text-green-500 dark:text-green-400 mb-4" />
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">All Clear!</h3>
            <p className="text-gray-500 dark:text-gray-400 text-sm">
              This trace completed successfully with no errors detected.
            </p>
          </div>
        )}
      </div>
    </div>
  )
}
