'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 { 
  PremiumTable, 
  Badge, 
  PlatformBadge, 
  StatCard, 
  PageContainer,
  SearchInput,
  TabBar,
  FilterBar,
  SelectDropdown,
  ActionButton,
} from '@/components/PremiumTable'
import {
  Clock,
  ExternalLink,
  Flame,
  Timer,
  Gavel,
  DollarSign,
  RefreshCw,
  Target,
  Loader2,
  Sparkles,
  Eye,
  Zap,
  Crown,
  Plus,
  Check,
} from 'lucide-react'
import Link from 'next/link'
import clsx from 'clsx'

interface Auction {
  domain: string
  platform: string
  platform_url: string
  current_bid: number
  currency: string
  num_bids: number
  end_time: string
  time_remaining: string
  buy_now_price: number | null
  reserve_met: boolean | null
  traffic: number | null
  age_years: number | null
  tld: string
  affiliate_url: string
}

interface Opportunity {
  auction: Auction
  analysis: {
    opportunity_score: number
    urgency?: string
    competition?: string
    price_range?: string
    recommendation: string
    reasoning?: string
  }
}

type TabType = 'all' | 'ending' | 'hot' | 'opportunities'
type SortField = 'ending' | 'bid_asc' | 'bid_desc' | 'bids' | 'score'
type FilterPreset = 'all' | 'no-trash' | 'short' | 'high-value' | 'low-competition'

const PLATFORMS = [
  { value: 'All', label: 'All Sources' },
  { value: 'GoDaddy', label: 'GoDaddy' },
  { value: 'Sedo', label: 'Sedo' },
  { value: 'NameJet', label: 'NameJet' },
  { value: 'DropCatch', label: 'DropCatch' },
]

const FILTER_PRESETS: { id: FilterPreset, label: string, icon: typeof Gavel, description: string, proOnly?: boolean }[] = [
  { id: 'all', label: 'All', icon: Gavel, description: 'Show all auctions' },
  { id: 'no-trash', label: 'No Trash', icon: Sparkles, description: 'Clean domains only (no spam)', proOnly: true },
  { id: 'short', label: 'Short', icon: Zap, description: '4-letter domains or less' },
  { id: 'high-value', label: 'High Value', icon: Crown, description: 'Premium TLDs with high activity', proOnly: true },
  { id: 'low-competition', label: 'Low Competition', icon: Target, description: 'Under 5 bids' },
]

const PREMIUM_TLDS = ['com', 'io', 'ai', 'co', 'net', 'org', 'app', 'dev']

// Pure functions (no hooks needed)
function isCleanDomain(auction: Auction): boolean {
  const name = auction.domain.split('.')[0]
  if (name.includes('-')) return false
  if (name.length > 4 && /\d/.test(name)) return false
  if (name.length > 12) return false
  if (!PREMIUM_TLDS.includes(auction.tld)) return false
  return true
}

function calculateDealScore(auction: Auction): number {
  let score = 50
  const name = auction.domain.split('.')[0]
  if (name.length <= 4) score += 25
  else if (name.length <= 6) score += 15
  else if (name.length <= 8) score += 5
  if (['com', 'io', 'ai'].includes(auction.tld)) score += 15
  else if (['co', 'net', 'org'].includes(auction.tld)) score += 5
  if (auction.age_years && auction.age_years > 10) score += 15
  else if (auction.age_years && auction.age_years > 5) score += 10
  if (auction.num_bids >= 20) score += 10
  else if (auction.num_bids >= 10) score += 5
  if (isCleanDomain(auction)) score += 10
  return Math.min(score, 100)
}

function getTimeColor(timeRemaining: string): string {
  if (timeRemaining.includes('m') && !timeRemaining.includes('h') && !timeRemaining.includes('d')) return 'text-red-400'
  if (timeRemaining.includes('h') && parseInt(timeRemaining) < 2) return 'text-amber-400'
  return 'text-foreground-muted'
}

const formatCurrency = (value: number) => {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(value)
}

