'use client'

import { useEffect, useState, useMemo } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import { PlatformBadge } from '@/components/PremiumTable'
import {
  Clock,
  ExternalLink,
  Search,
  Flame,
  Timer,
  Gavel,
  DollarSign,
  X,
  Lock,
  TrendingUp,
  ChevronUp,
  ChevronDown,
  ChevronsUpDown,
  Sparkles,
} 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
}

type TabType = 'all' | 'ending' | 'hot'
type SortField = 'domain' | 'ending' | 'bid' | 'bids'
type SortDirection = 'asc' | 'desc'

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

// Premium TLDs that look professional (from analysis_1.md)
const PREMIUM_TLDS = ['com', 'io', 'ai', 'co', 'de', 'ch', 'net', 'org', 'app', 'dev', 'xyz']

// Vanity Filter: Only show "beautiful" domains to non-authenticated users (from analysis_1.md)
// Rules: No numbers (except short domains), no hyphens, length < 12, only premium TLDs
function isVanityDomain(auction: Auction): boolean {
  const domain = auction.domain
  const parts = domain.split('.')
  if (parts.length < 2) return false
  
  const name = parts[0]
  const tld = parts.slice(1).join('.').toLowerCase()
  
  // Check TLD is premium
  if (!PREMIUM_TLDS.includes(tld)) return false
  
  // Check length (max 12 characters for the name)
  if (name.length > 12) return false
  
  // No hyphens
  if (name.includes('-')) return false
  
  // No numbers (unless domain is 4 chars or less - short domains are valuable)
  if (name.length > 4 && /\d/.test(name)) return false
  
  return true
}

// Generate a mock "Deal Score" for display purposes
// In production, this would come from a valuation API
function getDealScore(auction: Auction): number | null {
  // Simple heuristic based on domain characteristics
  let score = 50
  
  // Short domains are more valuable
  const name = auction.domain.split('.')[0]
  if (name.length <= 4) score += 20
  else if (name.length <= 6) score += 10
  
  // Premium TLDs
  if (['com', 'io', 'ai'].includes(auction.tld)) score += 15
  
  // Age bonus
  if (auction.age_years && auction.age_years > 5) score += 10
  
  // High competition = good domain
  if (auction.num_bids >= 20) score += 15
  else if (auction.num_bids >= 10) score += 10
  
  // Cap at 100
  return Math.min(score, 100)
}

function SortIcon({ field, currentField, direction }: { field: SortField, currentField: SortField, direction: SortDirection }) {
  if (field !== currentField) {
    return <ChevronsUpDown className="w-4 h-4 text-foreground-subtle" />
  }
  return direction === 'asc' 
    ? <ChevronUp className="w-4 h-4 text-accent" />
    : <ChevronDown className="w-4 h-4 text-accent" />
}

