import { Suspense } from "react"
import Link from "next/link"
import { cacheLife, cacheTag } from "next/cache"
import { Search as SearchIcon } from "lucide-react"
import { Prisma } from "@prisma/client"
import { prisma } from "@/lib/prisma"
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"

interface SearchParams {
  trace_id?: string
  page?: string
  organization?: string
}

interface TraceSummaryRow {
  trace_id: string
  call_count: number
  total_cost: number
  total_tokens: bigint
  failed_calls: number
  has_partial: boolean
  call_types: string[]
  first_seen: Date
  last_seen: Date
}

// Organizations change infrequently — cache 5 min
// Rewritten as raw SQL to use the partial index on (organization WHERE organization IS NOT NULL)
async function getUniqueOrganizations() {
  "use cache"
  cacheLife({ stale: 60, revalidate: 300, expire: 1800 })
  cacheTag("observability:organizations")

  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)
}

// Trace IDs for an org — shared between count + main query
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[]
}

// COUNT from trace_summaries materialized view (refreshed every 5 min via pg_cron)
async function getTotalTracesCount(
  traceIdFilter: string | undefined,
  organizationFilter: string | undefined,
) {
  "use cache"
  cacheLife("frequent")

  let traceIdPrefixes: string[] = []
  if (organizationFilter) {
    traceIdPrefixes = await getOrgTraceIds(organizationFilter)
    if (traceIdPrefixes.length === 0) return 0
  }

  let whereClause = Prisma.empty
  if (traceIdFilter) {
    whereClause = Prisma.sql`WHERE trace_id LIKE ${`%${traceIdFilter}%`}`
  } else if (traceIdPrefixes.length > 0) {
    whereClause = Prisma.sql`WHERE trace_id IN (${Prisma.join(traceIdPrefixes)})`
  }

  const result = await prisma.$queryRaw<[{ count: bigint }]>`
    SELECT COUNT(*) as count FROM trace_summaries ${whereClause}
  `

  return Number(result[0].count)
}

// Paginated traces from trace_summaries materialized view (refreshed every 5 min via pg_cron).
// Returns pre-aggregated data — no GROUP BY on 1.4M rows needed.
async function getDistinctTraces(
  traceIdSearch: string | undefined,
  filteredTraceIds: string[],
  pageSize: number,
  skip: number,
): Promise<TraceSummaryRow[]> {
  "use cache"
  cacheLife("frequent")

  let whereClause = Prisma.empty
  if (traceIdSearch) {
    whereClause = Prisma.sql`WHERE trace_id LIKE ${`%${traceIdSearch}%`}`
  } else if (filteredTraceIds.length > 0) {
    whereClause = Prisma.sql`WHERE trace_id IN (${Prisma.join(filteredTraceIds)})`
  }

  return prisma.$queryRaw<TraceSummaryRow[]>`
    SELECT trace_id, call_count, total_cost, total_tokens, failed_calls,
           has_partial, call_types, first_seen, last_seen
    FROM trace_summaries
    ${whereClause}
    ORDER BY last_seen DESC
    LIMIT ${pageSize} OFFSET ${skip}
  `
}

export default async function TracesPage(props: { searchParams: Promise<SearchParams> }) {
  return (
    <Suspense fallback={<TracesPageSkeleton />}>
      <TracesPageContent searchParams={props.searchParams} />
    </Suspense>
  )
}

