"use client"

import { useState, useCallback, useRef, useEffect } from "react"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Search,
  FileCode2,
  Zap,
  Clock,
  ChevronLeft,
  ChevronRight,
  Filter,
  ArrowUpDown,
  ArrowUp,
  ArrowDown,
} from "lucide-react"
import { formatDistanceToNow } from "date-fns"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import Image from "next/image"
import { ReviewQualityBadge } from "@/components/ui/quality_badge"

interface Repository {
  id: string
  full_name?: string
}

interface DiffContent {
  oldContent: string
  newContent: string
}

interface EventMetadata {
  diffContents?: Record<string, DiffContent>
  [key: string]: unknown
}

interface OptimizationEvent {
  id: string
  function_name?: string
  file_path?: string
  repository?: Repository | null | undefined
  speedup_x?: number
  speedup_pct?: number
  metadata?: EventMetadata | null | undefined
  created_at: string
  status?: string
  event_type?: string
  trace_id: string
  review_quality: string
}

interface FilterState {
  search: string
  repositoryId: string | null
  status: string
  eventType: string
  reviewQuality: string
  sortBy: string
  page: number
}

interface OptimizationsTableProps {
  initialEvents: OptimizationEvent[]
  initialTotalCount: number
  availableRepositories: Array<{ id: string; full_name: string }>
}

function TableSkeleton() {
  return (
    <>
      {Array.from({ length: 5 }).map((_, index) => (
        <TableRow key={index}>
          <TableCell>
            <div className="flex items-start gap-3">
              <div className="h-4 w-4 bg-muted animate-pulse rounded mt-1 flex-shrink-0" />
              <div className="flex-1 min-w-0 space-y-2">
                <div className="h-4 bg-muted animate-pulse rounded w-3/4" />
                <div className="h-3 bg-muted animate-pulse rounded w-1/2" />
              </div>
            </div>
          </TableCell>
          <TableCell>
            <div className="flex items-center gap-3">
              <div className="h-8 w-8 bg-muted animate-pulse rounded-full flex-shrink-0" />
              <div className="h-4 bg-muted animate-pulse rounded w-32" />
            </div>
          </TableCell>
          <TableCell className="text-center">
            <div className="h-6 bg-muted animate-pulse rounded-full w-20 mx-auto" />
          </TableCell>
          <TableCell className="text-center">
            <div className="h-6 bg-muted animate-pulse rounded-full w-24 mx-auto" />
          </TableCell>
          <TableCell className="text-center">
            <div className="h-6 bg-muted animate-pulse rounded-full w-16 mx-auto" />
          </TableCell>
          <TableCell className="text-center">
            <div className="h-6 bg-muted animate-pulse rounded-full w-24 mx-auto" />
          </TableCell>
          <TableCell className="text-center">
            <div className="flex items-center justify-center gap-2">
              <div className="h-6 bg-muted animate-pulse rounded-full w-12" />
              <div className="h-6 bg-muted animate-pulse rounded-full w-12" />
            </div>
          </TableCell>
          <TableCell className="text-right">
            <div className="flex items-center justify-end gap-2">
              <div className="h-3 w-3 bg-muted animate-pulse rounded flex-shrink-0" />
              <div className="h-4 bg-muted animate-pulse rounded w-24" />
            </div>
          </TableCell>
        </TableRow>
      ))}
    </>
  )
}