export default function AuctionsPage() {
  const { isAuthenticated, subscription } = useStore()
  
  const [allAuctions, setAllAuctions] = useState<Auction[]>([])
  const [endingSoon, setEndingSoon] = useState<Auction[]>([])
  const [hotAuctions, setHotAuctions] = useState<Auction[]>([])
  const [opportunities, setOpportunities] = useState<Opportunity[]>([])
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const [activeTab, setActiveTab] = useState<TabType>('all')
  const [sortBy, setSortBy] = useState<SortField>('ending')
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')
  
  // Filters
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedPlatform, setSelectedPlatform] = useState('All')
  const [maxBid, setMaxBid] = useState('')
  const [filterPreset, setFilterPreset] = useState<FilterPreset>('all')
  const [trackedDomains, setTrackedDomains] = useState<Set<string>>(new Set())
  const [trackingInProgress, setTrackingInProgress] = useState<string | null>(null)
  
  const isPaidUser = subscription?.tier === 'trader' || subscription?.tier === 'tycoon'

  // Data loading
  const loadData = useCallback(async () => {
    setLoading(true)
    try {
      const [auctionsData, hotData, endingData] = await Promise.all([
        api.getAuctions(),
        api.getHotAuctions(50),
        api.getEndingSoonAuctions(24, 50),
      ])
      
      setAllAuctions(auctionsData.auctions || [])
      setHotAuctions(hotData || [])
      setEndingSoon(endingData || [])
    } catch (error) {
      console.error('Failed to load auction data:', error)
    } finally {
      setLoading(false)
    }
  }, [])

  const loadOpportunities = useCallback(async () => {
    try {
      const oppData = await api.getAuctionOpportunities()
      setOpportunities(oppData.opportunities || [])
    } catch (e) {
      console.error('Failed to load opportunities:', e)
    }
  }, [])

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

  useEffect(() => {
    if (isAuthenticated && opportunities.length === 0) {
      loadOpportunities()
    }
  }, [isAuthenticated, opportunities.length, loadOpportunities])

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

  const handleTrackDomain = useCallback(async (domain: string) => {
    if (trackedDomains.has(domain)) return
    
    setTrackingInProgress(domain)
    try {
      await api.addDomain(domain)
      setTrackedDomains(prev => new Set([...Array.from(prev), domain]))
    } catch (error) {
      console.error('Failed to track domain:', error)
    } finally {
      setTrackingInProgress(null)
    }
  }, [trackedDomains])

  const handleSort = useCallback((field: string) => {
    const f = field as SortField
    if (sortBy === f) {
      setSortDirection(d => d === 'asc' ? 'desc' : 'asc')
    } else {
      setSortBy(f)
      setSortDirection('asc')
    }
  }, [sortBy])

  // Memoized tabs
  const tabs = useMemo(() => [
    { id: 'all', label: 'All', icon: Gavel, count: allAuctions.length },
    { id: 'ending', label: 'Ending Soon', icon: Timer, count: endingSoon.length, color: 'warning' as const },
    { id: 'hot', label: 'Hot', icon: Flame, count: hotAuctions.length },
    { id: 'opportunities', label: 'Opportunities', icon: Target, count: opportunities.length },
  ], [allAuctions.length, endingSoon.length, hotAuctions.length, opportunities.length])

  // Filter and sort auctions
  const sortedAuctions = useMemo(() => {
    // Get base auctions for current tab
    let auctions: Auction[] = []
    switch (activeTab) {
      case 'ending': auctions = [...endingSoon]; break
      case 'hot': auctions = [...hotAuctions]; break
      case 'opportunities': auctions = opportunities.map(o => o.auction); break
      default: auctions = [...allAuctions]
    }

    // Apply preset filter
    const baseFilter = filterPreset === 'all' && isPaidUser ? 'no-trash' : filterPreset
    switch (baseFilter) {
      case 'no-trash': auctions = auctions.filter(isCleanDomain); break
      case 'short': auctions = auctions.filter(a => a.domain.split('.')[0].length <= 4); break
      case 'high-value': auctions = auctions.filter(a => 
        PREMIUM_TLDS.slice(0, 3).includes(a.tld) && a.num_bids >= 5 && calculateDealScore(a) >= 70
      ); break
      case 'low-competition': auctions = auctions.filter(a => a.num_bids < 5); break
    }

    // Apply search
    if (searchQuery) {
      const q = searchQuery.toLowerCase()
      auctions = auctions.filter(a => a.domain.toLowerCase().includes(q))
    }

    // Apply platform filter
    if (selectedPlatform !== 'All') {
      auctions = auctions.filter(a => a.platform === selectedPlatform)
    }

    // Apply max bid
    if (maxBid) {
      const max = parseFloat(maxBid)
      auctions = auctions.filter(a => a.current_bid <= max)
    }

    // Sort (skip for opportunities - already sorted by score)
    if (activeTab !== 'opportunities') {
      const mult = sortDirection === 'asc' ? 1 : -1
      auctions.sort((a, b) => {
        switch (sortBy) {
          case 'ending': return mult * (new Date(a.end_time).getTime() - new Date(b.end_time).getTime())
          case 'bid_asc':
          case 'bid_desc': return mult * (a.current_bid - b.current_bid)
          case 'bids': return mult * (b.num_bids - a.num_bids)
          case 'score': return mult * (calculateDealScore(b) - calculateDealScore(a))
          default: return 0
        }
      })
    }

    return auctions
  }, [activeTab, allAuctions, endingSoon, hotAuctions, opportunities, filterPreset, isPaidUser, searchQuery, selectedPlatform, maxBid, sortBy, sortDirection])

  // Subtitle
  const subtitle = useMemo(() => {
    if (loading) return 'Loading live auctions...'
    const total = allAuctions.length
    if (total === 0) return 'No active auctions found'
    return `${sortedAuctions.length.toLocaleString()} auctions ${sortedAuctions.length < total ? `(filtered from ${total.toLocaleString()})` : 'across 4 platforms'}`
  }, [loading, allAuctions.length, sortedAuctions.length])

  // Get opportunity data helper
  const getOpportunityData = useCallback((domain: string) => {
    if (activeTab !== 'opportunities') return null
    return opportunities.find(o => o.auction.domain === domain)?.analysis
  }, [activeTab, opportunities])

  // Table columns - memoized
  const columns = useMemo(() => [
    {
      key: 'domain',
      header: 'Domain',
      sortable: true,
      render: (a: Auction) => (
        <div>
          <a 
            href={a.affiliate_url}
            target="_blank"
            rel="noopener noreferrer"
            className="font-mono font-medium text-foreground hover:text-accent transition-colors"
          >
            {a.domain}
          </a>
          <div className="flex items-center gap-2 mt-1 lg:hidden">
            <PlatformBadge platform={a.platform} />
            {a.age_years && <span className="text-xs text-foreground-subtle">{a.age_years}y</span>}
          </div>
        </div>
      ),
    },
    {
      key: 'platform',
      header: 'Platform',
      hideOnMobile: true,
      render: (a: Auction) => (
        <div className="space-y-1">
          <PlatformBadge platform={a.platform} />
          {a.age_years && (
            <span className="text-xs text-foreground-subtle flex items-center gap-1">
              <Clock className="w-3 h-3" /> {a.age_years}y
            </span>
          )}
        </div>
      ),
    },
    {
      key: 'bid_asc',
      header: 'Bid',
      sortable: true,
      align: 'right' as const,
      render: (a: Auction) => (
        <div>
          <span className="font-medium text-foreground">{formatCurrency(a.current_bid)}</span>
          {a.buy_now_price && (
            <p className="text-xs text-accent">Buy: {formatCurrency(a.buy_now_price)}</p>
          )}
        </div>
      ),
    },
    {
      key: 'score',
      header: 'Deal Score',
      sortable: true,
      align: 'center' as const,
      hideOnMobile: true,
      render: (a: Auction) => {
        if (activeTab === 'opportunities') {
          const oppData = getOpportunityData(a.domain)
          if (oppData) {
            return (
              <span className="inline-flex items-center justify-center w-9 h-9 bg-accent/10 text-accent font-bold rounded-lg">
                {oppData.opportunity_score}
              </span>
            )
          }
        }
        
        if (!isPaidUser) {
          return (
            <Link
              href="/pricing"
              className="inline-flex items-center justify-center w-9 h-9 bg-foreground/5 text-foreground-subtle rounded-lg hover:bg-accent/10 hover:text-accent transition-all"
              title="Upgrade to see Deal Score"
            >
              <Crown className="w-4 h-4" />
            </Link>
          )
        }
        
        const score = calculateDealScore(a)
        return (
          <div className="inline-flex flex-col items-center">
            <span className={clsx(
              "inline-flex items-center justify-center w-9 h-9 rounded-lg font-bold text-sm",
              score >= 75 ? "bg-accent/20 text-accent" :
              score >= 50 ? "bg-amber-500/20 text-amber-400" :
              "bg-foreground/10 text-foreground-muted"
            )}>
              {score}
            </span>
            {score >= 75 && <span className="text-[10px] text-accent mt-0.5 font-medium">Undervalued</span>}
          </div>
        )
      },
    },
    {
      key: 'bids',
      header: 'Bids',
      sortable: true,
      align: 'right' as const,
      hideOnMobile: true,
      render: (a: Auction) => (
        <span className={clsx(
          "font-medium flex items-center justify-end gap-1",
          a.num_bids >= 20 ? "text-accent" : a.num_bids >= 10 ? "text-amber-400" : "text-foreground-muted"
        )}>
          {a.num_bids}
          {a.num_bids >= 20 && <Flame className="w-3 h-3" />}
        </span>
      ),
    },
    {
      key: 'ending',
      header: 'Time Left',
      sortable: true,
      align: 'right' as const,
      hideOnMobile: true,
      render: (a: Auction) => (
        <span className={clsx("font-medium", getTimeColor(a.time_remaining))}>
          {a.time_remaining}
        </span>
      ),
    },
    {
      key: 'actions',
      header: '',
      align: 'right' as const,
      render: (a: Auction) => (
        <div className="flex items-center gap-2 justify-end">
          <button
            onClick={(e) => { e.preventDefault(); handleTrackDomain(a.domain) }}
            disabled={trackedDomains.has(a.domain) || trackingInProgress === a.domain}
            className={clsx(
              "inline-flex items-center justify-center w-8 h-8 rounded-lg transition-all",
              trackedDomains.has(a.domain)
                ? "bg-accent/20 text-accent cursor-default"
                : "bg-foreground/5 text-foreground-subtle hover:bg-accent/10 hover:text-accent"
            )}
            title={trackedDomains.has(a.domain) ? 'Already tracked' : 'Add to Watchlist'}
          >
            {trackingInProgress === a.domain ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : trackedDomains.has(a.domain) ? (
              <Check className="w-4 h-4" />
            ) : (
              <Plus className="w-4 h-4" />
            )}
          </button>
          <a
            href={a.affiliate_url}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-1.5 px-4 py-2 bg-foreground text-background text-xs font-medium rounded-lg hover:bg-foreground/90 transition-all"
          >
            Bid <ExternalLink className="w-3 h-3" />
          </a>
        </div>
      ),
    },
  ], [activeTab, isPaidUser, trackedDomains, trackingInProgress, handleTrackDomain, getOpportunityData])

  return (
    <CommandCenterLayout
      title="Auctions"
      subtitle={subtitle}
      actions={
        <ActionButton onClick={handleRefresh} disabled={refreshing} variant="ghost" icon={refreshing ? Loader2 : RefreshCw}>
          {refreshing ? '' : 'Refresh'}
        </ActionButton>
      }
    >
      <PageContainer>
        {/* Stats */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <StatCard title="All Auctions" value={allAuctions.length} icon={Gavel} />
          <StatCard title="Ending Soon" value={endingSoon.length} icon={Timer} />
          <StatCard title="Hot Auctions" value={hotAuctions.length} subtitle="20+ bids" icon={Flame} />
          <StatCard title="Opportunities" value={opportunities.length} icon={Target} />
        </div>

        {/* Tabs */}
        <TabBar tabs={tabs} activeTab={activeTab} onChange={(id) => setActiveTab(id as TabType)} />

        {/* Smart Filter Presets */}
        <div className="flex flex-wrap gap-2 p-1.5 bg-background-secondary/30 border border-border/30 rounded-xl">
          {FILTER_PRESETS.map((preset) => {
            const isDisabled = preset.proOnly && !isPaidUser
            const isActive = filterPreset === preset.id
            const Icon = preset.icon
            return (
              <button
                key={preset.id}
                onClick={() => !isDisabled && setFilterPreset(preset.id)}
                disabled={isDisabled}
                title={isDisabled ? 'Upgrade to Trader to use this filter' : preset.description}
                className={clsx(
                  "flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-lg transition-all",
                  isActive
                    ? "bg-accent text-background shadow-md"
                    : isDisabled
                      ? "text-foreground-subtle opacity-50 cursor-not-allowed"
                      : "text-foreground-muted hover:text-foreground hover:bg-foreground/5"
                )}
              >
                <Icon className="w-4 h-4" />
                <span className="hidden sm:inline">{preset.label}</span>
                {preset.proOnly && !isPaidUser && <Crown className="w-3 h-3 text-amber-400" />}
              </button>
            )
          })}
        </div>

        {/* Tier notification for Scout users */}
        {!isPaidUser && (
          <div className="p-4 bg-amber-500/10 border border-amber-500/20 rounded-xl flex items-center gap-3">
            <div className="w-10 h-10 bg-amber-500/20 rounded-xl flex items-center justify-center shrink-0">
              <Eye className="w-5 h-5 text-amber-400" />
            </div>
            <div className="flex-1">
              <p className="text-sm font-medium text-foreground">You&apos;re seeing the raw auction feed</p>
              <p className="text-xs text-foreground-muted">
                Upgrade to Trader for spam-free listings, Deal Scores, and Smart Filters.
              </p>
            </div>
            <Link
              href="/pricing"
              className="shrink-0 px-4 py-2 bg-accent text-background text-sm font-medium rounded-lg hover:bg-accent-hover transition-all"
            >
              Upgrade
            </Link>
          </div>
        )}

        {/* Filters */}
        <FilterBar>
          <SearchInput
            value={searchQuery}
            onChange={setSearchQuery}
            placeholder="Search domains..."
            className="flex-1 min-w-[200px] max-w-md"
          />
          <SelectDropdown value={selectedPlatform} onChange={setSelectedPlatform} options={PLATFORMS} />
          <div className="relative">
            <DollarSign className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-foreground-muted" />
            <input
              type="number"
              placeholder="Max bid"
              value={maxBid}
              onChange={(e) => setMaxBid(e.target.value)}
              className="w-28 h-10 pl-9 pr-3 bg-background-secondary/50 border border-border/40 rounded-xl
                         text-sm text-foreground placeholder:text-foreground-subtle
                         focus:outline-none focus:border-accent/50 transition-all"
            />
          </div>
        </FilterBar>

        {/* Table */}
        <PremiumTable
          data={sortedAuctions}
          keyExtractor={(a) => `${a.domain}-${a.platform}`}
          loading={loading}
          sortBy={sortBy}
          sortDirection={sortDirection}
          onSort={handleSort}
          emptyIcon={<Gavel className="w-12 h-12 text-foreground-subtle" />}
          emptyTitle={searchQuery ? `No auctions matching "${searchQuery}"` : "No auctions found"}
          emptyDescription="Try adjusting your filters or check back later"
          columns={columns}
        />
      </PageContainer>
    </CommandCenterLayout>
  )
}