function TracesPageSkeleton() {
  return (
    <div className="container mx-auto p-6">
      <div className="mb-8">
        <div className="flex items-center justify-between gap-4 mb-2">
          <div className="h-8 w-32 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" />
          <div className="flex items-center gap-2 flex-1 max-w-2xl">
            <div className="flex-1 h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" />
            <div className="w-40 h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" />
            <div className="w-20 h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" />
          </div>
        </div>
        <div className="h-4 w-80 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mt-2" />
      </div>
      <div className="grid grid-cols-1 md:grid-cols-4 gap-5 mb-8">
        {[1, 2, 3, 4].map(i => (
          <div
            key={i}
            className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 border border-gray-200 dark:border-gray-700"
          >
            <div className="h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded mb-2 animate-pulse" />
            <div className="h-8 w-16 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" />
          </div>
        ))}
      </div>
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700">
        <div className="p-4 space-y-3">
          {[1, 2, 3, 4, 5].map(i => (
            <div key={i} className="h-12 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" />
          ))}
        </div>
      </div>
    </div>
  )
}

async function TracesPageContent({
  searchParams: searchParamsPromise,
}: {
  searchParams: Promise<SearchParams>
}) {
  const searchParams = await searchParamsPromise
  try {
    const page = parseInt(searchParams.page || "1")
    const pageSize = 50
    const skip = (page - 1) * pageSize

    // Get trace IDs filtered by organization if specified (uses shared cached function)
    let filteredTraceIds: string[] = []
    if (searchParams.organization) {
      filteredTraceIds = await getOrgTraceIds(searchParams.organization)

      // If organization filter is applied but no traces found, return empty result early
      if (filteredTraceIds.length === 0) {
        const orgs = await getUniqueOrganizations()

        // Return early with empty results
        return (
          <div className="container mx-auto p-6">
            {/* Header with search form */}
            <div className="mb-8">
              <div className="flex items-center justify-between gap-4 mb-2">
                <div className="flex items-center gap-3">
                  <h2 className="text-2xl font-bold tracking-tight text-gray-900 dark:text-white whitespace-nowrap">
                    All Traces
                  </h2>
                  <HelpButton
                    title="Understanding Traces"
                    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 a trace?
                          </h4>
                          <p>
                            A trace represents a complete optimization request from start to finish.
                            Each trace contains all the LLM API calls made during that optimization.
                          </p>
                        </div>
                        <div>
                          <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                            Multi-model traces
                          </h4>
                          <p>
                            When using multiple models for optimization, all calls share the same
                            base trace_id (first 33 characters). This helps track related operations
                            together.
                          </p>
                        </div>
                        <div>
                          <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                            Page sections
                          </h4>
                          <ul className="list-disc list-inside space-y-1 ml-2">
                            <li>
                              <strong>Summary Stats:</strong> Quick overview of trace metrics on
                              this page
                            </li>
                            <li>
                              <strong>Traces Table:</strong> Detailed list of all traces with
                              aggregated data
                            </li>
                            <li>
                              <strong>Filters:</strong> Search by trace ID or filter by organization
                            </li>
                          </ul>
                        </div>
                      </div>
                    }
                  />
                </div>
                <form method="get" className="flex items-center gap-2 flex-1 max-w-2xl">
                  <div className="flex-1 relative">
                    <input
                      type="text"
                      name="trace_id"
                      placeholder="Search by Trace ID..."
                      defaultValue={searchParams.trace_id || ""}
                      className="w-full 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"
                      title="Search by full or partial trace ID. Finds all related calls."
                    />
                  </div>
                  <div className="flex items-center gap-1.5">
                    <label
                      htmlFor="organization-filter-empty"
                      className="text-sm font-medium text-gray-700 dark:text-gray-300 whitespace-nowrap"
                    >
                      Organization
                    </label>
                    <InfoIcon
                      content="Filter by organization that initiated the optimization request"
                      side="top"
                    />
                  </div>
                  <select
                    id="organization-filter-empty"
                    name="organization"
                    defaultValue={searchParams.organization || ""}
                    className="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 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="">All Organizations</option>
                    {orgs.map((org: string) => (
                      <option key={org} value={org}>
                        {org}
                      </option>
                    ))}
                  </select>
                  <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>
                  <Link
                    href="/observability/traces"
                    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">
                View optimization request traces with aggregated metrics
              </p>
            </div>
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-16 text-center border border-gray-200 dark:border-gray-700">
              <div className="flex flex-col items-center justify-center space-y-4">
                <SearchIcon className="h-12 w-12 text-gray-400 dark:text-gray-500" />
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-1">
                    No Traces Found
                  </h3>
                  <p className="text-sm text-gray-500 dark:text-gray-400">
                    No traces found for organization &quot;{searchParams.organization}&quot;. Try
                    selecting a different organization.
                  </p>
                </div>
                <Link
                  href="/observability/llm-calls"
                  className="text-sm text-blue-600 dark:text-blue-400 hover:underline"
                >
                  View All LLM Calls →
                </Link>
              </div>
            </div>
          </div>
        )
      }
    }

    // All data comes from trace_summaries materialized view (refreshed every 5 min)
    // and optimization_features for org mapping — no raw llm_calls scan needed.
    const [traceSummaries, totalTracesCount] = await Promise.all([
      getDistinctTraces(searchParams.trace_id, filteredTraceIds, pageSize, skip),
      getTotalTracesCount(searchParams.trace_id, searchParams.organization),
    ])

    const paginatedTraceIds = traceSummaries.map(t => t.trace_id)

    // Only need optimization_features for org column
    const allOptimizationFeatures =
      paginatedTraceIds.length > 0
        ? await prisma.optimization_features.findMany({
            where: { trace_id: { in: paginatedTraceIds } },
            select: { trace_id: true, organization: true },
          })
        : []

    const traceIdToOrganization = new Map<string, string>()
    ;(allOptimizationFeatures as Array<{ trace_id: string; organization: string | null }>).forEach(
      (feature: { trace_id: string; organization: string | null }) => {
        if (feature.trace_id && feature.organization) {
          traceIdToOrganization.set(feature.trace_id, feature.organization)
        }
      },
    )

    const orgs = await getUniqueOrganizations()

    // trace_summaries already has pre-aggregated data — map directly
    const traces = traceSummaries.map(t => ({
      trace_id: t.trace_id,
      first_seen: new Date(t.first_seen),
      last_seen: new Date(t.last_seen),
      call_count: t.call_count,
      total_cost: Number(t.total_cost),
      total_tokens: Number(t.total_tokens),
      failed_calls: t.failed_calls,
      hasPartial: t.has_partial,
      status: t.failed_calls > 0 ? "failed" : t.has_partial ? "partial_success" : "success",
      call_types: new Set(t.call_types || []),
    }))
    const totalPages = Math.ceil(totalTracesCount / pageSize)

    return (
      <div className="container mx-auto p-6">
        {/* Header */}
        <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">
              <h2 className="text-2xl font-bold tracking-tight text-gray-900 dark:text-white whitespace-nowrap">
                All Traces
              </h2>
              <HelpButton
                title="Understanding Traces"
                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 a trace?
                      </h4>
                      <p>
                        A trace represents a complete optimization request from start to finish.
                        Each trace contains all the LLM API calls made during that optimization.
                      </p>
                    </div>
                    <div>
                      <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                        Multi-model traces
                      </h4>
                      <p>
                        When using multiple models for optimization, all calls share the same base
                        trace_id (first 33 characters). This helps track related operations
                        together.
                      </p>
                    </div>
                    <div>
                      <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                        Page sections
                      </h4>
                      <ul className="list-disc list-inside space-y-1 ml-2">
                        <li>
                          <strong>Summary Stats:</strong> Quick overview of trace metrics on this
                          page
                        </li>
                        <li>
                          <strong>Traces Table:</strong> Detailed list of all traces with aggregated
                          data
                        </li>
                        <li>
                          <strong>Filters:</strong> Search by trace ID or filter by organization
                        </li>
                      </ul>
                    </div>
                  </div>
                }
              />
            </div>
            {/* Compact Search Bar */}
            <form method="get" className="flex items-center gap-2 flex-1 max-w-2xl">
              <div className="flex-1 relative">
                <input
                  type="text"
                  name="trace_id"
                  placeholder="Search by Trace ID..."
                  defaultValue={searchParams.trace_id || ""}
                  className="w-full 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"
                  title="Search by full or partial trace ID. Finds all related calls."
                />
              </div>
              <div className="flex items-center gap-1.5">
                <label
                  htmlFor="organization-filter"
                  className="text-sm font-medium text-gray-700 dark:text-gray-300 whitespace-nowrap"
                >
                  Organization
                </label>
                <InfoIcon
                  content="Filter by organization that initiated the optimization request"
                  side="top"
                />
              </div>
              <select
                id="organization-filter"
                name="organization"
                defaultValue={searchParams.organization || ""}
                className="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 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="">All Organizations</option>
                {orgs.map((org: string) => (
                  <option key={org} value={org}>
                    {org}
                  </option>
                ))}
              </select>
              <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 || searchParams.organization) && (
                <Link
                  href="/observability/traces"
                  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">
            View optimization request traces with aggregated metrics
          </p>
        </div>

        {/* Summary Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-5 mb-8">
          <StatCard
            label="Total Traces"
            value={totalTracesCount}
            helpText="Total number of unique traces across all pages matching your filters"
            icon="Database"
          />
          <StatCard
            label="LLM Calls (Page)"
            value={traces.reduce((sum: number, t: { call_count: number }) => sum + t.call_count, 0)}
            helpText="Number of individual LLM API calls on this page. Each trace may have multiple calls."
            icon="Zap"
            variant="default"
            className="border-l-4 border-blue-500"
          />
          <StatCard
            label="Total Cost (Page)"
            value={`$${traces.reduce((sum, t) => sum + t.total_cost, 0).toFixed(4)}`}
            helpText="Total cost in USD for all LLM calls shown on this page. Based on model pricing and token usage."
            icon="DollarSign"
          />
          <StatCard
            label="Failed Traces (Page)"
            value={traces.filter(t => t.failed_calls > 0).length}
            helpText="Traces containing at least one failed LLM call. Click a trace to see error details."
            icon="AlertTriangle"
            variant="error"
          />
        </div>

        {/* Traces Table */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50 dark:bg-gray-900">
                <tr>
                  <ColumnHeader
                    label="Trace ID"
                    tooltip="Unique identifier for this optimization request. Click to view detailed timeline."
                  />
                  <ColumnHeader
                    label="Organization"
                    tooltip="Organization that initiated this optimization (from GitHub/CLI metadata)"
                  />
                  <ColumnHeader
                    label="Status"
                    tooltip="Overall status: Success (all calls succeeded), Partial (some succeeded), Failed (any call failed)"
                  />
                  <ColumnHeader
                    label="Calls"
                    tooltip="Number of LLM API calls in this trace. Includes retries and multi-model attempts."
                  />
                  <ColumnHeader
                    label="Call Types"
                    tooltip="Types of LLM operations: optimization, validation, line_profiler, etc."
                  />
                  <ColumnHeader
                    label="Cost"
                    tooltip="Total cost in USD for all LLM calls in this trace"
                  />
                  <ColumnHeader
                    label="Tokens"
                    tooltip="Combined prompt + completion tokens across all calls"
                  />
                  <ColumnHeader
                    label="Duration"
                    tooltip="Time between first and last call in this trace"
                  />
                  <ColumnHeader
                    label="Last Seen"
                    tooltip="Timestamp of the most recent call in this trace"
                  />
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                {traces.length === 0 ? (
                  <tr>
                    <td colSpan={9} className="px-6 py-16 text-center">
                      <div className="flex flex-col items-center justify-center space-y-4">
                        <SearchIcon className="h-12 w-12 text-gray-400 dark:text-gray-500" />
                        <div>
                          <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-1">
                            No Traces Found
                          </h3>
                          <p className="text-sm text-gray-500 dark:text-gray-400">
                            {searchParams.trace_id || searchParams.organization
                              ? "Try adjusting your filters above"
                              : "Run an optimization to see traces here"}
                          </p>
                        </div>
                        {(searchParams.trace_id || searchParams.organization) && (
                          <Link
                            href="/observability/llm-calls"
                            className="text-sm text-blue-600 dark:text-blue-400 hover:underline"
                          >
                            View All LLM Calls →
                          </Link>
                        )}
                      </div>
                    </td>
                  </tr>
                ) : (
                  traces.map(trace => {
                    // Ensure duration is never negative by using Math.max
                    const duration = Math.max(
                      0,
                      (trace.last_seen.getTime() - trace.first_seen.getTime()) / 1000,
                    )
                    const hasPartial = trace.hasPartial
                    const statusColor =
                      trace.failed_calls > 0
                        ? "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300"
                        : hasPartial
                          ? "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300"
                          : "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300"
                    const statusText =
                      trace.failed_calls > 0 ? "Failed" : hasPartial ? "Partial" : "Success"
                    const statusBorderColor =
                      trace.failed_calls > 0
                        ? "border-red-500"
                        : hasPartial
                          ? "border-yellow-500"
                          : "border-green-500"

                    return (
                      <tr
                        key={trace.trace_id}
                        className={`border-l-4 border-transparent hover:bg-gray-50 dark:hover:bg-gray-700/50 hover:shadow-md hover:${statusBorderColor} transition-all duration-200`}
                      >
                        <td className="px-6 py-5">
                          {trace.trace_id && trace.trace_id.trim() ? (
                            <Link
                              href={`/observability/trace/${trace.trace_id}`}
                              className="text-blue-600 dark:text-blue-400 hover:underline font-mono text-sm"
                            >
                              {trace.trace_id.substring(0, 8)}...
                            </Link>
                          ) : (
                            <span className="text-gray-400 dark:text-gray-500 font-mono text-sm">
                              N/A
                            </span>
                          )}
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                          {traceIdToOrganization.get(trace.trace_id) || "N/A"}
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap">
                          <span
                            className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${statusColor}`}
                          >
                            {statusText}
                          </span>
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                          {trace.call_count}
                          {trace.failed_calls > 0 && (
                            <span className="text-red-600 dark:text-red-400 ml-1">
                              ({trace.failed_calls} failed)
                            </span>
                          )}
                        </td>
                        <td className="px-6 py-5 text-sm text-gray-700 dark:text-gray-300">
                          <div className="flex flex-wrap gap-1">
                            {Array.from(trace.call_types)
                              .slice(0, 3)
                              .map(type => (
                                <span
                                  key={type}
                                  className="px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 rounded"
                                >
                                  {type}
                                </span>
                              ))}
                            {trace.call_types.size > 3 && (
                              <span className="px-2 py-0.5 text-xs text-gray-500 dark:text-gray-400">
                                +{trace.call_types.size - 3}
                              </span>
                            )}
                          </div>
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                          ${trace.total_cost.toFixed(4)}
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                          {trace.total_tokens.toLocaleString()}
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                          {duration.toFixed(2)}s
                        </td>
                        <td className="px-6 py-5 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400">
                          {trace.last_seen.toLocaleString()}
                        </td>
                      </tr>
                    )
                  })
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="mt-8 flex justify-center items-center gap-4">
            {page > 1 && (
              <Link
                href={`/observability/traces?page=${page - 1}${searchParams.trace_id ? `&trace_id=${searchParams.trace_id}` : ""}${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="text-gray-600 dark:text-gray-400">
              Page {page} of {totalPages} • Showing {traces.length} traces
            </span>
            {page < totalPages && (
              <Link
                href={`/observability/traces?page=${page + 1}${searchParams.trace_id ? `&trace_id=${searchParams.trace_id}` : ""}${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
  }
}
