'use client'

import { useEffect, useState, useMemo, useCallback, useRef } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { CommandCenterLayout } from '@/components/CommandCenterLayout'
import { Toast, useToast } from '@/components/Toast'
import {
  Eye,
  Gavel,
  Clock,
  ExternalLink,
  Plus,
  Activity,
  Search,
  ArrowRight,
  CheckCircle2,
  XCircle,
  Loader2,
  Crosshair,
  Radar,
  Zap,
  Globe,
  Target,
  Cpu,
  Radio
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'

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

interface HotAuction {
  domain: string
  current_bid: number
  time_remaining: string
  platform: string
  affiliate_url?: string
}

interface TrendingTld {
  tld: string
  current_price: number
  price_change: number
  reason: string
}

interface SearchResult {
  domain: string
  status: string
  is_available: boolean | null
  registrar: string | null
  expiration_date: string | null
  loading: boolean
  inAuction: boolean
  auctionData?: HotAuction
}

// ============================================================================
// ANIMATED RADAR COMPONENT
// ============================================================================

function RadarAnimation() {
  return (
    <div className="relative w-full h-full flex items-center justify-center">
      {/* Outer Ring */}
      <div className="absolute w-full h-full border border-accent/20 rounded-full" />
      <div className="absolute w-[75%] h-[75%] border border-accent/15 rounded-full" />
      <div className="absolute w-[50%] h-[50%] border border-accent/10 rounded-full" />
      <div className="absolute w-[25%] h-[25%] border border-accent/5 rounded-full" />
      
      {/* Crosshairs */}
      <div className="absolute w-full h-px bg-accent/10" />
      <div className="absolute w-px h-full bg-accent/10" />
      
      {/* Sweeping Line */}
      <div 
        className="absolute w-1/2 h-px bg-gradient-to-r from-accent to-transparent origin-left animate-[spin_4s_linear_infinite]"
        style={{ transformOrigin: 'left center' }}
      />
      
      {/* Center Dot */}
      <div className="w-2 h-2 bg-accent rounded-full shadow-[0_0_20px_rgba(16,185,129,0.8)]" />
      
      {/* Blips */}
      <div className="absolute top-[20%] left-[60%] w-1.5 h-1.5 bg-accent rounded-full animate-ping" />
      <div className="absolute top-[70%] left-[30%] w-1 h-1 bg-accent/50 rounded-full animate-pulse" />
      <div className="absolute top-[40%] left-[75%] w-1 h-1 bg-white/30 rounded-full" />
    </div>
  )
}

// ============================================================================
// LIVE TICKER
// ============================================================================

function LiveTicker({ items }: { items: { label: string; value: string; highlight?: boolean }[] }) {
  return (
    <div className="relative border-y border-white/[0.08] bg-black/40 overflow-hidden">
      <div className="absolute left-0 top-0 bottom-0 w-24 bg-gradient-to-r from-[#020202] to-transparent z-10" />
      <div className="absolute right-0 top-0 bottom-0 w-24 bg-gradient-to-l from-[#020202] to-transparent z-10" />
      
      <div className="flex animate-[ticker_30s_linear_infinite] py-3" style={{ width: 'max-content' }}>
        {[...items, ...items, ...items].map((item, i) => (
          <div key={i} className="flex items-center gap-4 px-8 border-r border-white/[0.08]">
            <span className="text-[10px] font-mono uppercase tracking-widest text-white/40">{item.label}</span>
            <span className={clsx(
              "text-sm font-mono font-medium",
              item.highlight ? "text-accent" : "text-white"
            )}>{item.value}</span>
          </div>
        ))}
      </div>
    </div>
  )
}

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

export default function RadarPage() {
  const { isAuthenticated, user, domains, addDomain } = useStore()
  const { toast, showToast, hideToast } = useToast()
  
  const [hotAuctions, setHotAuctions] = useState<HotAuction[]>([])
  const [marketStats, setMarketStats] = useState({ totalAuctions: 0, endingSoon: 0 })
  const [loadingData, setLoadingData] = useState(true)
  
  const [searchQuery, setSearchQuery] = useState('')
  const [searchResult, setSearchResult] = useState<SearchResult | null>(null)
  const [addingToWatchlist, setAddingToWatchlist] = useState(false)
  const [searchFocused, setSearchFocused] = useState(false)
  const searchInputRef = useRef<HTMLInputElement>(null)

  // Load Data
  const loadDashboardData = useCallback(async () => {
    try {
      const summary = await api.getDashboardSummary()
      setHotAuctions((summary.market.ending_soon_preview || []).slice(0, 6))
      setMarketStats({
        totalAuctions: summary.market.total_auctions || 0,
        endingSoon: summary.market.ending_soon || 0,
      })
    } catch (error) {
      console.error('Failed to load data:', error)
    } finally {
      setLoadingData(false)
    }
  }, [])

  useEffect(() => {
    if (isAuthenticated) loadDashboardData()
  }, [isAuthenticated, loadDashboardData])

  // Search
  const handleSearch = useCallback(async (domainInput: string) => {
    if (!domainInput.trim()) { setSearchResult(null); return }
    const cleanDomain = domainInput.trim().toLowerCase()
    setSearchResult({ domain: cleanDomain, status: 'checking', is_available: null, registrar: null, expiration_date: null, loading: true, inAuction: false })
    
    try {
      const [whoisResult, auctionsResult] = await Promise.all([
        api.checkDomain(cleanDomain).catch(() => null),
        api.getAuctions(cleanDomain).catch(() => ({ auctions: [] })),
      ])
      const auctionMatch = (auctionsResult as any).auctions?.find((a: any) => a.domain.toLowerCase() === cleanDomain)
      setSearchResult({
        domain: whoisResult?.domain || cleanDomain,
        status: whoisResult?.status || 'unknown',
        is_available: whoisResult?.is_available ?? null,
        registrar: whoisResult?.registrar || null,
        expiration_date: whoisResult?.expiration_date || null,
        loading: false,
        inAuction: !!auctionMatch,
        auctionData: auctionMatch,
      })
    } catch {
      setSearchResult({ domain: cleanDomain, status: 'error', is_available: null, registrar: null, expiration_date: null, loading: false, inAuction: false })
    }
  }, [])

  const handleAddToWatchlist = useCallback(async () => {
    if (!searchQuery.trim()) return
    setAddingToWatchlist(true)
    try {
      await addDomain(searchQuery.trim())
      showToast(`Target acquired: ${searchQuery.trim()}`, 'success')
      setSearchQuery('')
      setSearchResult(null)
    } catch (err: any) {
      showToast(err.message || 'Mission failed', 'error')
    } finally {
      setAddingToWatchlist(false)
    }
  }, [searchQuery, addDomain, showToast])

  useEffect(() => {
    const timer = setTimeout(() => {
      if (searchQuery.length > 3) handleSearch(searchQuery)
      else setSearchResult(null)
    }, 500)
    return () => clearTimeout(timer)
  }, [searchQuery, handleSearch])

  // Computed
  const availableDomains = domains?.filter(d => d.is_available) || []
  const totalDomains = domains?.length || 0
  
  const tickerItems = [
    { label: 'System', value: 'ONLINE', highlight: true },
    { label: 'Targets', value: totalDomains.toString() },
    { label: 'Opportunities', value: availableDomains.length.toString(), highlight: availableDomains.length > 0 },
    { label: 'Market', value: `${marketStats.totalAuctions} Active` },
    { label: 'Latency', value: '12ms' },
  ]

  return (
    <CommandCenterLayout>
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
      
      <div className="min-h-screen">
        
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* HERO SECTION - CINEMATIC */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="relative min-h-[60vh] flex items-center py-20">
          <div className="absolute inset-0 pointer-events-none">
            <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] opacity-20">
              <RadarAnimation />
            </div>
          </div>
          
          <div className="relative z-10 w-full max-w-[1400px] mx-auto px-6">
            <div className="grid lg:grid-cols-2 gap-16 items-center">
              
              {/* Left: Typography */}
              <div className="space-y-8">
                <div className="inline-flex items-center gap-4">
                  <div className="w-2 h-2 bg-accent rounded-full animate-pulse shadow-[0_0_15px_rgba(16,185,129,0.8)]" />
                  <span className="text-[10px] font-mono uppercase tracking-[0.3em] text-accent">
                    Intelligence Hub // Active
                  </span>
                </div>
                
                <h1 className="font-display text-[4rem] sm:text-[5rem] lg:text-[6rem] leading-[0.9] tracking-[-0.04em]">
                  <span className="block text-white animate-fade-in">Global</span>
                  <span className="block text-white animate-fade-in" style={{ animationDelay: '0.1s' }}>Recon.</span>
                  <span className="block text-white/30 mt-4 animate-fade-in" style={{ animationDelay: '0.2s' }}>
                    Zero Blind Spots.
                  </span>
                </h1>
                
                <p className="text-lg text-white/50 max-w-md font-light leading-relaxed">
                  Scanning {marketStats.totalAuctions.toLocaleString()}+ auction listings across all major platforms. 
                  <span className="text-white font-medium"> Your targets. Your intel.</span>
                </p>
                
                {/* Stats Row */}
                <div className="flex gap-12 pt-8 border-t border-white/[0.08]">
                  <div>
                    <div className="text-4xl font-display text-white">{totalDomains}</div>
                    <div className="text-[10px] uppercase tracking-widest text-white/40 font-mono mt-1">Tracking</div>
                  </div>
                  <div>
                    <div className="text-4xl font-display text-accent">{availableDomains.length}</div>
                    <div className="text-[10px] uppercase tracking-widest text-white/40 font-mono mt-1">Ready</div>
                  </div>
                  <div>
                    <div className="text-4xl font-display text-white">{marketStats.endingSoon}</div>
                    <div className="text-[10px] uppercase tracking-widest text-white/40 font-mono mt-1">Ending Soon</div>
                  </div>
                </div>
              </div>
              
              {/* Right: Search Terminal */}
              <div className="relative">
                <div className="absolute -inset-4 bg-gradient-to-tr from-accent/10 via-transparent to-accent/5 blur-3xl opacity-50" />
                
                <div className="relative bg-[#0A0A0A] border border-white/20 p-2">
                  {/* Tech Corners */}
                  <div className="absolute -top-px -left-px w-6 h-6 border-t-2 border-l-2 border-accent" />
                  <div className="absolute -top-px -right-px w-6 h-6 border-t-2 border-r-2 border-accent" />
                  <div className="absolute -bottom-px -left-px w-6 h-6 border-b-2 border-l-2 border-accent" />
                  <div className="absolute -bottom-px -right-px w-6 h-6 border-b-2 border-r-2 border-accent" />
                  
                  <div className="bg-[#050505] p-8 relative overflow-hidden">
                    {/* Header */}
                    <div className="flex items-center justify-between mb-8">
                      <span className="text-[10px] font-mono uppercase tracking-[0.2em] text-accent flex items-center gap-2">
                        <Crosshair className="w-3 h-3" />
                        Target Acquisition
                      </span>
                      <div className="flex gap-1">
                        <div className="w-1.5 h-1.5 bg-accent/50" />
                        <div className="w-1.5 h-1.5 bg-accent/30" />
                        <div className="w-1.5 h-1.5 bg-accent/10" />
                      </div>
                    </div>
                    
                    {/* Input */}
                    <div className={clsx(
                      "relative border transition-all duration-300",
                      searchFocused ? "border-accent shadow-[0_0_30px_-10px_rgba(16,185,129,0.3)]" : "border-white/10"
                    )}>
                      <div className="absolute left-4 top-1/2 -translate-y-1/2 text-accent font-mono">{'>'}</div>
                      <input
                        ref={searchInputRef}
                        type="text"
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        onFocus={() => setSearchFocused(true)}
                        onBlur={() => setSearchFocused(false)}
                        placeholder="ENTER_TARGET..."
                        className="w-full bg-black/50 px-10 py-5 text-2xl text-white placeholder:text-white/20 font-mono uppercase tracking-tight outline-none"
                      />
                      {searchQuery && (
                        <button 
                          onClick={() => { setSearchQuery(''); setSearchResult(null) }}
                          className="absolute right-4 top-1/2 -translate-y-1/2 text-white/30 hover:text-white"
                        >
                          <XCircle className="w-5 h-5" />
                        </button>
                      )}
                    </div>
                    
                    {/* Results */}
                    {searchResult && (
                      <div className="mt-6 border-t border-white/[0.08] pt-6">
                        {searchResult.loading ? (
                          <div className="flex items-center gap-3 text-accent">
                            <Loader2 className="w-4 h-4 animate-spin" />
                            <span className="text-sm font-mono uppercase tracking-widest">Scanning registries...</span>
                          </div>
                        ) : (
                          <div className="space-y-4">
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-3">
                                {searchResult.is_available ? (
                                  <div className="w-3 h-3 bg-accent shadow-[0_0_10px_rgba(16,185,129,0.8)]" />
                                ) : (
                                  <div className="w-3 h-3 bg-white/20" />
                                )}
                                <span className="text-xl font-mono text-white">{searchResult.domain}</span>
                              </div>
                              <span className={clsx(
                                "text-[10px] font-mono uppercase tracking-widest px-3 py-1 border",
                                searchResult.is_available 
                                  ? "text-accent border-accent/30 bg-accent/5" 
                                  : "text-white/40 border-white/10"
                              )}>
                                {searchResult.is_available ? 'AVAILABLE' : 'REGISTERED'}
                              </span>
                            </div>
                            
                            {searchResult.is_available && (
                              <div className="flex gap-3 pt-4">
                                <button
                                  onClick={handleAddToWatchlist}
                                  disabled={addingToWatchlist}
                                  className="flex-1 py-3 border border-white/20 text-white/80 font-mono text-xs uppercase tracking-widest hover:bg-white/5 transition-colors"
                                >
                                  {addingToWatchlist ? 'TRACKING...' : '+ TRACK'}
                                </button>
                                <a
                                  href={`https://www.namecheap.com/domains/registration/results/?domain=${searchResult.domain}`}
                                  target="_blank"
                                  className="flex-1 py-3 bg-accent text-black font-mono text-xs font-bold uppercase tracking-widest hover:bg-white transition-colors flex items-center justify-center gap-2"
                                >
                                  ACQUIRE <ArrowRight className="w-3 h-3" />
                                </a>
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                    )}
                    
                    {/* Footer */}
                    <div className="mt-8 pt-6 border-t border-white/[0.05] flex justify-between items-center text-[10px] text-white/20 font-mono">
                      <span>SECURE_CONNECTION</span>
                      <span>V2.1.0</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* Ticker */}
        <LiveTicker items={tickerItems} />

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* LIVE FEED SECTION */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="py-24 px-6">
          <div className="max-w-[1400px] mx-auto">
            
            {/* Section Header */}
            <div className="flex flex-col lg:flex-row justify-between items-end mb-16 border-b border-white/[0.08] pb-8">
              <div>
                <span className="text-accent font-mono text-xs uppercase tracking-[0.2em] mb-4 block">Live Feed</span>
                <h2 className="font-display text-4xl sm:text-5xl text-white leading-none">
                  Market <br />
                  <span className="text-white/30">Operations.</span>
                </h2>
              </div>
              <div className="mt-6 lg:mt-0 flex items-center gap-6">
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 bg-accent rounded-full animate-pulse" />
                  <span className="text-xs font-mono text-white/40 uppercase">Live Updates</span>
                </div>
                <Link 
                  href="/terminal/market" 
                  className="text-xs font-mono uppercase tracking-widest text-white/40 hover:text-white transition-colors flex items-center gap-2"
                >
                  Full Feed <ArrowRight className="w-3 h-3" />
                </Link>
              </div>
            </div>

            {/* Grid */}
            <div className="grid lg:grid-cols-3 gap-px bg-white/[0.08]">
              
              {/* Hot Auctions */}
              <div className="lg:col-span-2 bg-[#020202] p-8">
                <div className="flex items-center gap-3 mb-8">
                  <div className="w-8 h-8 border border-accent/30 flex items-center justify-center bg-accent/5">
                    <Gavel className="w-4 h-4 text-accent" />
                  </div>
                  <div>
                    <h3 className="text-sm font-bold text-white uppercase tracking-wider">Active Auctions</h3>
                    <p className="text-[10px] text-white/40 font-mono">Real-time market data</p>
                  </div>
                </div>
                
                {loadingData ? (
                  <div className="flex items-center justify-center py-12">
                    <Loader2 className="w-6 h-6 text-accent animate-spin" />
                  </div>
                ) : hotAuctions.length > 0 ? (
                  <div className="space-y-px bg-white/[0.05]">
                    {hotAuctions.map((auction, i) => (
                      <a
                        key={i}
                        href={auction.affiliate_url || '#'}
                        target="_blank"
                        className="flex items-center justify-between p-4 bg-[#020202] hover:bg-white/[0.02] transition-colors group"
                      >
                        <div className="flex items-center gap-4">
                          <div className="w-8 h-8 border border-white/10 flex items-center justify-center text-[10px] font-mono text-white/30 group-hover:border-accent/30 group-hover:text-accent transition-colors">
                            {auction.platform.substring(0, 2).toUpperCase()}
                          </div>
                          <div>
                            <div className="font-mono text-white group-hover:text-accent transition-colors">{auction.domain}</div>
                            <div className="text-[10px] text-white/30 font-mono uppercase">{auction.time_remaining} LEFT</div>
                          </div>
                        </div>
                        <div className="text-right">
                          <div className="font-mono text-accent font-bold">${auction.current_bid.toLocaleString()}</div>
                          <div className="text-[10px] text-white/20 uppercase">Current</div>
                        </div>
                      </a>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-12 text-white/20 font-mono text-xs uppercase">
                    No active auctions
                  </div>
                )}
              </div>
              
              {/* Quick Actions */}
              <div className="bg-[#020202] p-8 flex flex-col">
                <div className="flex items-center gap-3 mb-8">
                  <div className="w-8 h-8 border border-white/20 flex items-center justify-center bg-white/5">
                    <Zap className="w-4 h-4 text-white" />
                  </div>
                  <div>
                    <h3 className="text-sm font-bold text-white uppercase tracking-wider">Quick Access</h3>
                    <p className="text-[10px] text-white/40 font-mono">Navigation</p>
                  </div>
                </div>
                
                <div className="space-y-3 flex-1">
                  {[
                    { label: 'Watchlist', desc: 'Your targets', href: '/terminal/watchlist', icon: Eye },
                    { label: 'Market', desc: 'All auctions', href: '/terminal/market', icon: Gavel },
                    { label: 'Intel', desc: 'TLD pricing', href: '/terminal/intel', icon: Globe },
                  ].map((item) => (
                    <Link
                      key={item.href}
                      href={item.href}
                      className="flex items-center gap-4 p-4 border border-white/[0.08] hover:border-accent/30 hover:bg-accent/5 transition-all group"
                    >
                      <item.icon className="w-5 h-5 text-white/40 group-hover:text-accent transition-colors" />
                      <div className="flex-1">
                        <div className="text-sm text-white font-medium group-hover:text-accent transition-colors">{item.label}</div>
                        <div className="text-[10px] text-white/30 font-mono uppercase">{item.desc}</div>
                      </div>
                      <ArrowRight className="w-4 h-4 text-white/20 group-hover:text-accent group-hover:translate-x-1 transition-all" />
                    </Link>
                  ))}
                </div>
                
                {/* System Status */}
                <div className="mt-8 pt-6 border-t border-white/[0.08]">
                  <div className="text-[10px] font-mono uppercase text-white/30 mb-3">System Status</div>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <div className="w-1.5 h-1.5 bg-accent rounded-full animate-pulse" />
                      <span className="text-xs text-white/60 font-mono">All Systems Operational</span>
                    </div>
                    <span className="text-[10px] text-white/20 font-mono">99.9%</span>
                  </div>
                </div>
              </div>
              
            </div>
          </div>
        </section>

      </div>
      
      <style jsx global>{`
        @keyframes ticker {
          0% { transform: translateX(0); }
          100% { transform: translateX(-33.33%); }
        }
      `}</style>
    </CommandCenterLayout>
  )
}