import Link from "next/link"
import { Metadata } from "next"
import { cacheLife } from "next/cache"
import { Award, Database as DatabaseIcon, GitFork, Terminal } from "lucide-react"
import { Prisma } from "@prisma/client"
import { prisma } from "@/lib/prisma"
import { getCallSource } from "@/lib/observability-utils"
import { HelpButton } from "@/components/observability/help-button"
import { StatCard } from "@/components/observability/stat-card"
import { ColumnHeader } from "@/components/observability/column-header"
import { InfoIcon } from "@/components/observability/info-icon"

export const metadata: Metadata = {
  title: "LLM Calls - Observability",
  description: "View all LLM API calls for prompt engineering analysis",
}

interface SearchParams {
  call_type?: string
  model?: string
  status?: string
  trace_id?: string
  page?: string
  organization?: string
}

async function getUniqueOrganizations() {
  "use cache"
  cacheLife({ stale: 60, revalidate: 300, expire: 1800 })

  const result = await prisma.$queryRaw<Array<{ organization: string }>>`
    SELECT DISTINCT organization
    FROM optimization_features
    WHERE organization IS NOT NULL
    ORDER BY organization ASC
  `
  return result.map((r: { organization: string }) => r.organization)
}

async function getOrgTraceIds(organization: string) {
  "use cache"
  cacheLife("frequent")

  const orgFeatures = await prisma.optimization_features.findMany({
    where: { organization },
    select: { trace_id: true },
    distinct: ["trace_id"],
  })
  return orgFeatures.map((f: { trace_id: string }) => f.trace_id).filter(Boolean) as string[]
}

async function getCallTypes() {
  "use cache"
  cacheLife({ stale: 60, revalidate: 300, expire: 1800 })

  const result = await prisma.$queryRaw<Array<{ call_type: string }>>`
    SELECT DISTINCT call_type
    FROM llm_calls
    WHERE call_type IS NOT NULL
    ORDER BY call_type ASC
  `
  return result.map(r => ({ call_type: r.call_type }))
}

async function getModels() {
  "use cache"
  cacheLife({ stale: 60, revalidate: 300, expire: 1800 })

  const result = await prisma.$queryRaw<Array<{ model_name: string }>>`
    SELECT DISTINCT model_name
    FROM llm_calls
    WHERE model_name IS NOT NULL
    ORDER BY model_name ASC
  `
  return result.map(r => ({ model_name: r.model_name }))
}