function calculateDiffStats(
  diffContents: Record<string, { oldContent: string; newContent: string }>,
) {
  let totalAdditions = 0
  let totalDeletions = 0

  Object.entries(diffContents).forEach(([, { oldContent, newContent }]) => {
    const oldLines = oldContent.split("\n").filter(line => line.trim() !== "")
    const newLines = newContent.split("\n").filter(line => line.trim() !== "")

    const oldLineMap = new Map<string, number>()
    const newLineMap = new Map<string, number>()

    oldLines.forEach(line => {
      const trimmed = line.trim()
      oldLineMap.set(trimmed, (oldLineMap.get(trimmed) || 0) + 1)
    })

    newLines.forEach(line => {
      const trimmed = line.trim()
      newLineMap.set(trimmed, (newLineMap.get(trimmed) || 0) + 1)
    })

    for (const [line, oldCount] of Array.from(oldLineMap)) {
      const newCount = newLineMap.get(line) || 0
      if (oldCount > newCount) {
        totalDeletions += oldCount - newCount
      }
    }

    for (const [line, newCount] of Array.from(newLineMap)) {
      const oldCount = oldLineMap.get(line) || 0
      if (newCount > oldCount) {
        totalAdditions += newCount - oldCount
      }
    }
  })

  return { totalAdditions, totalDeletions }
}

function ClickableTableRow({
  event,
  children,
  onRowClick,
}: {
  event: OptimizationEvent
  children: React.ReactNode
  onRowClick: (eventId: string) => void
}) {
  const handleRowClick = useCallback(
    (e: React.MouseEvent) => {
      if ((e.target as HTMLElement).closest('a[href^="http"]')) {
        return
      }
      onRowClick(event.trace_id)
    },
    [event.trace_id, onRowClick],
  )

  return (
    <TableRow
      key={event.id}
      className="group cursor-pointer hover:bg-muted"
      onClick={handleRowClick}
    >
      {children}
    </TableRow>
  )
}

