'use client'

import { useEffect, useState, useMemo, useCallback } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { useAnalyzePanelStore } from '@/lib/analyze-store'
import {
  ExternalLink,
  Loader2,
  Diamond,
  Zap,
  ChevronLeft,
  ChevronRight,
  ChevronUp,
  ChevronDown,
  RefreshCw,
  Clock,
  Search,
  Eye,
  EyeOff,
  ShieldCheck,
  Ban,
  X,
  Filter,
  Shield,
} from 'lucide-react'
import clsx from 'clsx'

// ============================================================================
// TYPES
// ============================================================================

interface MarketItem {
  id: string
  domain: string
  tld: string
  price: number
  currency: string
  price_type: 'bid' | 'fixed' | 'negotiable'
  status: 'auction' | 'instant'
  source: string
  is_pounce: boolean
  verified: boolean
  time_remaining?: string
  end_time?: string
  num_bids?: number
  slug?: string
  seller_verified: boolean
  url: string
  is_external: boolean
  pounce_score: number
}

type SourceFilter = 'all' | 'pounce' | 'external'
type PriceRange = 'all' | 'low' | 'mid' | 'high'

// ============================================================================
// HELPERS
// ============================================================================

function calcTimeRemaining(endTimeIso?: string): string {
  if (!endTimeIso) return 'N/A'
  const end = new Date(endTimeIso).getTime()
  const now = Date.now()
  const diff = end - now

  if (diff <= 0) return 'Ended'

  const seconds = Math.floor(diff / 1000)
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const mins = Math.floor((seconds % 3600) / 60)

  if (days > 0) return `${days}d ${hours}h`
  if (hours > 0) return `${hours}h ${mins}m`
  if (mins > 0) return `${mins}m`
  return '< 1m'
}

function getSecondsUntilEnd(endTimeIso?: string): number {
  if (!endTimeIso) return Infinity
  const diff = new Date(endTimeIso).getTime() - Date.now()
  return diff > 0 ? diff / 1000 : -1
}

function formatPrice(price: number, currency = 'USD'): string {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency,
    maximumFractionDigits: 0,
  }).format(price)
}

function isSpam(domain: string): boolean {
  const name = domain.split('.')[0]
  if (name.includes('-')) return true
  if (name.length > 4 && /\d/.test(name)) return true
  if (/^\d+$/.test(name)) return true
  return false
}

// ============================================================================
// COMPONENT
// ============================================================================

interface AuctionsTabProps {
  showToast: (message: string, type?: 'success' | 'error' | 'info') => void
}