async function fetchLLMCallsData(
  callType: string | undefined,
  model: string | undefined,
  status: string | undefined,
  traceId: string | undefined,
  organization: string | undefined,
  page: number,
) {
  "use cache"
  cacheLife({ stale: 15, revalidate: 60, expire: 300 })

  const pageSize = 50
  const skip = (page - 1) * pageSize

  // Resolve org trace IDs (inner call is itself cached)
  let filteredTraceIds: string[] = []
  if (organization) {
    filteredTraceIds = await getOrgTraceIds(organization)
    if (filteredTraceIds.length === 0) return null
  }

  // Build Prisma where clause
  type WhereClause = {
    call_type?: string
    model_name?: { contains: string }
    status?: string
    trace_id?: { startsWith: string } | { in: string[] }
  }
  const where: WhereClause = {}
  if (callType) where.call_type = callType
  if (model) where.model_name = { contains: model }
  if (status) where.status = status
  if (traceId) {
    where.trace_id = { startsWith: traceId }
  } else if (filteredTraceIds.length > 0) {
    where.trace_id = { in: filteredTraceIds }
  }

  // Build safe Prisma.sql WHERE fragment for combined stats query (mirrors Prisma where)
  let statsWhere = Prisma.sql`TRUE`
  if (callType) {
    statsWhere = Prisma.sql`${statsWhere} AND call_type = ${callType}`
  }
  if (model) {
    statsWhere = Prisma.sql`${statsWhere} AND model_name LIKE ${"%" + model + "%"}`
  }
  if (status) {
    statsWhere = Prisma.sql`${statsWhere} AND status = ${status}`
  }
  if (traceId) {
    statsWhere = Prisma.sql`${statsWhere} AND trace_id LIKE ${traceId + "%"}`
  } else if (filteredTraceIds.length > 0) {
    statsWhere = Prisma.sql`${statsWhere} AND trace_id IN (${Prisma.join(filteredTraceIds)})`
  }

  // Round 1: LLM calls + combined stats in parallel
  const [llmCalls, statsResult] = await Promise.all([
    prisma.llm_calls.findMany({
      where,
      orderBy: { created_at: "desc" },
      take: pageSize,
      skip,
      select: {
        id: true,
        trace_id: true,
        call_type: true,
        model_name: true,
        status: true,
        parsing_status: true,
        candidates_generated: true,
        candidates_valid: true,
        prompt_tokens: true,
        completion_tokens: true,
        llm_cost: true,
        latency_ms: true,
        created_at: true,
        error_message: true,
        context: true,
      },
    }),
    prisma.$queryRaw<
      [
        {
          total_count: bigint
          success_count: bigint
          total_cost: number
          avg_latency: number | null
        },
      ]
    >`SELECT
        COUNT(*) as total_count,
        COUNT(*) FILTER (WHERE status = 'success') as success_count,
        COALESCE(SUM(llm_cost), 0) as total_cost,
        AVG(latency_ms) as avg_latency
      FROM llm_calls
      WHERE ${statsWhere}`,
  ])
  const totalCount = Number(statsResult[0].total_count)

  // Round 2: optimization features/events for current page's trace IDs
  const traceIds = llmCalls.map(call => call.trace_id).filter(Boolean) as string[]
  const uniqueTraceIdPrefixes = Array.from(new Set(traceIds.map(id => id.substring(0, 36))))
  const [optimizationFeatures, optimizationEvents] = await Promise.all([
    uniqueTraceIdPrefixes.length > 0
      ? prisma.optimization_features.findMany({
          where: { trace_id: { in: uniqueTraceIdPrefixes } },
          select: { trace_id: true, organization: true, ranking: true },
        })
      : [],
    uniqueTraceIdPrefixes.length > 0
      ? prisma.optimization_events.findMany({
          where: { trace_id: { in: uniqueTraceIdPrefixes } },
          select: { trace_id: true, event_type: true },
          distinct: ["trace_id"],
        })
      : [],
  ])

  return {
    llmCalls,
    totalCount,
    successCount: Number(statsResult[0].success_count),
    totalCost: Number(statsResult[0].total_cost),
    avgLatency: Number(statsResult[0].avg_latency ?? 0),
    totalPages: Math.ceil(totalCount / pageSize),
    optimizationFeatures: optimizationFeatures as Array<{
      trace_id: string
      organization: string | null
      ranking: unknown
    }>,
    optimizationEvents: optimizationEvents as Array<{
      trace_id: string | null
      event_type: string
    }>,
  }
}