export function OptimizationsTable({
  initialEvents,
  initialTotalCount,
  availableRepositories,
}: OptimizationsTableProps) {
  const router = useRouter()

  const [events, setEvents] = useState<OptimizationEvent[]>(initialEvents)
  const [totalCount, setTotalCount] = useState(initialTotalCount)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const [filters, setFilters] = useState<FilterState>({
    search: "",
    repositoryId: null,
    status: "all",
    eventType: "all",
    reviewQuality: "all",
    sortBy: "created_at_desc",
    page: 1,
  })

  const pageSize = 10
  const isInitialMount = useRef(true)
  const debounceTimer = useRef<NodeJS.Timeout>(undefined)
  const [retryKey, setRetryKey] = useState(0)

  // Load events when filters change (skip initial mount — server provided that data)
  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false
      return
    }

    const controller = new AbortController()

    const doFetch = () => {
      setIsLoading(true)
      setError(null)

      const params = new URLSearchParams({
        page: String(filters.page),
        pageSize: String(pageSize),
        search: filters.search,
        status: filters.status,
        eventType: filters.eventType,
        reviewQuality: filters.reviewQuality,
        sortBy: filters.sortBy,
      })
      if (filters.repositoryId) params.set("repositoryId", filters.repositoryId)

      fetch(`/api/optimization-events?${params}`, { signal: controller.signal })
        .then(res => {
          if (!res.ok) throw new Error(`HTTP ${res.status}`)
          return res.json()
        })
        .then(data => {
          type RawEvent = OptimizationEvent & {
            repository?: { id: string; full_name?: string; name?: string } | null
          }
          const transformedEvents: OptimizationEvent[] = (data?.events || []).map(
            (event: RawEvent) => ({
              ...event,
              metadata: event.metadata as EventMetadata | null | undefined,
              repository: event.repository
                ? {
                    id: event.repository.id,
                    full_name: event.repository.full_name || event.repository.name,
                  }
                : null,
            }),
          )
          setEvents(transformedEvents)
          setTotalCount(data?.totalCount || 0)
        })
        .catch(err => {
          if (err instanceof DOMException && err.name === "AbortError") return
          console.error("Failed to fetch optimization events:", err)
          setError(err instanceof Error ? err.message : "Failed to load events")
        })
        .finally(() => {
          if (!controller.signal.aborted) setIsLoading(false)
        })
    }

    if (debounceTimer.current) {
      clearTimeout(debounceTimer.current)
    }

    if (filters.search !== "") {
      debounceTimer.current = setTimeout(doFetch, 300)
    } else {
      doFetch()
    }

    return () => {
      controller.abort()
      if (debounceTimer.current) {
        clearTimeout(debounceTimer.current)
      }
    }
    // Flatten filter properties as deps to avoid object-reference churn
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    filters.page,
    filters.search,
    filters.status,
    filters.eventType,
    filters.reviewQuality,
    filters.sortBy,
    filters.repositoryId,
    pageSize,
    retryKey,
  ])

  const handleRowClick = useCallback(
    (traceId: string) => {
      router.push(`/review-optimizations/${traceId}`)
    },
    [router],
  )

  const updateFilter = useCallback((key: keyof FilterState, value: string | number | null) => {
    setFilters(prev => ({
      ...prev,
      [key]: value,
      ...(key !== "page" && { page: 1 }),
    }))
  }, [])

  const clearFilters = useCallback(() => {
    setFilters({
      search: "",
      repositoryId: null,
      status: "all",
      eventType: "all",
      reviewQuality: "all",
      sortBy: "created_at_desc",
      page: 1,
    })
  }, [])

  const hasActiveFilters =
    filters.search ||
    filters.repositoryId !== null ||
    filters.status !== "all" ||
    filters.eventType !== "all" ||
    filters.reviewQuality !== "all" ||
    filters.sortBy !== "created_at_desc"

  const totalPages = Math.ceil(totalCount / pageSize)

  const handlePageChange = useCallback(
    (newPage: number) => {
      if (newPage >= 1 && newPage <= totalPages) {
        updateFilter("page", newPage)
      }
    },
    [totalPages, updateFilter],
  )

  const getSortIcon = useCallback(
    (field: string) => {
      if (filters.sortBy.startsWith(field)) {
        return filters.sortBy.endsWith("_asc") ? (
          <ArrowUp className="h-4 w-4" />
        ) : (
          <ArrowDown className="h-4 w-4" />
        )
      }
      return <ArrowUpDown className="h-4 w-4 opacity-50" />
    },
    [filters.sortBy],
  )

  const toggleSort = useCallback(
    (field: string) => {
      const newSort = filters.sortBy.startsWith(field)
        ? filters.sortBy === `${field}_desc`
          ? `${field}_asc`
          : `${field}_desc`
        : `${field}_desc`
      updateFilter("sortBy", newSort)
    },
    [filters.sortBy, updateFilter],
  )

  const getSpeedupBadge = useCallback((speedup?: number, speedupPct?: number) => {
    if (typeof speedup !== "number" || typeof speedupPct !== "number") return null

    const clamp = (v: number, min: number, max: number) => Math.min(Math.max(v, min), max)
    const x = clamp(speedup, 1, 300)
    const t = (x - 1) / 299

    const hue = 158
    const lightness = 95 - t * (95 - 35)
    const saturation = 45 + t * (75 - 45)
    const textColor = lightness < 60 ? "#fff" : "#047857"
    const borderLightness = lightness > 60 ? lightness - 8 : lightness + 8
    const borderSaturation = saturation > 70 ? saturation - 10 : saturation + 10

    const bgColor = `hsl(${hue}, ${saturation}%, ${lightness}%)`
    const borderColor = `hsl(${hue}, ${borderSaturation}%, ${borderLightness}%)`

    return (
      <Badge
        variant="default"
        className="font-mono text-[11px] px-2 py-0.5 whitespace-nowrap font-medium"
        style={{
          backgroundColor: bgColor,
          color: textColor,
          border: `1px solid ${borderColor}`,
        }}
      >
        {speedup.toFixed(2)}x ({speedupPct.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ",")}%)
      </Badge>
    )
  }, [])

  const getStatusBadge = useCallback((status?: string) => {
    if (!status) return null

    const variants: Record<string, { className: string; label: string }> = {
      approved: {
        className:
          "bg-green-100 text-green-800 border-green-300 dark:bg-green-900/30 dark:text-green-100 dark:border-green-700",
        label: "Approved",
      },
      rejected: {
        className:
          "bg-red-100 text-red-800 border-red-300 dark:bg-red-900/30 dark:text-red-100 dark:border-red-700",
        label: "Rejected",
      },
    }

    const variant = variants[status] || {
      className: "bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-100",
      label: status,
    }

    return (
      <Badge variant="secondary" className={variant.className}>
        {variant.label}
      </Badge>
    )
  }, [])

  const getEventTypeBadge = useCallback((eventType?: string) => {
    if (!eventType) return null

    const variants: Record<string, { className: string; label: string }> = {
      pr_created: {
        className:
          "bg-blue-100 text-blue-800 border-blue-300 dark:bg-blue-900/30 dark:text-blue-100 dark:border-blue-700",
        label: "PR Created",
      },
      pr_merged: {
        className:
          "bg-purple-100 text-purple-800 border-purple-300 dark:bg-purple-900/30 dark:text-purple-100 dark:border-purple-700",
        label: "PR Merged",
      },
      pr_closed: {
        className:
          "bg-orange-100 text-orange-800 border-orange-300 dark:bg-orange-900/30 dark:text-orange-100 dark:border-orange-700",
        label: "PR Closed",
      },
      "no-pr": {
        className:
          "bg-gray-100 text-gray-800 border-gray-300 dark:bg-gray-800 dark:text-gray-100 dark:border-gray-600",
        label: "Staged Changes",
      },
    }

    const variant = variants[eventType] || {
      className: "bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-100",
      label: eventType,
    }

    return (
      <Badge variant="secondary" className={variant.className}>
        {variant.label}
      </Badge>
    )
  }, [])

  return (
    <div className="py-8 px-4">
      <div className="mb-8">
        <h1 className="text-3xl font-bold mb-2">Review Optimizations</h1>
      </div>

      {/* Search and Filters */}
      <div className="mb-6">
        <div className="flex flex-wrap items-center gap-3">
          <div className="relative flex-1 min-w-[200px] max-w-md">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
            <Input
              placeholder="Search by function name, file path, or repository name..."
              value={filters.search}
              onChange={e => updateFilter("search", e.target.value)}
              className="pl-10 w-full"
            />
          </div>

          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <Filter className="h-4 w-4" />
            <span className="hidden sm:inline">Filters:</span>
          </div>

          <Select
            value={filters.repositoryId || "all"}
            onValueChange={value =>
              updateFilter(
                "repositoryId",
                value === "all" ? null : value === "none" ? "none" : value,
              )
            }
          >
            <SelectTrigger
              className={`w-[180px] sm:w-[220px] ${
                filters.repositoryId === null
                  ? "text-muted-foreground [&>span]:text-muted-foreground"
                  : ""
              }`}
            >
              <SelectValue placeholder="All Repositories" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Repositories</SelectItem>
              <SelectItem value="none">Without Repository</SelectItem>
              {availableRepositories.map(repo => (
                <SelectItem key={repo.id} value={repo.id}>
                  {repo.full_name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          <Select value={filters.status} onValueChange={value => updateFilter("status", value)}>
            <SelectTrigger
              className={`w-[120px] sm:w-[150px] ${
                filters.status === "all"
                  ? "text-muted-foreground [&>span]:text-muted-foreground"
                  : ""
              }`}
            >
              <SelectValue placeholder="Status" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">Reviews</SelectItem>
              <SelectItem value="approved">Approved</SelectItem>
              <SelectItem value="rejected">Rejected</SelectItem>
            </SelectContent>
          </Select>

          <Select
            value={filters.eventType}
            onValueChange={value => updateFilter("eventType", value)}
          >
            <SelectTrigger
              className={`w-[120px] sm:w-[150px] ${
                filters.eventType === "all"
                  ? "text-muted-foreground [&>span]:text-muted-foreground"
                  : ""
              }`}
            >
              <SelectValue placeholder="Event Type" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">Status</SelectItem>
              <SelectItem value="pr_created">PR Created</SelectItem>
              <SelectItem value="pr_merged">PR Merged</SelectItem>
              <SelectItem value="pr_closed">PR Closed</SelectItem>
              <SelectItem value="no-pr">Staged Changes</SelectItem>
            </SelectContent>
          </Select>

          <Select
            value={filters.reviewQuality}
            onValueChange={value => updateFilter("reviewQuality", value)}
          >
            <SelectTrigger
              className={`w-[120px] sm:w-[150px] ${
                filters.reviewQuality === "all"
                  ? "text-muted-foreground [&>span]:text-muted-foreground"
                  : ""
              }`}
            >
              <SelectValue placeholder="Quality" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Quality</SelectItem>
              <SelectItem value="high">High</SelectItem>
              <SelectItem value="medium">Medium</SelectItem>
              <SelectItem value="low">Low</SelectItem>
            </SelectContent>
          </Select>

          <Select value={filters.sortBy} onValueChange={value => updateFilter("sortBy", value)}>
            <SelectTrigger
              className={`w-[140px] sm:w-[200px] ${
                filters.sortBy === "created_at_desc"
                  ? "text-muted-foreground [&>span]:text-muted-foreground"
                  : ""
              }`}
            >
              <SelectValue placeholder="Sort by" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="created_at_desc">Newest</SelectItem>
              <SelectItem value="created_at_asc">Oldest</SelectItem>
              <SelectItem value="speedup_x_desc">Speedup (Highest)</SelectItem>
              <SelectItem value="speedup_x_asc">Speedup (Lowest)</SelectItem>
              <SelectItem value="review_quality_desc">Quality (High to Low)</SelectItem>
              <SelectItem value="review_quality_asc">Quality (Low to High)</SelectItem>
            </SelectContent>
          </Select>

          {hasActiveFilters && (
            <Button
              variant="ghost"
              size="sm"
              onClick={clearFilters}
              className="text-muted-foreground hover:text-foreground"
            >
              Clear
            </Button>
          )}
        </div>
      </div>

      {error && (
        <div className="mb-6 p-4 rounded-lg bg-destructive/10 border border-destructive/20">
          <p className="text-destructive text-sm">Error: {error}</p>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setRetryKey(k => k + 1)}
            className="mt-2"
            disabled={isLoading}
          >
            Retry
          </Button>
        </div>
      )}

      <div className="rounded-lg border bg-card">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[25%]">FUNCTION / FILE</TableHead>
              <TableHead className="w-[18%]">REPOSITORY</TableHead>
              <TableHead className="text-center">REVIEW</TableHead>
              <TableHead className="text-center">STATUS</TableHead>
              <TableHead
                className="text-center cursor-pointer hover:bg-muted/50"
                onClick={() => toggleSort("review_quality")}
              >
                <div className="flex items-center justify-center gap-1">
                  <span>QUALITY</span>
                  {getSortIcon("review_quality")}
                </div>
              </TableHead>
              <TableHead
                className="text-center cursor-pointer hover:bg-muted/50"
                onClick={() => toggleSort("speedup_x")}
              >
                <div className="flex items-center justify-center gap-1">
                  <span>SPEEDUP</span>
                  {getSortIcon("speedup_x")}
                </div>
              </TableHead>
              <TableHead className="text-center">CHANGES</TableHead>
              <TableHead
                className="text-right cursor-pointer hover:bg-muted/50"
                onClick={() => toggleSort("created_at")}
              >
                <div className="flex items-center justify-end gap-1">
                  <span>CREATED</span>
                  {getSortIcon("created_at")}
                </div>
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              <TableSkeleton />
            ) : events.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} className="py-12">
                  <div className="mx-auto max-w-lg text-center bg-muted/5 border border-dashed border-border rounded-xl px-6 py-10">
                    <div className="inline-flex items-center justify-center w-14 h-14 rounded-full bg-muted/30 mb-4">
                      <Zap className="h-8 w-8 text-muted-foreground" />
                    </div>
                    <h3 className="text-base sm:text-lg font-semibold mb-2">
                      No optimizations to review yet
                    </h3>
                    <p className="text-xs sm:text-sm text-muted-foreground mb-3">
                      Run `codeflash --all with --staging-review` in a repository or install the VS
                      Code extension to trigger your first optimization review.
                    </p>
                    {hasActiveFilters ? (
                      <p className="text-xs sm:text-sm text-muted-foreground">
                        Filters are currently hiding results—clear them to see everything.
                      </p>
                    ) : (
                      <div className="flex flex-col sm:flex-row items-center justify-center gap-2 sm:gap-3 mt-4">
                        <a
                          href="/onboarding"
                          className="w-full sm:w-auto inline-flex items-center justify-center rounded-lg bg-primary px-4 py-2 text-xs sm:text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
                        >
                          View setup steps
                        </a>
                        <a
                          href="https://docs.codeflash.ai/editor-plugins/vscode"
                          target="_blank"
                          rel="noopener noreferrer"
                          className="w-full sm:w-auto inline-flex items-center justify-center rounded-lg border border-border px-4 py-2 text-xs sm:text-sm font-medium text-foreground hover:bg-muted/40 transition-colors"
                        >
                          Install VS Code extension
                        </a>
                      </div>
                    )}
                  </div>
                </TableCell>
              </TableRow>
            ) : (
              events.map((event: OptimizationEvent) => {
                let diffStats: { totalAdditions: number; totalDeletions: number } = {
                  totalAdditions: 0,
                  totalDeletions: 0,
                }

                if (
                  event.metadata &&
                  typeof event.metadata === "object" &&
                  event.metadata !== null &&
                  typeof event.metadata.diffContents === "object" &&
                  event.metadata.diffContents !== null
                ) {
                  const diffContentsRaw = event.metadata.diffContents
                  if (diffContentsRaw && typeof diffContentsRaw === "object") {
                    let valid = true
                    for (const value of Object.values(diffContentsRaw as object)) {
                      if (
                        !value ||
                        typeof value !== "object" ||
                        typeof (value as DiffContent).oldContent !== "string" ||
                        typeof (value as DiffContent).newContent !== "string"
                      ) {
                        valid = false
                        break
                      }
                    }
                    if (valid) {
                      const diffContents = diffContentsRaw as Record<
                        string,
                        { oldContent: string; newContent: string }
                      >
                      diffStats = calculateDiffStats(diffContents)
                    }
                  }
                }

                return (
                  <ClickableTableRow key={event.id} event={event} onRowClick={handleRowClick}>
                    <TableCell className="w-auto min-w-0">
                      <div className="flex items-start gap-3">
                        <FileCode2 className="h-4 w-4 text-muted-foreground mt-1 flex-shrink-0" />
                        <div className="flex-1 min-w-0 overflow-hidden">
                          <div className="font-mono text-sm font-medium truncate">
                            {event.function_name || "Unknown Function"}
                          </div>
                          <div className="text-xs text-muted-foreground truncate">
                            {event.file_path || "No file path"}
                          </div>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell className="w-auto min-w-0">
                      <div className="flex items-center gap-3">
                        {event.repository ? (
                          <>
                            <div className="relative h-8 w-8 flex-shrink-0">
                              {event.repository.full_name && (
                                <Image
                                  src={`https://github.com/${event.repository.full_name.split("/")[0]}.png`}
                                  alt={event.repository.full_name}
                                  fill
                                  sizes="32px"
                                  className="rounded-full object-cover"
                                  onError={e => {
                                    e.currentTarget.style.display = "none"
                                  }}
                                />
                              )}
                            </div>
                            <div className="flex-1 min-w-0 overflow-hidden">
                              <div className="flex items-center gap-1">
                                <span className="text-sm font-medium truncate">
                                  {event.repository.full_name || "Unknown Repository"}
                                </span>
                              </div>
                            </div>
                          </>
                        ) : (
                          <>
                            <div className="h-8 w-8 rounded-full bg-muted flex items-center justify-center flex-shrink-0">
                              <Zap className="h-4 w-4 text-muted-foreground" />
                            </div>
                            <span className="text-sm text-muted-foreground">
                              Untracked repository
                            </span>
                          </>
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="text-center">{getStatusBadge(event.status)}</TableCell>
                    <TableCell className="text-center">
                      {getEventTypeBadge(event.event_type)}
                    </TableCell>
                    <TableCell className="text-center">
                      <ReviewQualityBadge quality={event.review_quality} />
                    </TableCell>
                    <TableCell className="text-center">
                      {getSpeedupBadge(event.speedup_x, event.speedup_pct)}
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="flex items-center justify-center gap-2 flex-wrap">
                        {diffStats.totalAdditions > 0 && (
                          <Badge
                            variant="secondary"
                            className="bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-950/50 dark:text-emerald-400 dark:border-emerald-800 whitespace-nowrap font-medium"
                          >
                            +{diffStats.totalAdditions}
                          </Badge>
                        )}
                        {diffStats.totalDeletions > 0 && (
                          <Badge
                            variant="secondary"
                            className="bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-950/50 dark:text-rose-400 dark:border-rose-800 whitespace-nowrap font-medium"
                          >
                            -{diffStats.totalDeletions}
                          </Badge>
                        )}
                        {diffStats.totalAdditions === 0 && diffStats.totalDeletions === 0 && (
                          <span className="text-muted-foreground text-xs">—</span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-2">
                        <Clock className="h-3 w-3 text-muted-foreground flex-shrink-0" />
                        <span className="text-sm text-muted-foreground whitespace-nowrap">
                          {formatDistanceToNow(new Date(event.created_at), {
                            addSuffix: true,
                          })}
                        </span>
                      </div>
                    </TableCell>
                  </ClickableTableRow>
                )
              })
            )}
          </TableBody>
        </Table>
      </div>

      {!isLoading && totalPages > 1 && (
        <div className="flex items-center justify-between mt-6">
          <p className="text-sm text-muted-foreground">
            Showing {(filters.page - 1) * pageSize + 1} to{" "}
            {Math.min(filters.page * pageSize, totalCount)} of {totalCount} events
          </p>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              disabled={filters.page === 1}
              onClick={() => handlePageChange(filters.page - 1)}
            >
              <ChevronLeft className="h-4 w-4" />
              Previous
            </Button>

            <div className="flex items-center gap-1">
              {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                let pageNum: number

                if (totalPages <= 5) {
                  pageNum = i + 1
                } else if (filters.page <= 3) {
                  pageNum = i + 1
                } else if (filters.page >= totalPages - 2) {
                  pageNum = totalPages - 4 + i
                } else {
                  pageNum = filters.page - 2 + i
                }

                return (
                  <Button
                    key={i}
                    variant={filters.page === pageNum ? "default" : "outline"}
                    size="sm"
                    className="w-8 h-8 p-0"
                    onClick={() => handlePageChange(pageNum)}
                  >
                    {pageNum}
                  </Button>
                )
              })}
              {totalPages > 5 && filters.page < totalPages - 2 && <span className="px-2">...</span>}
              {totalPages > 5 && filters.page < totalPages - 2 && (
                <Button
                  variant="outline"
                  size="sm"
                  className="w-8 h-8 p-0"
                  onClick={() => handlePageChange(totalPages)}
                >
                  {totalPages}
                </Button>
              )}
            </div>

            <Button
              variant="outline"
              size="sm"
              disabled={filters.page === totalPages}
              onClick={() => handlePageChange(filters.page + 1)}
            >
              Next
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}
    </div>
  )
}