export default function AuctionsPage() {
  const { isAuthenticated, checkAuth, isLoading: authLoading } = useStore()
  
  const [allAuctions, setAllAuctions] = useState<Auction[]>([])
  const [endingSoon, setEndingSoon] = useState<Auction[]>([])
  const [hotAuctions, setHotAuctions] = useState<Auction[]>([])
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState<TabType>('all')
  const [sortField, setSortField] = useState<SortField>('ending')
  const [sortDirection, setSortDirection] = useState<SortDirection>('asc')
  
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedPlatform, setSelectedPlatform] = useState('All')
  const [maxBid, setMaxBid] = useState('')

  useEffect(() => {
    checkAuth()
    loadAuctions()
  }, [checkAuth])

  const loadAuctions = async () => {
    setLoading(true)
    try {
      const [all, ending, hot] = await Promise.all([
        api.getAuctions(undefined, undefined, undefined, undefined, undefined, false, 'ending', 100, 0),
        api.getEndingSoonAuctions(50),
        api.getHotAuctions(50),
      ])
      setAllAuctions(all.auctions || [])
      setEndingSoon(ending || [])
      setHotAuctions(hot || [])
    } catch (error) {
      console.error('Failed to load auctions:', error)
    } finally {
      setLoading(false)
    }
  }

  const getCurrentAuctions = (): Auction[] => {
    switch (activeTab) {
      case 'ending': return endingSoon
      case 'hot': return hotAuctions
      default: return allAuctions
    }
  }

  // Apply Vanity Filter for non-authenticated users (from analysis_1.md)
  // Shows only "beautiful" domains to visitors - no spam/trash
  const displayAuctions = useMemo(() => {
    const current = getCurrentAuctions()
    if (isAuthenticated) {
      // Authenticated users see all auctions
      return current
    }
    // Non-authenticated users only see "vanity" domains (clean, professional-looking)
    return current.filter(isVanityDomain)
  }, [activeTab, allAuctions, endingSoon, hotAuctions, isAuthenticated])

  const filteredAuctions = displayAuctions.filter(auction => {
    if (searchQuery && !auction.domain.toLowerCase().includes(searchQuery.toLowerCase())) {
      return false
    }
    if (selectedPlatform !== 'All' && auction.platform !== selectedPlatform) {
      return false
    }
    if (maxBid && auction.current_bid > parseFloat(maxBid)) {
      return false
    }
    return true
  })

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc')
    } else {
      setSortField(field)
      setSortDirection('asc')
    }
  }

  const sortedAuctions = [...filteredAuctions].sort((a, b) => {
    const modifier = sortDirection === 'asc' ? 1 : -1
    switch (sortField) {
      case 'domain':
        return a.domain.localeCompare(b.domain) * modifier
      case 'bid':
        return (a.current_bid - b.current_bid) * modifier
      case 'bids':
        return (a.num_bids - b.num_bids) * modifier
      default:
        return 0
    }
  })

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

  const getTimeColor = (timeRemaining: string) => {
    if (timeRemaining.includes('m') && !timeRemaining.includes('h')) return 'text-red-400'
    if (timeRemaining.includes('h') && parseInt(timeRemaining) < 12) return 'text-amber-400'
    return 'text-foreground-muted'
  }

  // Hot auctions preview for the hero section
  const hotPreview = hotAuctions.slice(0, 4)

  if (authLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="w-5 h-5 border-2 border-accent border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background relative overflow-hidden">
      {/* Background Effects - matching landing page */}
      <div className="fixed inset-0 pointer-events-none">
        <div className="absolute top-[-20%] left-1/2 -translate-x-1/2 w-[1200px] h-[800px] bg-accent/[0.03] rounded-full blur-[120px]" />
        <div className="absolute bottom-[-10%] right-[-10%] w-[600px] h-[600px] bg-accent/[0.02] rounded-full blur-[100px]" />
        <div 
          className="absolute inset-0 opacity-[0.015]"
          style={{
            backgroundImage: `linear-gradient(rgba(255,255,255,.1) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.1) 1px, transparent 1px)`,
            backgroundSize: '64px 64px',
          }}
        />
      </div>

      <Header />

      <main className="relative pt-32 sm:pt-40 pb-20 sm:pb-28 px-4 sm:px-6 flex-1">
        <div className="max-w-7xl mx-auto">
          {/* Hero Header - centered like TLD pricing */}
          <div className="text-center mb-16 sm:mb-20 animate-fade-in">
            <span className="text-sm font-semibold text-accent uppercase tracking-wider">Live Market</span>
            <h1 className="mt-4 font-display text-[2.5rem] sm:text-[3.5rem] md:text-[4.5rem] lg:text-[5rem] leading-[0.95] tracking-[-0.03em] text-foreground">
              {/* Use "Live Feed" or "Curated Opportunities" if count is small (from report.md) */}
              {allAuctions.length >= 50 
                ? `${allAuctions.length}+ Live Auctions` 
                : 'Live Auction Feed'}
            </h1>
            <p className="mt-5 text-lg sm:text-xl text-foreground-muted max-w-2xl mx-auto">
              {isAuthenticated 
                ? 'All auctions from GoDaddy, Sedo, NameJet & DropCatch. Unfiltered.'
                : 'Curated opportunities from GoDaddy, Sedo, NameJet & DropCatch.'}
            </p>
            {!isAuthenticated && displayAuctions.length < allAuctions.length && (
              <p className="mt-2 text-sm text-accent flex items-center justify-center gap-1">
                <Sparkles className="w-4 h-4" />
                Showing {displayAuctions.length} premium domains • Sign in to see all {allAuctions.length}
              </p>
            )}
          </div>

          {/* Login Banner for non-authenticated users */}
          {!isAuthenticated && (
            <div className="mb-8 p-5 bg-accent-muted border border-accent/20 rounded-xl flex flex-col sm:flex-row items-center justify-between gap-4 animate-fade-in">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-accent/20 rounded-xl flex items-center justify-center">
                  <Lock className="w-5 h-5 text-accent" />
                </div>
                <div>
                  <p className="text-body-sm font-medium text-foreground">Unlock Smart Opportunities</p>
                  <p className="text-ui-sm text-foreground-muted">
                    Sign in for AI-powered analysis and personalized recommendations.
                  </p>
                </div>
              </div>
              <Link
                href="/register"
                className="shrink-0 px-5 py-2.5 bg-accent text-background text-ui font-medium rounded-lg
                           hover:bg-accent-hover transition-all duration-300"
              >
                Hunt Free
              </Link>
            </div>
          )}

          {/* Hot Auctions Preview */}
          {hotPreview.length > 0 && (
            <div className="mb-12 sm:mb-16 animate-slide-up">
              <h2 className="text-body-lg sm:text-heading-sm font-medium text-foreground mb-4 sm:mb-6 flex items-center gap-2">
                <Flame className="w-5 h-5 text-accent" />
                Hot Right Now
              </h2>
              <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
                {hotPreview.map((auction) => (
                  <a
                    key={`${auction.domain}-${auction.platform}`}
                    href={auction.affiliate_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="p-4 sm:p-5 bg-background-secondary/50 border border-border rounded-xl hover:border-border-hover hover:bg-background-secondary transition-all duration-300 text-left group"
              >
                    <div className="flex items-center justify-between mb-3">
                      <span className="font-mono text-body-lg sm:text-heading-sm text-foreground group-hover:text-accent transition-colors">
                        {auction.domain}
                      </span>
                      <span className="text-ui-sm font-medium px-2 py-0.5 rounded-full text-accent bg-accent-muted flex items-center gap-1">
                        <Flame className="w-3 h-3" />
                        {auction.num_bids}
                      </span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-body-sm text-foreground-muted">
                        {formatCurrency(auction.current_bid)}
                      </span>
                      <span className={clsx("text-body-sm", getTimeColor(auction.time_remaining))}>
                        {auction.time_remaining}
                      </span>
                    </div>
                    <div className="mt-2">
                      <PlatformBadge platform={auction.platform} />
                    </div>
                  </a>
                ))}
              </div>
            </div>
          )}

          {/* Search & Filters */}
          <div className="mb-6 animate-slide-up">
            <div className="flex flex-wrap gap-3">
              <div className="relative flex-1 min-w-[200px] max-w-md">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-foreground-subtle" />
                <input
                  type="text"
                  placeholder="Search domains..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-12 pr-10 py-3 bg-background-secondary/50 border border-border rounded-xl
                             text-body text-foreground placeholder:text-foreground-subtle
                             focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent
                             transition-all duration-300"
                />
                {searchQuery && (
                  <button
                    onClick={() => setSearchQuery('')}
                    className="absolute right-4 top-1/2 -translate-y-1/2 p-1 text-foreground-subtle hover:text-foreground transition-colors"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
              <select
                value={selectedPlatform}
                onChange={(e) => setSelectedPlatform(e.target.value)}
                className="px-4 py-3 bg-background-secondary/50 border border-border rounded-xl
                           text-body text-foreground cursor-pointer focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent"
              >
                {PLATFORMS.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
              </select>
              <div className="relative">
                <DollarSign className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-foreground-subtle" />
                <input
                  type="number"
                  placeholder="Max bid"
                  value={maxBid}
                  onChange={(e) => setMaxBid(e.target.value)}
                  className="w-32 pl-10 pr-4 py-3 bg-background-secondary/50 border border-border rounded-xl
                             text-body text-foreground placeholder:text-foreground-subtle
                             focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent"
                />
              </div>
            </div>
          </div>

          {/* Tabs */}
          <div className="flex flex-wrap gap-2 mb-6 animate-slide-up">
            {[
              { id: 'all' as const, label: 'All Auctions', icon: Gavel, count: allAuctions.length },
              { id: 'ending' as const, label: 'Ending Soon', icon: Timer, count: endingSoon.length },
              { id: 'hot' as const, label: 'Hot', icon: Flame, count: hotAuctions.length },
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={clsx(
                  "flex items-center gap-2 px-4 py-2.5 text-ui-sm font-medium rounded-xl transition-all",
                  activeTab === tab.id
                    ? "bg-accent text-background"
                    : "bg-background-secondary/50 text-foreground-muted hover:text-foreground hover:bg-background-secondary border border-border"
                )}
              >
                <tab.icon className="w-4 h-4" />
                {tab.label}
                <span className={clsx(
                  "text-xs px-1.5 py-0.5 rounded",
                  activeTab === tab.id ? "bg-background/20" : "bg-foreground/10"
                )}>{tab.count}</span>
              </button>
            ))}
            </div>

          {/* Auctions Table */}
            <div className="bg-background-secondary/30 border border-border rounded-xl overflow-hidden animate-slide-up">
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="bg-background-secondary border-b border-border">
                      <th className="text-left px-4 sm:px-6 py-4">
                        <button
                        onClick={() => handleSort('domain')}
                          className="flex items-center gap-2 text-ui-sm text-foreground-subtle font-medium hover:text-foreground transition-colors"
                        >
                          Domain
                        <SortIcon field="domain" currentField={sortField} direction={sortDirection} />
                        </button>
                      </th>
                      <th className="text-left px-4 sm:px-6 py-4 hidden lg:table-cell">
                        <span className="text-ui-sm text-foreground-subtle font-medium">Platform</span>
                      </th>
                      <th className="text-right px-4 sm:px-6 py-4">
                        <button
                        onClick={() => handleSort('bid')}
                          className="flex items-center gap-2 ml-auto text-ui-sm text-foreground-subtle font-medium hover:text-foreground transition-colors"
                        >
                        Current Bid
                        <SortIcon field="bid" currentField={sortField} direction={sortDirection} />
                        </button>
                      </th>
                    <th className="text-center px-4 sm:px-6 py-4 hidden md:table-cell">
                      <span className="text-ui-sm text-foreground-subtle font-medium flex items-center justify-center gap-1">
                        Deal Score
                        {!isAuthenticated && <Lock className="w-3 h-3" />}
                      </span>
                    </th>
                      <th className="text-right px-4 sm:px-6 py-4 hidden sm:table-cell">
                        <button
                          onClick={() => handleSort('bids')}
                          className="flex items-center gap-2 ml-auto text-ui-sm text-foreground-subtle font-medium hover:text-foreground transition-colors"
                        >
                          Bids
                        <SortIcon field="bids" currentField={sortField} direction={sortDirection} />
                        </button>
                      </th>
                      <th className="text-right px-4 sm:px-6 py-4 hidden md:table-cell">
                      <button
                        onClick={() => handleSort('ending')}
                        className="flex items-center gap-2 ml-auto text-ui-sm text-foreground-subtle font-medium hover:text-foreground transition-colors"
                      >
                        Time Left
                        <SortIcon field="ending" currentField={sortField} direction={sortDirection} />
                      </button>
                        </th>
                      <th className="px-4 sm:px-6 py-4"></th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                  {loading ? (
                    // Loading skeleton
                    Array.from({ length: 10 }).map((_, idx) => (
                      <tr key={idx} className="animate-pulse">
                        <td className="px-4 sm:px-6 py-4"><div className="h-4 w-32 bg-background-tertiary rounded" /></td>
                        <td className="px-4 sm:px-6 py-4 hidden lg:table-cell"><div className="h-4 w-20 bg-background-tertiary rounded" /></td>
                        <td className="px-4 sm:px-6 py-4"><div className="h-4 w-16 bg-background-tertiary rounded ml-auto" /></td>
                        <td className="px-4 sm:px-6 py-4 hidden md:table-cell"><div className="h-8 w-8 bg-background-tertiary rounded mx-auto" /></td>
                        <td className="px-4 sm:px-6 py-4 hidden sm:table-cell"><div className="h-4 w-12 bg-background-tertiary rounded ml-auto" /></td>
                        <td className="px-4 sm:px-6 py-4 hidden md:table-cell"><div className="h-4 w-16 bg-background-tertiary rounded ml-auto" /></td>
                        <td className="px-4 sm:px-6 py-4"><div className="h-8 w-16 bg-background-tertiary rounded ml-auto" /></td>
                      </tr>
                    ))
                  ) : sortedAuctions.length === 0 ? (
                    <tr>
                      <td colSpan={7} className="px-6 py-12 text-center text-foreground-muted">
                        {searchQuery ? `No auctions found matching "${searchQuery}"` : 'No auctions found'}
                        </td>
                      </tr>
                    ) : (
                    sortedAuctions.map((auction) => (
                          <tr
                        key={`${auction.domain}-${auction.platform}`}
                            className="hover:bg-background-secondary/50 transition-colors group"
                          >
                            <td className="px-4 sm:px-6 py-4">
                          <div>
                                <a 
                                  href={auction.affiliate_url}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="font-mono text-body-sm sm:text-body font-medium text-foreground hover:text-accent transition-colors"
                                >
                                  {auction.domain}
                                </a>
                            <div className="flex items-center gap-2 mt-1 lg:hidden">
                              <PlatformBadge platform={auction.platform} />
                                </div>
                              </div>
                            </td>
                            <td className="px-4 sm:px-6 py-4 hidden lg:table-cell">
                          <div className="space-y-1">
                            <PlatformBadge platform={auction.platform} />
                                {auction.age_years && (
                              <span className="text-ui-sm text-foreground-subtle flex items-center gap-1">
                                <Clock className="w-3 h-3" /> {auction.age_years}y
                                  </span>
                                )}
                              </div>
                            </td>
                            <td className="px-4 sm:px-6 py-4 text-right">
                          <div>
                            <span className="text-body-sm font-medium text-foreground">
                                {formatCurrency(auction.current_bid)}
                              </span>
                              {auction.buy_now_price && (
                              <p className="text-ui-sm text-accent">Buy: {formatCurrency(auction.buy_now_price)}</p>
                            )}
                          </div>
                        </td>
                        {/* Deal Score Column - locked for non-authenticated users */}
                        <td className="px-4 sm:px-6 py-4 text-center hidden md:table-cell">
                          {isAuthenticated ? (
                            <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",
                                (getDealScore(auction) ?? 0) >= 75 ? "bg-accent/20 text-accent" :
                                (getDealScore(auction) ?? 0) >= 50 ? "bg-amber-500/20 text-amber-400" :
                                "bg-foreground/10 text-foreground-muted"
                              )}>
                                {getDealScore(auction)}
                              </span>
                              {(getDealScore(auction) ?? 0) >= 75 && (
                                <span className="text-[10px] text-accent mt-0.5 font-medium">Undervalued</span>
                              )}
                            </div>
                          ) : (
                            <Link
                              href="/login?redirect=/auctions"
                              className="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-foreground/5 text-foreground-subtle 
                                         hover:bg-accent/10 hover:text-accent transition-all group"
                              title="Sign in to see Deal Score"
                            >
                              <Lock className="w-4 h-4 group-hover:scale-110 transition-transform" />
                            </Link>
                              )}
                            </td>
                            <td className="px-4 sm:px-6 py-4 text-right hidden sm:table-cell">
                          <span className={clsx(
                            "font-medium flex items-center justify-end gap-1",
                            auction.num_bids >= 20 ? "text-accent" : auction.num_bids >= 10 ? "text-amber-400" : "text-foreground-muted"
                          )}>
                                {auction.num_bids}
                                {auction.num_bids >= 20 && <Flame className="w-3 h-3" />}
                              </span>
                            </td>
                            <td className="px-4 sm:px-6 py-4 text-right hidden md:table-cell">
                          <span className={clsx("font-medium", getTimeColor(auction.time_remaining))}>
                                {auction.time_remaining}
                              </span>
                            </td>
                        <td className="px-4 sm:px-6 py-4">
                              <a
                                href={auction.affiliate_url}
                                target="_blank"
                                rel="noopener noreferrer"
                            className="inline-flex items-center gap-1 text-ui-sm text-accent hover:text-accent-hover transition-colors opacity-0 group-hover:opacity-100"
                              >
                                Bid
                            <ExternalLink className="w-3 h-3" />
                              </a>
                            </td>
                          </tr>
                    ))
                    )}
                  </tbody>
                </table>
              </div>
            </div>

          {/* Stats */}
          {!loading && (
            <div className="mt-6 flex justify-center">
              <p className="text-ui-sm text-foreground-subtle">
                {searchQuery 
                  ? `Found ${sortedAuctions.length} auctions matching "${searchQuery}"`
                  : `${allAuctions.length} auctions available across ${PLATFORMS.length - 1} platforms`
                }
              </p>
            </div>
          )}
        </div>
      </main>

      <Footer />
    </div>
  )
}