export function AuctionsTab({ showToast }: AuctionsTabProps) {
  const openAnalyze = useAnalyzePanelStore((s) => s.open)

  const [items, setItems] = useState<MarketItem[]>([])
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const [stats, setStats] = useState({ total: 0, pounceCount: 0, auctionCount: 0, highScore: 0 })

  const [sourceFilter, setSourceFilter] = useState<SourceFilter>('all')
  const [searchQuery, setSearchQuery] = useState('')
  const [priceRange, setPriceRange] = useState<PriceRange>('all')
  const [hideSpam, setHideSpam] = useState(true)
  const [tldFilter, setTldFilter] = useState<string>('all')
  const [searchFocused, setSearchFocused] = useState(false)

  const [trackedDomains, setTrackedDomains] = useState<Set<string>>(new Set())
  const [trackingInProgress, setTrackingInProgress] = useState<string | null>(null)

  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const ITEMS_PER_PAGE = 50

  const [filtersOpen, setFiltersOpen] = useState(false)

  const [sortField, setSortField] = useState<'domain' | 'score' | 'price' | 'time'>('time')
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')

  const loadData = useCallback(async (currentPage = 1) => {
    setLoading(true)
    try {
      const result = await api.getMarketFeed({
        source: sourceFilter,
        keyword: searchQuery || undefined,
        tld: tldFilter === 'all' ? undefined : tldFilter,
        minPrice: priceRange === 'low' ? undefined : priceRange === 'mid' ? 100 : priceRange === 'high' ? 1000 : undefined,
        maxPrice: priceRange === 'low' ? 100 : priceRange === 'mid' ? 1000 : undefined,
        sortBy: 'time',
        limit: ITEMS_PER_PAGE,
        offset: (currentPage - 1) * ITEMS_PER_PAGE,
      })

      setItems(result.items || [])
      setStats({
        total: result.total,
        pounceCount: result.pounce_direct_count,
        auctionCount: result.auction_count,
        highScore: (result.items || []).filter((i: MarketItem) => i.pounce_score >= 80).length,
      })
      setTotalPages(Math.ceil((result.total || 0) / ITEMS_PER_PAGE))
    } catch (error) {
      console.error('Failed to load market data:', error)
      setItems([])
    } finally {
      setLoading(false)
    }
  }, [sourceFilter, searchQuery, priceRange, tldFilter])

  useEffect(() => {
    setPage(1)
    loadData(1)
  }, [loadData])

  const handlePageChange = useCallback((newPage: number) => {
    setPage(newPage)
    loadData(newPage)
  }, [loadData])

  const handleRefresh = useCallback(async () => {
    setRefreshing(true)
    await loadData()
    setRefreshing(false)
  }, [loadData])

  useEffect(() => {
    const loadTrackedDomains = async () => {
      try {
        const result = await api.getDomains(1, 100)
        const domainSet = new Set(result.domains.map((d: any) => d.name))
        setTrackedDomains(domainSet)
      } catch (error) {
        console.error('Failed to load tracked domains:', error)
      }
    }
    loadTrackedDomains()
  }, [])

  const handleTrack = useCallback(async (domain: string) => {
    if (trackingInProgress) return
    setTrackingInProgress(domain)

    try {
      if (trackedDomains.has(domain)) {
        const result = await api.getDomains(1, 100)
        const domainToDelete = result.domains.find((d: any) => d.name === domain)
        if (domainToDelete) {
          await api.deleteDomain(domainToDelete.id)
          setTrackedDomains((prev) => {
            const next = new Set(Array.from(prev))
            next.delete(domain)
            return next
          })
          showToast(`Removed: ${domain}`, 'success')
        }
      } else {
        await api.addDomain(domain)
        setTrackedDomains((prev) => new Set([...Array.from(prev), domain]))
        showToast(`Tracking: ${domain}`, 'success')
      }
    } catch (error: any) {
      showToast(error.message || 'Failed', 'error')
    } finally {
      setTrackingInProgress(null)
    }
  }, [trackedDomains, trackingInProgress, showToast])

  const filteredItems = useMemo(() => {
    let filtered = items

    const nowMs = Date.now()
    filtered = filtered.filter((item) => {
      if (item.status !== 'auction') return true
      if (!item.end_time) return true
      const t = Date.parse(item.end_time)
      if (Number.isNaN(t)) return true
      return t > nowMs - 2000
    })

    if (searchQuery && !loading) {
      const query = searchQuery.toLowerCase()
      filtered = filtered.filter((item) => item.domain.toLowerCase().includes(query))
    }

    if (hideSpam) {
      filtered = filtered.filter((item) => !isSpam(item.domain))
    }

    const mult = sortDirection === 'asc' ? 1 : -1
    filtered.sort((a, b) => {
      switch (sortField) {
        case 'domain':
          return mult * a.domain.localeCompare(b.domain)
        case 'score':
          return mult * ((a.pounce_score || 0) - (b.pounce_score || 0))
        case 'price':
          return mult * (a.price - b.price)
        case 'time':
          const aTime = a.end_time ? new Date(a.end_time).getTime() : Infinity
          const bTime = b.end_time ? new Date(b.end_time).getTime() : Infinity
          return mult * (aTime - bTime)
        default:
          return 0
      }
    })

    return filtered
  }, [items, searchQuery, loading, hideSpam, sortField, sortDirection])

  const handleSort = useCallback((field: typeof sortField) => {
    if (sortField === field) {
      setSortDirection((d) => (d === 'asc' ? 'desc' : 'asc'))
    } else {
      setSortField(field)
      setSortDirection(field === 'time' || field === 'price' ? 'asc' : 'desc')
    }
  }, [sortField])

  const activeFiltersCount = [sourceFilter !== 'all', priceRange !== 'all', tldFilter !== 'all', hideSpam].filter(Boolean).length

  if (loading && items.length === 0) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-6 h-6 text-accent animate-spin" />
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* Search & Filters */}
      <div className="space-y-3">
        {/* Search */}
        <div className={clsx(
          "relative border transition-all duration-200",
          searchFocused ? "border-accent/50 bg-accent/[0.02]" : "border-white/[0.08] bg-white/[0.02]"
        )}>
          <div className="flex items-center">
            <Search className={clsx("w-4 h-4 ml-3 transition-colors", searchFocused ? "text-accent" : "text-white/30")} />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onFocus={() => setSearchFocused(true)}
              onBlur={() => setSearchFocused(false)}
              placeholder="Filter auctions..."
              className="flex-1 bg-transparent px-3 py-3 text-sm text-white placeholder:text-white/20 outline-none font-mono"
            />
            {searchQuery && (
              <button onClick={() => setSearchQuery('')} className="p-3 text-white/30 hover:text-white transition-colors">
                <X className="w-4 h-4" />
              </button>
            )}
            <button onClick={handleRefresh} disabled={refreshing} className="p-3 text-white/30 hover:text-white transition-colors">
              <RefreshCw className={clsx("w-4 h-4", refreshing && "animate-spin")} />
            </button>
          </div>
        </div>

        {/* Filter Toggle */}
        <button
          onClick={() => setFiltersOpen(!filtersOpen)}
          className={clsx(
            "flex items-center justify-between w-full py-2 px-3 border transition-colors",
            filtersOpen ? "border-accent/30 bg-accent/[0.05]" : "border-white/[0.08] bg-white/[0.02]"
          )}
        >
          <div className="flex items-center gap-2">
            <Filter className="w-4 h-4 text-white/40" />
            <span className="text-xs font-mono text-white/60">Filters</span>
            {activeFiltersCount > 0 && <span className="px-1.5 py-0.5 text-[9px] font-bold bg-accent text-black">{activeFiltersCount}</span>}
          </div>
          <ChevronRight className={clsx("w-4 h-4 text-white/30 transition-transform", filtersOpen && "rotate-90")} />
        </button>

        {/* Filters Panel */}
        {filtersOpen && (
          <div className="p-3 border border-white/[0.08] bg-white/[0.02] space-y-3 animate-in fade-in slide-in-from-top-2 duration-200">
            {/* Source */}
            <div>
              <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider mb-2">Source</div>
              <div className="flex gap-2">
                {[
                  { value: 'all', label: 'All' },
                  { value: 'pounce', label: 'Pounce', icon: Diamond },
                  { value: 'external', label: 'External' },
                ].map((item) => (
                  <button
                    key={item.value}
                    onClick={() => setSourceFilter(item.value as SourceFilter)}
                    className={clsx(
                      "flex-1 py-2 text-[10px] font-bold uppercase tracking-wider border transition-colors flex items-center justify-center gap-1",
                      sourceFilter === item.value ? "border-accent bg-accent/10 text-accent" : "border-white/[0.08] text-white/40"
                    )}
                  >
                    {item.icon && <item.icon className="w-3 h-3" />}
                    {item.label}
                  </button>
                ))}
              </div>
            </div>

            {/* TLD */}
            <div>
              <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider mb-2">TLD</div>
              <div className="flex gap-2 flex-wrap">
                {['all', 'com', 'ai', 'io', 'net'].map((tld) => (
                  <button
                    key={tld}
                    onClick={() => setTldFilter(tld)}
                    className={clsx(
                      "px-3 py-1.5 text-[10px] font-mono uppercase border transition-colors",
                      tldFilter === tld ? "border-accent bg-accent/10 text-accent" : "border-white/[0.08] text-white/40"
                    )}
                  >
                    {tld === 'all' ? 'All' : `.${tld}`}
                  </button>
                ))}
              </div>
            </div>

            {/* Price */}
            <div>
              <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider mb-2">Price</div>
              <div className="flex gap-2">
                {[
                  { value: 'all', label: 'All' },
                  { value: 'low', label: '< $100' },
                  { value: 'mid', label: '< $1k' },
                  { value: 'high', label: '$1k+' },
                ].map((item) => (
                  <button
                    key={item.value}
                    onClick={() => setPriceRange(item.value as PriceRange)}
                    className={clsx(
                      "flex-1 py-1.5 text-[10px] font-mono border transition-colors",
                      priceRange === item.value ? "border-amber-400 bg-amber-400/10 text-amber-400" : "border-white/[0.08] text-white/40"
                    )}
                  >
                    {item.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Spam Filter */}
            <button
              onClick={() => setHideSpam(!hideSpam)}
              className={clsx(
                "flex items-center justify-between w-full py-2 px-3 border transition-colors",
                hideSpam ? "border-white/20 bg-white/[0.05]" : "border-white/[0.08]"
              )}
            >
              <div className="flex items-center gap-2">
                <Ban className="w-4 h-4 text-white/40" />
                <span className="text-xs font-mono text-white/60">Hide spam domains</span>
              </div>
              <div className={clsx("w-4 h-4 border flex items-center justify-center", hideSpam ? "border-accent bg-accent" : "border-white/30")}>
                {hideSpam && <span className="text-black text-[10px] font-bold">✓</span>}
              </div>
            </button>
          </div>
        )}
      </div>

      {/* Stats Bar */}
      <div className="flex items-center justify-between text-[10px] font-mono text-white/40">
        <span>{filteredItems.length} domains shown</span>
        <span>{filteredItems.filter((i) => i.pounce_score >= 80).length} high score</span>
      </div>

      {/* Results */}
      {filteredItems.length === 0 ? (
        <div className="text-center py-16 border border-dashed border-white/[0.08]">
          <Search className="w-8 h-8 text-white/10 mx-auto mb-3" />
          <p className="text-white/40 text-sm font-mono">No domains found</p>
          <p className="text-white/25 text-xs font-mono mt-1">Try adjusting filters</p>
        </div>
      ) : (
        <>
          <div className="space-y-px bg-white/[0.04] border border-white/[0.08]">
            {/* Desktop Table Header */}
            <div className="hidden lg:grid grid-cols-[1fr_80px_100px_80px_120px] gap-4 px-3 py-2 text-[10px] font-mono text-white/40 uppercase tracking-wider border-b border-white/[0.08]">
              <button onClick={() => handleSort('domain')} className="flex items-center gap-1 hover:text-white/60 text-left">
                Domain
                {sortField === 'domain' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
              </button>
              <button onClick={() => handleSort('score')} className="flex items-center gap-1 justify-center hover:text-white/60">
                Score
                {sortField === 'score' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
              </button>
              <button onClick={() => handleSort('price')} className="flex items-center gap-1 justify-end hover:text-white/60">
                Price
                {sortField === 'price' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
              </button>
              <button onClick={() => handleSort('time')} className="flex items-center gap-1 justify-center hover:text-white/60">
                Time
                {sortField === 'time' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
              </button>
              <div className="text-right">Actions</div>
            </div>

            {filteredItems.map((item) => {
              const timeLeftSec = getSecondsUntilEnd(item.end_time)
              const isUrgent = timeLeftSec > 0 && timeLeftSec < 3600
              const isPounce = item.is_pounce
              const displayTime = item.status === 'auction' ? calcTimeRemaining(item.end_time) : null
              const isTracked = trackedDomains.has(item.domain)
              const isTracking = trackingInProgress === item.domain

              return (
                <div key={item.id} className={clsx("bg-[#020202] hover:bg-white/[0.02] transition-all", isPounce && "bg-accent/[0.02]")}>
                  {/* Mobile Row */}
                  <div className="lg:hidden p-3">
                    <div className="flex items-start justify-between gap-3 mb-2">
                      <div className="flex items-center gap-3 min-w-0 flex-1">
                        <div className={clsx("w-8 h-8 flex items-center justify-center border shrink-0", isPounce ? "bg-accent/10 border-accent/20" : "bg-white/[0.02] border-white/[0.06]")}>
                          {isPounce ? <Diamond className="w-4 h-4 text-accent" /> : <span className="text-[9px] font-mono text-white/40">{item.source.substring(0, 2).toUpperCase()}</span>}
                        </div>
                        <div className="min-w-0 flex-1">
                          <button onClick={() => openAnalyze(item.domain)} className="text-sm font-bold text-white font-mono truncate text-left">
                            {item.domain}
                          </button>
                          <div className="flex items-center gap-2 text-[10px] font-mono text-white/30">
                            <span className="uppercase">{item.source}</span>
                            <span className="text-white/10">|</span>
                            <span className={clsx(isUrgent && "text-orange-400")}>{isPounce ? 'Instant' : displayTime || 'N/A'}</span>
                          </div>
                        </div>
                      </div>

                      <div className="text-right shrink-0">
                        <div className={clsx("text-base font-bold font-mono", isPounce ? "text-accent" : "text-white")}>{formatPrice(item.price)}</div>
                        <div className={clsx("text-[9px] font-mono px-1 py-0.5 inline-block", item.pounce_score >= 80 ? "text-accent bg-accent/10" : item.pounce_score >= 50 ? "text-amber-400 bg-amber-400/10" : "text-white/30 bg-white/5")}>
                          Score {item.pounce_score}
                        </div>
                      </div>
                    </div>

                    <div className="flex gap-2">
                      <button
                        onClick={() => handleTrack(item.domain)}
                        disabled={isTracking}
                        className={clsx(
                          "flex-1 py-2 text-[10px] font-bold uppercase tracking-wider border flex items-center justify-center gap-1.5 transition-all",
                          isTracked ? "border-accent bg-accent/10 text-accent" : "border-white/[0.08] text-white/40"
                        )}
                      >
                        {isTracking ? <Loader2 className="w-3 h-3 animate-spin" /> : isTracked ? <Eye className="w-3 h-3" /> : <EyeOff className="w-3 h-3" />}
                        {isTracked ? 'Tracked' : 'Track'}
                      </button>

                      <button onClick={() => openAnalyze(item.domain)} className="w-10 py-2 text-[10px] font-bold uppercase tracking-wider border border-white/[0.08] text-white/50 flex items-center justify-center transition-all hover:text-white hover:bg-white/5">
                        <Shield className="w-3.5 h-3.5" />
                      </button>

                      <a
                        href={item.url}
                        target={isPounce ? '_self' : '_blank'}
                        rel={isPounce ? undefined : 'noopener noreferrer'}
                        className={clsx("flex-1 py-2 text-[10px] font-bold uppercase tracking-wider flex items-center justify-center gap-1.5 transition-all", isPounce ? "bg-accent text-black" : "bg-white/10 text-white")}
                      >
                        {isPounce ? 'Buy' : 'Bid'}
                        {!isPounce && <ExternalLink className="w-3 h-3" />}
                      </a>
                    </div>
                  </div>

                  {/* Desktop Row */}
                  <div className="hidden lg:grid grid-cols-[1fr_80px_100px_80px_120px] gap-4 items-center p-3 group">
                    <div className="flex items-center gap-3 min-w-0 flex-1">
                      <div className={clsx("w-8 h-8 flex items-center justify-center border shrink-0", isPounce ? "bg-accent/10 border-accent/20" : "bg-white/[0.02] border-white/[0.06]")}>
                        {isPounce ? <Diamond className="w-4 h-4 text-accent" /> : <span className="text-[9px] font-mono text-white/40">{item.source.substring(0, 2).toUpperCase()}</span>}
                      </div>
                      <div className="min-w-0">
                        <button onClick={() => openAnalyze(item.domain)} className="text-sm font-bold text-white font-mono truncate group-hover:text-accent transition-colors text-left">
                          {item.domain}
                        </button>
                        <div className="flex items-center gap-2 text-[10px] font-mono text-white/30">
                          <span className="uppercase">{item.source}</span>
                          {isPounce && item.verified && (
                            <>
                              <span className="text-white/10">|</span>
                              <span className="text-accent flex items-center gap-0.5">
                                <ShieldCheck className="w-3 h-3" />
                                Verified
                              </span>
                            </>
                          )}
                          {item.num_bids ? (
                            <>
                              <span className="text-white/10">|</span>
                              {item.num_bids} bids
                            </>
                          ) : null}
                        </div>
                      </div>
                    </div>

                    <div className="w-16 text-center shrink-0">
                      <span className={clsx("text-xs font-mono font-bold px-2 py-0.5", item.pounce_score >= 80 ? "text-accent bg-accent/10" : item.pounce_score >= 50 ? "text-amber-400 bg-amber-400/10" : "text-white/40 bg-white/5")}>
                        {item.pounce_score}
                      </span>
                    </div>

                    <div className="w-24 text-right shrink-0">
                      <div className={clsx("font-mono text-sm font-bold", isPounce ? "text-accent" : "text-white")}>{formatPrice(item.price)}</div>
                      <div className="text-[9px] font-mono text-white/30 uppercase">{item.price_type === 'bid' ? 'Bid' : 'Buy Now'}</div>
                    </div>

                    <div className="w-20 text-center shrink-0">
                      {isPounce ? (
                        <span className="text-xs text-accent font-mono flex items-center justify-center gap-1">
                          <Zap className="w-3 h-3" />
                          Instant
                        </span>
                      ) : (
                        <span className={clsx("text-xs font-mono", isUrgent ? "text-orange-400" : "text-white/50")}>{displayTime || 'N/A'}</span>
                      )}
                    </div>

                    <div className="flex items-center gap-2 shrink-0 opacity-50 group-hover:opacity-100 transition-opacity">
                      <button
                        onClick={() => handleTrack(item.domain)}
                        disabled={isTracking}
                        className={clsx(
                          "w-7 h-7 flex items-center justify-center border transition-colors",
                          isTracked ? "bg-accent/10 text-accent border-accent/20 hover:bg-red-500/10 hover:text-red-400 hover:border-red-500/20" : "text-white/30 border-white/10 hover:text-accent hover:bg-accent/10 hover:border-accent/20"
                        )}
                      >
                        {isTracking ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : isTracked ? <Eye className="w-3.5 h-3.5" /> : <EyeOff className="w-3.5 h-3.5" />}
                      </button>

                      <button onClick={() => openAnalyze(item.domain)} className="w-7 h-7 flex items-center justify-center border transition-colors text-white/30 border-white/10 hover:text-accent hover:bg-accent/10 hover:border-accent/20">
                        <Shield className="w-3.5 h-3.5" />
                      </button>

                      <a
                        href={item.url}
                        target={isPounce ? '_self' : '_blank'}
                        rel={isPounce ? undefined : 'noopener noreferrer'}
                        className={clsx("h-7 px-3 flex items-center gap-1.5 text-xs font-bold transition-colors", isPounce ? "bg-accent text-black hover:bg-white" : "bg-white/10 text-white hover:bg-white/20")}
                      >
                        {isPounce ? 'Buy' : 'Bid'}
                        {!isPounce && <ExternalLink className="w-3 h-3" />}
                      </a>
                    </div>
                  </div>
                </div>
              )
            })}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between pt-4">
              <div className="text-[10px] text-white/40 font-mono uppercase tracking-wider">
                Page {page}/{totalPages}
              </div>
              <div className="flex items-center gap-1">
                <button
                  onClick={() => handlePageChange(page - 1)}
                  disabled={page === 1}
                  className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/50 hover:text-white hover:bg-white/5 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                >
                  <ChevronLeft className="w-4 h-4" />
                </button>

                <span className="text-xs text-white/50 font-mono px-2">
                  {page}/{totalPages}
                </span>

                <button
                  onClick={() => handlePageChange(page + 1)}
                  disabled={page === totalPages}
                  className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/50 hover:text-white hover:bg-white/5 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                >
                  <ChevronRight className="w-4 h-4" />
                </button>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  )
}