export default async function LLMCallsPage(props: { searchParams: Promise<SearchParams> }) {
  const searchParams = await props.searchParams
  try {
    const page = parseInt(searchParams.page || "1")

    // Fetch all data in parallel — dropdowns are individually cached,
    // main data fetch is cached as a unit keyed by search params
    const [uniqueOrganizations, callTypes, models, data] = await Promise.all([
      getUniqueOrganizations(),
      getCallTypes(),
      getModels(),
      fetchLLMCallsData(
        searchParams.call_type,
        searchParams.model,
        searchParams.status,
        searchParams.trace_id,
        searchParams.organization,
        page,
      ),
    ])

    // If organization filter matched no traces, show empty state
    if (!data) {
      return (
        <div className="container mx-auto px-4 py-8">
          <div className="mb-6">
            {/* Title and Search Bar on Same Line */}
            <div className="flex items-center justify-between gap-4 mb-2">
              <h1 className="text-3xl font-bold text-gray-900 dark:text-white whitespace-nowrap">
                LLM Calls
              </h1>
              {/* Compact Search Bar */}
              <form method="get" className="flex items-center gap-2 flex-1 max-w-xl">
                <input
                  type="text"
                  name="trace_id"
                  placeholder="Search by Trace ID..."
                  defaultValue={searchParams.trace_id || ""}
                  className="flex-1 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400"
                />
                <button
                  type="submit"
                  className="px-4 py-2 text-sm bg-blue-600 dark:bg-blue-700 text-white rounded hover:bg-blue-700 dark:hover:bg-blue-600 whitespace-nowrap"
                >
                  Search
                </button>
                {searchParams.trace_id && (
                  <Link
                    href="/observability/llm-calls"
                    className="px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-900 dark:text-gray-100 whitespace-nowrap"
                  >
                    Clear
                  </Link>
                )}
              </form>
            </div>
            <p className="text-gray-600 dark:text-gray-400">
              Track and analyze all LLM API calls for prompt engineering
            </p>
          </div>

          {/* Filters */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4 mb-6 border border-gray-200 dark:border-gray-700">
            <form method="get" className="flex flex-wrap gap-4">
              <div>
                <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">
                  Call Type
                </label>
                <select
                  name="call_type"
                  className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                  defaultValue={searchParams.call_type || ""}
                >
                  <option value="">All</option>
                  {callTypes.map((ct: { call_type: string | null }) => (
                    <option key={ct.call_type!} value={ct.call_type!}>
                      {ct.call_type}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">
                  Model
                </label>
                <select
                  name="model"
                  className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                  defaultValue={searchParams.model || ""}
                >
                  <option value="">All</option>
                  {models.map((m: { model_name: string | null }) => (
                    <option key={m.model_name!} value={m.model_name!}>
                      {m.model_name}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">
                  Status
                </label>
                <select
                  name="status"
                  className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                  defaultValue={searchParams.status || ""}
                >
                  <option value="">All</option>
                  <option value="success">Success</option>
                  <option value="partial_success">Partial</option>
                  <option value="failed">Failed</option>
                  <option value="in_progress">In Progress</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">
                  Organization
                </label>
                <select
                  name="organization"
                  className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                  defaultValue={searchParams.organization || ""}
                >
                  <option value="">All Organizations</option>
                  {uniqueOrganizations.map(org => (
                    <option key={org} value={org}>
                      {org}
                    </option>
                  ))}
                </select>
              </div>

              <div className="flex items-end">
                <button
                  type="submit"
                  className="px-4 py-2 bg-blue-600 dark:bg-blue-700 text-white rounded hover:bg-blue-700 dark:hover:bg-blue-600"
                >
                  Filter
                </button>
              </div>
            </form>
          </div>

          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-12 text-center border border-gray-200 dark:border-gray-700">
            <p className="text-gray-500 dark:text-gray-400">
              No LLM calls found for organization &quot;{searchParams.organization}&quot;.
            </p>
          </div>
        </div>
      )
    }

    const {
      llmCalls,
      totalCount,
      successCount,
      totalCost,
      avgLatency,
      totalPages,
      optimizationFeatures,
      optimizationEvents,
    } = data

    // Build lookup maps from cached arrays (cheap in-memory iteration)
    const traceIdToEventType = new Map<string, string>()
    optimizationEvents.forEach(event => {
      if (event.trace_id) traceIdToEventType.set(event.trace_id, event.event_type)
    })
    const traceIdToOrganization = new Map<string, string>()
    optimizationFeatures.forEach(feature => {
      if (feature.trace_id && feature.organization) {
        traceIdToOrganization.set(feature.trace_id, feature.organization)
      }
    })
    const traceIdsWithBest = new Set(
      optimizationFeatures
        .filter(f => f.trace_id && (f.ranking as { ranking?: string[] } | null)?.ranking?.[0])
        .map(f => f.trace_id.substring(0, 36)),
    )

    return (
      <div className="container mx-auto px-4 py-8">
        <div className="mb-8">
          {/* Title, Search Bar, and Help Button */}
          <div className="flex items-center justify-between gap-4 mb-2">
            <div className="flex items-center gap-3">
              <h1 className="text-3xl font-bold tracking-tight text-gray-900 dark:text-white whitespace-nowrap">
                LLM Calls
              </h1>
              <HelpButton
                title="Understanding LLM Calls"
                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">
                        What is an LLM call?
                      </h4>
                      <p>
                        Each individual API request to an AI model (like GPT-4, Claude, etc.) for
                        generating code optimizations, validations, or other tasks.
                      </p>
                    </div>
                    <div>
                      <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                        Call sequence (#)
                      </h4>
                      <p>
                        Shows the order of calls within a trace. Multiple calls may be part of the
                        same optimization request.
                      </p>
                    </div>
                    <div>
                      <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                        Call types
                      </h4>
                      <ul className="list-disc list-inside space-y-1 ml-2">
                        <li>
                          <strong>optimization:</strong> Generates optimized code
                        </li>
                        <li>
                          <strong>validation:</strong> Checks quality of generated code
                        </li>
                        <li>
                          <strong>line_profiler:</strong> Analyzes performance bottlenecks
                        </li>
                      </ul>
                    </div>
                    <div>
                      <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                        Parsing status
                      </h4>
                      <p>
                        Indicates whether the model&apos;s response was successfully parsed and
                        extracted into usable code candidates.
                      </p>
                    </div>
                  </div>
                }
              />
            </div>
            {/* Compact Search Bar */}
            <form method="get" className="flex items-center gap-2 flex-1 max-w-xl">
              <input
                type="text"
                name="trace_id"
                placeholder="Search by Trace ID..."
                defaultValue={searchParams.trace_id || ""}
                className="flex-1 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-shadow"
              />
              <button
                type="submit"
                className="px-4 py-2 text-sm bg-blue-600 dark:bg-blue-700 text-white rounded hover:bg-blue-700 dark:hover:bg-blue-600 whitespace-nowrap"
              >
                Search
              </button>
              {searchParams.trace_id && (
                <Link
                  href="/observability/llm-calls"
                  className="px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-900 dark:text-gray-100 whitespace-nowrap"
                >
                  Clear
                </Link>
              )}
            </form>
          </div>
          <p className="text-gray-600 dark:text-gray-400">
            Track and analyze all LLM API calls for prompt engineering
          </p>
        </div>

        {/* Filters */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-5 mb-8 border border-gray-200 dark:border-gray-700 hover:shadow-md transition-shadow">
          <form method="get" className="flex flex-wrap gap-4">
            <div>
              <label className="flex items-center gap-1.5 text-sm font-semibold mb-1 text-gray-700 dark:text-gray-300">
                Call Type
                <InfoIcon
                  content="Type of operation: optimization generates code, validation checks quality, etc."
                  side="top"
                />
              </label>
              <select
                name="call_type"
                className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                defaultValue={searchParams.call_type || ""}
              >
                <option value="">All</option>
                {callTypes.map((ct: { call_type: string | null }) => (
                  <option key={ct.call_type!} value={ct.call_type!}>
                    {ct.call_type}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="flex items-center gap-1.5 text-sm font-semibold mb-1 text-gray-700 dark:text-gray-300">
                Model
                <InfoIcon content="AI model used (e.g., gpt-4, claude-3, etc.)" side="top" />
              </label>
              <select
                name="model"
                className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                defaultValue={searchParams.model || ""}
              >
                <option value="">All</option>
                {models.map((m: { model_name: string | null }) => (
                  <option key={m.model_name!} value={m.model_name!}>
                    {m.model_name}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="flex items-center gap-1.5 text-sm font-semibold mb-1 text-gray-700 dark:text-gray-300">
                Status
                <InfoIcon
                  content="success = completed normally, failed = error occurred, partial = incomplete results"
                  side="top"
                />
              </label>
              <select
                name="status"
                className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                defaultValue={searchParams.status || ""}
              >
                <option value="">All</option>
                <option value="success">Success</option>
                <option value="partial_success">Partial</option>
                <option value="failed">Failed</option>
                <option value="in_progress">In Progress</option>
              </select>
            </div>

            <div>
              <label className="flex items-center gap-1.5 text-sm font-semibold mb-1 text-gray-700 dark:text-gray-300">
                Organization
                <InfoIcon content="Organization that made the request" side="top" />
              </label>
              <select
                name="organization"
                className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                defaultValue={searchParams.organization || ""}
              >
                <option value="">All Organizations</option>
                {uniqueOrganizations.map(org => (
                  <option key={org} value={org}>
                    {org}
                  </option>
                ))}
              </select>
            </div>

            <div className="flex items-end gap-2">
              <button
                type="submit"
                className="px-4 py-2 bg-blue-600 dark:bg-blue-700 text-white rounded hover:bg-blue-700 dark:hover:bg-blue-600 focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
              >
                Filter
              </button>
              {(searchParams.call_type ||
                searchParams.model ||
                searchParams.status ||
                searchParams.organization) && (
                <Link
                  href="/observability/llm-calls"
                  className="px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-900 dark:text-gray-100"
                >
                  Clear All
                </Link>
              )}
            </div>
          </form>
        </div>

        {/* Stats Summary */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-5 mb-8">
          <StatCard
            label="Total Calls"
            value={totalCount}
            helpText="Total number of LLM API calls matching your filters (across all pages)"
            icon="Activity"
          />
          <StatCard
            label="Success Rate"
            value={`${totalCount > 0 ? Math.round((successCount / totalCount) * 100) : 0}%`}
            helpText="Percentage of successful calls vs total calls. Excludes in-progress calls."
            icon="CheckCircle2"
            variant="success"
          />
          <StatCard
            label="Total Cost"
            value={`$${totalCost.toFixed(3)}`}
            helpText="Cumulative cost of all calls matching filters. Based on model pricing."
            icon="DollarSign"
          />
          <StatCard
            label="Avg Latency"
            value={`${avgLatency ? Math.round(avgLatency) : 0}ms`}
            helpText="Average time taken for LLM API to respond. Excludes network latency."
            icon="Clock"
          />
        </div>

        {/* LLM Calls Table */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden border border-gray-200 dark:border-gray-700">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
              <thead className="bg-gray-50 dark:bg-gray-900">
                <tr>
                  <ColumnHeader
                    label="#"
                    tooltip="Call sequence number within the trace. Shows execution order."
                    className="px-3 py-3"
                  />
                  <ColumnHeader
                    label="Timestamp"
                    tooltip="When this API call was made. Click to see full details."
                  />
                  <ColumnHeader
                    label="Trace ID"
                    tooltip="Parent trace containing this call. Click to view all calls in trace."
                  />
                  <ColumnHeader label="Organization" tooltip="Organization from trace metadata" />
                  <ColumnHeader
                    label="Type"
                    tooltip="Call type: what this LLM operation was attempting"
                  />
                  <ColumnHeader
                    label="Source"
                    tooltip="Origin of request: GitHub Action, CLI, VSCode extension, etc."
                  />
                  <ColumnHeader label="Model" tooltip="AI model used for this call" />
                  <ColumnHeader
                    label="Status"
                    tooltip="Call outcome: success, failed, partial_success, or in_progress"
                  />
                  <ColumnHeader
                    label="Tokens"
                    tooltip="Total tokens (prompt + completion) used in this call"
                  />
                  <ColumnHeader label="Cost" tooltip="Cost in USD for this specific call" />
                  <ColumnHeader label="Latency" tooltip="API response time in milliseconds" />
                  <ColumnHeader
                    label="Candidates"
                    tooltip="Valid candidates / Total generated. For optimization calls only."
                  />
                </tr>
              </thead>
              <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                {llmCalls.map(
                  (call: {
                    id: string
                    trace_id: string | null
                    call_type: string | null
                    model_name: string | null
                    status: string | null
                    parsing_status: string | null
                    candidates_generated: number | null
                    candidates_valid: number | null
                    prompt_tokens: number | null
                    completion_tokens: number | null
                    llm_cost: number | null
                    latency_ms: number | null
                    created_at: Date
                    error_message: string | null
                    context: unknown
                  }) => {
                    const ctx = call.context as { call_sequence?: number } | null
                    const callSequence = ctx?.call_sequence
                    const traceIdPrefix = call.trace_id?.substring(0, 36) || ""
                    const eventType = traceIdPrefix
                      ? traceIdToEventType.get(traceIdPrefix) || null
                      : null
                    const organization = traceIdPrefix
                      ? traceIdToOrganization.get(traceIdPrefix)
                      : null
                    const source = getCallSource(
                      eventType,
                      call.context as Record<string, unknown> | null,
                    )
                    const isBestOptimizationCall =
                      call.call_type === "optimization" && traceIdsWithBest.has(traceIdPrefix)
                    return (
                      <tr
                        key={call.id}
                        className="hover:bg-gray-50 dark:hover:bg-gray-700/50 hover:shadow-md transition-all duration-200"
                      >
                        <td className="px-3 py-5 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400 font-mono">
                          {callSequence ? `#${callSequence}` : "-"}
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm">
                          <Link
                            href={`/observability/llm-call/${call.id}`}
                            className="text-blue-600 dark:text-blue-400 hover:underline"
                          >
                            {new Date(call.created_at).toLocaleString()}
                          </Link>
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm">
                          {call.trace_id && call.trace_id.trim() ? (
                            <Link
                              href={`/observability/trace/${call.trace_id}`}
                              className="text-purple-600 dark:text-purple-400 hover:underline font-mono text-xs"
                            >
                              {call.trace_id.substring(0, 8)}...
                            </Link>
                          ) : (
                            <span className="text-gray-400 dark:text-gray-500 font-mono text-xs">
                              N/A
                            </span>
                          )}
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                          {organization || "N/A"}
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm">
                          <span className="inline-flex items-center gap-1.5">
                            <span className="px-2 py-1 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded">
                              {call.call_type}
                            </span>
                            {isBestOptimizationCall && (
                              <span
                                className="inline-flex items-center gap-1 px-2 py-0.5 bg-amber-100 dark:bg-amber-900 text-amber-800 dark:text-amber-200 rounded text-xs font-semibold"
                                title="Optimization that produced the chosen candidate for this trace"
                              >
                                <Award className="h-3.5 w-3.5" />
                                Best
                              </span>
                            )}
                          </span>
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm">
                          <span className="inline-flex items-center gap-1.5 px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded text-xs">
                            {source.toLowerCase().includes("github") ? (
                              <GitFork className="h-3 w-3" />
                            ) : source.toLowerCase().includes("vscode") ||
                              source.toLowerCase().includes("cli") ? (
                              <Terminal className="h-3 w-3" />
                            ) : null}
                            {source}
                          </span>
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                          {call.model_name}
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm">
                          <span
                            className={`px-2 py-1 rounded ${
                              call.status === "success"
                                ? "bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200"
                                : call.status === "failed"
                                  ? "bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200"
                                  : "bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200"
                            }`}
                          >
                            {call.status}
                          </span>
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                          {call.prompt_tokens && call.completion_tokens
                            ? `${call.prompt_tokens + call.completion_tokens}`
                            : "-"}
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                          {call.llm_cost ? `$${call.llm_cost.toFixed(4)}` : "-"}
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                          {call.latency_ms ? `${call.latency_ms}ms` : "-"}
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                          {call.candidates_valid}/{call.candidates_generated || 0}
                        </td>
                      </tr>
                    )
                  },
                )}
              </tbody>
            </table>
          </div>

          {llmCalls.length === 0 && (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <DatabaseIcon className="h-12 w-12 text-gray-400 dark:text-gray-500 mb-4" />
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                No LLM Calls Found
              </h3>
              {searchParams.call_type ||
              searchParams.model ||
              searchParams.status ||
              searchParams.organization ||
              searchParams.trace_id ? (
                <div className="space-y-3">
                  <p className="text-gray-500 dark:text-gray-400">
                    Try adjusting your filters above
                  </p>
                  <Link
                    href="/observability/llm-calls"
                    className="inline-flex items-center px-4 py-2 text-sm font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 border border-blue-200 dark:border-blue-800 rounded-md hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-colors"
                  >
                    Clear All Filters
                  </Link>
                </div>
              ) : (
                <div className="space-y-3">
                  <p className="text-gray-500 dark:text-gray-400">
                    Run the test script to generate sample data
                  </p>
                  <code className="block bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 px-4 py-2 rounded-md text-sm font-mono">
                    python django/aiservice/test_observability_local.py
                  </code>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="mt-6 flex justify-center gap-2">
            {page > 1 && (
              <Link
                href={`?page=${page - 1}${searchParams.call_type ? `&call_type=${searchParams.call_type}` : ""}${searchParams.model ? `&model=${searchParams.model}` : ""}${searchParams.status ? `&status=${searchParams.status}` : ""}${searchParams.organization ? `&organization=${searchParams.organization}` : ""}`}
                className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-900 dark:text-gray-100"
              >
                Previous
              </Link>
            )}
            <span className="px-4 py-2 text-gray-900 dark:text-gray-100">
              Page {page} of {totalPages}
            </span>
            {page < totalPages && (
              <Link
                href={`?page=${page + 1}${searchParams.call_type ? `&call_type=${searchParams.call_type}` : ""}${searchParams.model ? `&model=${searchParams.model}` : ""}${searchParams.status ? `&status=${searchParams.status}` : ""}${searchParams.organization ? `&organization=${searchParams.organization}` : ""}`}
                className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-900 dark:text-gray-100"
              >
                Next
              </Link>
            )}
          </div>
        )}
      </div>
    )
  } catch (error) {
    throw error
  }
}
