'use client'

import { useEffect, useState, useMemo, useCallback, memo } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { CommandCenterLayout } from '@/components/CommandCenterLayout'
import { 
  ExternalLink,
  Loader2,
  Diamond,
  Zap,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  Plus,
  Check,
  TrendingUp,
  RefreshCw,
  Clock,
  Search,
  Eye,
  EyeOff,
  ShieldCheck,
  Store,
  Gavel,
  Ban,
  Activity,
  Target,
  ArrowRight
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'

// ============================================================================
// 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 SortField = 'domain' | 'score' | 'price' | 'time' | 'source'
type SortDirection = 'asc' | 'desc'
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]
  return /[-\d]/.test(name)
}

// ============================================================================
// MAIN PAGE
// ============================================================================

export default function MarketPage() {
  const { subscription } = useStore()
  
  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 [sortField, setSortField] = useState<SortField>('score')
  const [sortDirection, setSortDirection] = useState<SortDirection>('desc')
  
  const [trackedDomains, setTrackedDomains] = useState<Set<string>>(new Set())
  const [trackingInProgress, setTrackingInProgress] = useState<string | null>(null)
  
  // Pagination
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const ITEMS_PER_PAGE = 50

  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: sortField === 'score' ? 'score' : 
                sortField === 'price' ? (sortDirection === 'asc' ? 'price_asc' : 'price_desc') :
                sortField === 'time' ? 'time' : 'newest',
        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 => 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, sortField, sortDirection, 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])

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

  // Load user's tracked domains on mount
  useEffect(() => {
    const loadTrackedDomains = async () => {
      try {
        const result = await api.getDomains(1, 100)
        const domainSet = new Set(result.items.map(d => d.domain))
        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)) {
        // Find and delete the domain
        const result = await api.getDomains(1, 100)
        const domainToDelete = result.items.find(d => d.domain === domain)
        if (domainToDelete) {
          await api.deleteDomain(domainToDelete.id)
          setTrackedDomains(prev => {
            const next = new Set(Array.from(prev))
            next.delete(domain)
            return next
          })
        }
      } else {
        // Add the domain
        await api.addDomain(domain)
        setTrackedDomains(prev => new Set([...Array.from(prev), domain]))
      }
    } catch (error) { 
      console.error(error) 
    } finally { 
      setTrackingInProgress(null) 
    }
  }, [trackedDomains, trackingInProgress])

  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 = [...filtered].sort((a, b) => {
      if (sortField === 'score' && a.is_pounce !== b.is_pounce) {
        return a.is_pounce ? -1 : 1
      }
      
      switch (sortField) {
        case 'domain': return mult * a.domain.localeCompare(b.domain)
        case 'score': return mult * (a.pounce_score - b.pounce_score)
        case 'price': return mult * (a.price - b.price)
        case 'time': return mult * (getSecondsUntilEnd(a.end_time) - getSecondsUntilEnd(b.end_time))
        case 'source': return mult * a.source.localeCompare(b.source)
        default: return 0
      }
    })
    
    return filtered
  }, [items, searchQuery, sortField, sortDirection, loading, hideSpam])

  return (
    <CommandCenterLayout minimal>
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* HEADER */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <section className="pt-6 lg:pt-8 pb-6">
        <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-6">
          <div className="space-y-3">
            <div className="inline-flex items-center gap-2">
              <Gavel className="w-4 h-4 text-accent" />
              <span className="text-[10px] font-mono tracking-wide text-accent">Live Auctions</span>
            </div>
            
            <h1 className="font-display text-[2rem] lg:text-[2.5rem] leading-[1] tracking-[-0.02em]">
              <span className="text-white">Market</span>
              <span className="text-white/30 ml-3">{stats.total}</span>
            </h1>
          </div>
          
          <div className="flex gap-6 lg:gap-8">
            <div className="text-right">
              <div className="text-xl font-display text-accent">{stats.pounceCount}</div>
              <div className="text-[9px] tracking-wide text-white/30 font-mono">Pounce Direct</div>
            </div>
            <div className="text-right">
              <div className="text-xl font-display text-white">{stats.auctionCount}</div>
              <div className="text-[9px] tracking-wide text-white/30 font-mono">External</div>
            </div>
            <div className="text-right">
              <div className="text-xl font-display text-amber-400">{stats.highScore}</div>
              <div className="text-[9px] tracking-wide text-white/30 font-mono">Score 80+</div>
            </div>
          </div>
        </div>
      </section>

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* FILTERS */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <section className="pb-6 border-b border-white/[0.08]">
        <div className="flex flex-wrap items-center gap-2">
          {/* Source Filters */}
          <button
            onClick={() => setSourceFilter('all')}
            className={clsx(
              "px-3 py-1.5 text-xs font-medium transition-colors",
              sourceFilter === 'all' ? "bg-white/10 text-white" : "text-white/40 hover:text-white/60"
            )}
          >
            All
          </button>
          <button
            onClick={() => setSourceFilter('pounce')}
            className={clsx(
              "px-3 py-1.5 text-xs font-medium transition-colors flex items-center gap-1.5",
              sourceFilter === 'pounce' ? "bg-accent/20 text-accent" : "text-white/40 hover:text-white/60"
            )}
          >
            <Diamond className="w-3 h-3" />
            Pounce Only
          </button>
          
          <div className="w-px h-5 bg-white/10" />
          
          {/* TLD Filter */}
          <select
            value={tldFilter}
            onChange={(e) => setTldFilter(e.target.value)}
            className="bg-transparent border border-white/10 text-white text-xs px-3 py-1.5 outline-none hover:border-white/20"
          >
            <option value="all" className="bg-black">All TLDs</option>
            <option value="com" className="bg-black">.com</option>
            <option value="ai" className="bg-black">.ai</option>
            <option value="io" className="bg-black">.io</option>
            <option value="net" className="bg-black">.net</option>
          </select>
          
          <div className="w-px h-5 bg-white/10" />
          
          {/* Price Filters */}
          {[
            { value: 'low', label: '< $100' },
            { value: 'mid', label: '< $1k' },
            { value: 'high', label: '$1k+' },
          ].map((item) => (
            <button
              key={item.value}
              onClick={() => setPriceRange(p => p === item.value ? 'all' : item.value as PriceRange)}
              className={clsx(
                "px-3 py-1.5 text-xs font-medium transition-colors",
                priceRange === item.value ? "bg-white/10 text-white" : "text-white/40 hover:text-white/60"
              )}
            >
              {item.label}
            </button>
          ))}
          
          <div className="w-px h-5 bg-white/10" />
          
          {/* Hide Spam */}
          <button
            onClick={() => setHideSpam(!hideSpam)}
            className={clsx(
              "px-3 py-1.5 text-xs font-medium transition-colors flex items-center gap-1.5",
              hideSpam ? "bg-white/10 text-white" : "text-white/40 hover:text-white/60"
            )}
          >
            <Ban className="w-3 h-3" />
            Hide spam
          </button>
          
          {/* Search - Right aligned */}
          <div className="flex-1" />
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/30" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search domains..."
              className="bg-[#050505] border border-white/10 pl-9 pr-4 py-2 text-sm text-white placeholder:text-white/25 outline-none focus:border-accent/40 w-48 lg:w-64"
            />
          </div>
          
          {/* Refresh */}
          <button
            onClick={handleRefresh}
            disabled={refreshing}
            className="p-2 text-white/30 hover:text-white transition-colors"
          >
            <RefreshCw className={clsx("w-4 h-4", refreshing && "animate-spin")} />
          </button>
        </div>
      </section>

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* TABLE */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <section className="py-6">
        {loading ? (
          <div className="flex items-center justify-center py-20">
            <Loader2 className="w-6 h-6 text-accent animate-spin" />
          </div>
        ) : filteredItems.length === 0 ? (
          <div className="text-center py-16">
            <div className="w-14 h-14 mx-auto bg-white/[0.02] border border-white/10 rounded-lg flex items-center justify-center mb-4">
              <Search className="w-6 h-6 text-white/20" />
            </div>
            <p className="text-white/40 text-sm">No domains found</p>
            <p className="text-white/25 text-xs mt-1">Try adjusting your filters</p>
          </div>
        ) : (
          <div className="space-y-px">
            {/* Table Header */}
            <div className="hidden lg:grid grid-cols-[1fr_80px_100px_100px_120px] gap-4 px-4 py-2 text-xs text-white/40 border-b border-white/[0.06]">
              <div>Domain</div>
              <div className="text-center">Score</div>
              <div className="text-right">Price</div>
              <div className="text-center">Time</div>
              <div className="text-right">Actions</div>
            </div>
            
            {/* Rows */}
            {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(
                    "group border border-white/[0.05] hover:border-white/[0.08] transition-all",
                    isPounce ? "bg-accent/[0.02]" : "bg-white/[0.01]"
                  )}
                >
                  {/* Mobile */}
                  <div className="lg:hidden p-4">
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center gap-3">
                        {isPounce ? (
                          <Diamond className="w-4 h-4 text-accent" />
                        ) : (
                          <span className="text-[10px] font-mono text-white/30">{item.source.substring(0, 3)}</span>
                        )}
                        <span className="text-sm font-medium text-white">{item.domain}</span>
                      </div>
                      <span className={clsx(
                        "text-sm font-mono font-medium",
                        isPounce ? "text-accent" : "text-white"
                      )}>
                        {formatPrice(item.price)}
                      </span>
                    </div>
                    <div className="flex items-center justify-between text-xs text-white/40">
                      <span>Score: {item.pounce_score}</span>
                      <span>{displayTime || 'Instant'}</span>
                    </div>
                    {/* Mobile Actions */}
                    <div className="flex items-center gap-2 mt-3 pt-3 border-t border-white/[0.05]">
                      <button
                        onClick={() => handleTrack(item.domain)}
                        disabled={isTracking}
                        className={clsx(
                          "flex-1 h-8 flex items-center justify-center gap-2 text-xs font-medium border transition-colors",
                          isTracked 
                            ? "bg-accent/10 text-accent border-accent/20" 
                            : "text-white/50 border-white/10 hover:text-white"
                        )}
                      >
                        {isTracking ? <Loader2 className="w-3 h-3 animate-spin" /> : isTracked ? <Eye className="w-3 h-3" /> : <EyeOff className="w-3 h-3" />}
                        {isTracked ? 'Tracking' : 'Track'}
                      </button>
                      <a
                        href={item.url}
                        target={isPounce ? "_self" : "_blank"}
                        rel={isPounce ? undefined : "noopener noreferrer"}
                        className={clsx(
                          "flex-1 h-8 flex items-center justify-center gap-1.5 text-xs font-semibold",
                          isPounce ? "bg-accent text-black" : "bg-white/10 text-white"
                        )}
                      >
                        {isPounce ? 'Buy' : 'Bid'}
                        {!isPounce && <ExternalLink className="w-3 h-3" />}
                      </a>
                    </div>
                  </div>
                  
                  {/* Desktop */}
                  <div className="hidden lg:grid grid-cols-[1fr_80px_100px_100px_120px] gap-4 items-center px-4 py-3">
                    {/* Domain */}
                    <div className="flex items-center gap-3 min-w-0">
                      {isPounce ? (
                        <div className="w-8 h-8 bg-accent/10 border border-accent/20 flex items-center justify-center shrink-0">
                          <Diamond className="w-4 h-4 text-accent" />
                        </div>
                      ) : (
                        <div className="w-8 h-8 bg-white/5 border border-white/10 flex items-center justify-center text-[10px] font-mono text-white/40 shrink-0">
                          {item.source.substring(0, 2).toUpperCase()}
                        </div>
                      )}
                      <div className="min-w-0">
                        <div className="text-sm font-medium text-white truncate">{item.domain}</div>
                        <div className="text-[10px] text-white/30 flex items-center gap-1.5">
                          {item.source}
                          {isPounce && item.verified && (
                            <>
                              <span className="text-white/20">·</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/20">·</span>{item.num_bids} bids</> : null}
                        </div>
                      </div>
                    </div>
                    
                    {/* Score */}
                    <div className="text-center">
                      <span className={clsx(
                        "text-xs font-mono font-medium 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>
                    
                    {/* Price */}
                    <div className="text-right">
                      <div className={clsx(
                        "font-mono text-sm font-medium",
                        isPounce ? "text-accent" : "text-white"
                      )}>
                        {formatPrice(item.price)}
                      </div>
                      <div className="text-[10px] text-white/30">
                        {item.price_type === 'bid' ? 'Bid' : 'Buy Now'}
                      </div>
                    </div>
                    
                    {/* Time */}
                    <div className="text-center">
                      {isPounce ? (
                        <span className="text-xs text-accent font-medium 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>
                    
                    {/* Actions */}
                    <div className="flex items-center justify-end gap-2 opacity-50 group-hover:opacity-100 transition-opacity">
                      <button
                        onClick={() => handleTrack(item.domain)}
                        disabled={isTracking}
                        title={isTracked ? "Stop tracking" : "Start tracking"}
                        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>
                      
                      <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-semibold 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 */}
        {!loading && totalPages > 1 && (
          <div className="flex items-center justify-between pt-6">
            <div className="text-xs text-white/40 font-mono">
              Page {page} of {totalPages} · {stats.total} domains
            </div>
            <div className="flex items-center gap-2">
              <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>
              
              {/* Page Numbers */}
              <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 (page <= 3) {
                    pageNum = i + 1
                  } else if (page >= totalPages - 2) {
                    pageNum = totalPages - 4 + i
                  } else {
                    pageNum = page - 2 + i
                  }
                  
                  return (
                    <button
                      key={pageNum}
                      onClick={() => handlePageChange(pageNum)}
                      className={clsx(
                        "w-8 h-8 flex items-center justify-center text-xs font-mono border transition-colors",
                        page === pageNum
                          ? "bg-accent text-black border-accent"
                          : "border-white/10 text-white/50 hover:text-white hover:bg-white/5"
                      )}
                    >
                      {pageNum}
                    </button>
                  )
                })}
              </div>
              
              <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>
        )}
      </section>
    </CommandCenterLayout>
  )
}