'use client'

import { useEffect, useState, useMemo, useCallback, useRef } from 'react'
import { useSearchParams } from 'next/navigation'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { TerminalLayout } from '@/components/TerminalLayout'
import { Ticker, useTickerItems } from '@/components/Ticker'
import { Toast, useToast } from '@/components/Toast'
import {
  Eye,
  Gavel,
  Tag,
  Clock,
  ExternalLink,
  Sparkles,
  Plus,
  Zap,
  Crown,
  Activity,
  Bell,
  Search,
  TrendingUp,
  ArrowRight,
  Globe,
  CheckCircle2,
  XCircle,
  Loader2,
  Wifi,
  ShieldAlert,
  BarChart3,
  Command
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'

// ============================================================================
// SHARED COMPONENTS
// ============================================================================

function Tooltip({ children, content }: { children: React.ReactNode; content: string }) {
  return (
    <div className="relative flex items-center group/tooltip w-fit">
      {children}
      <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-zinc-900 border border-zinc-800 rounded text-[10px] text-zinc-300 whitespace-nowrap opacity-0 group-hover/tooltip:opacity-100 transition-opacity pointer-events-none z-50 shadow-xl">
        {content}
        <div className="absolute top-full left-1/2 -translate-x-1/2 -mt-px border-4 border-transparent border-t-zinc-800" />
      </div>
    </div>
  )
}

function StatCard({ 
  label, 
  value, 
  subValue, 
  icon: Icon, 
  trend 
}: { 
  label: string
  value: string | number
  subValue?: string
  icon: any
  trend?: 'up' | 'down' | 'neutral' | 'active'
}) {
  return (
    <div className="bg-zinc-900/40 border border-white/5 rounded-xl p-4 flex items-start justify-between hover:bg-white/[0.02] transition-colors relative overflow-hidden group">
      <div className="absolute inset-0 bg-gradient-to-br from-white/[0.03] to-transparent opacity-0 group-hover:opacity-100 transition-opacity" />
      <div className="relative z-10">
        <p className="text-[11px] font-semibold text-zinc-500 uppercase tracking-wider mb-1">{label}</p>
        <div className="flex items-baseline gap-2">
          <span className="text-2xl font-bold text-white tracking-tight">{value}</span>
          {subValue && <span className="text-xs text-zinc-500 font-medium">{subValue}</span>}
        </div>
      </div>
      <div className={clsx(
        "relative z-10 p-2 rounded-lg bg-zinc-800/50 transition-colors",
        trend === 'up' && "text-emerald-400 bg-emerald-500/10",
        trend === 'down' && "text-red-400 bg-red-500/10",
        trend === 'active' && "text-emerald-400 bg-emerald-500/10 animate-pulse",
        trend === 'neutral' && "text-zinc-400"
      )}>
        <Icon className="w-4 h-4" />
      </div>
    </div>
  )
}

// ============================================================================
// 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 {
  available: boolean | null
  inAuction: boolean
  inMarketplace: boolean
  auctionData?: HotAuction
  loading: boolean
}

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

export default function RadarPage() {
  const searchParams = useSearchParams()
  const { 
    isAuthenticated, 
    isLoading, 
    user, 
    domains, 
    subscription,
    addDomain,
  } = useStore()
  
  const { toast, showToast, hideToast } = useToast()
  const [hotAuctions, setHotAuctions] = useState<HotAuction[]>([])
  const [trendingTlds, setTrendingTlds] = useState<TrendingTld[]>([])
  const [loadingData, setLoadingData] = useState(true)
  
  // Universal Search State
  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 [auctions, trending] = await Promise.all([
        api.getEndingSoonAuctions(5).catch(() => []),
        api.getTrendingTlds().catch(() => ({ trending: [] }))
      ])
      setHotAuctions(auctions.slice(0, 5))
      setTrendingTlds(trending.trending?.slice(0, 6) || [])
    } catch (error) {
      console.error('Failed to load dashboard data:', error)
    } finally {
      setLoadingData(false)
    }
  }, [])

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

  // Search Logic
  const handleSearch = useCallback(async (domain: string) => {
    if (!domain.trim()) {
      setSearchResult(null)
      return
    }

    const cleanDomain = domain.trim().toLowerCase()
    setSearchResult({ available: null, inAuction: false, inMarketplace: false, loading: true })

    try {
      const [whoisResult, auctionsResult] = await Promise.all([
        api.checkDomain(cleanDomain, true).catch(() => null),
        api.getAuctions(cleanDomain).catch(() => ({ auctions: [] })),
      ])

      const auctionMatch = (auctionsResult as any).auctions?.find(
        (a: any) => a.domain.toLowerCase() === cleanDomain
      )

      const isAvailable = whoisResult && 'is_available' in whoisResult 
        ? whoisResult.is_available 
        : null

      setSearchResult({
        available: isAvailable,
        inAuction: !!auctionMatch,
        inMarketplace: false,
        auctionData: auctionMatch,
        loading: false,
      })
    } catch (error) {
      setSearchResult({ available: null, inAuction: false, inMarketplace: false, loading: false })
    }
  }, [])

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

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

  // Focus shortcut
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.metaKey && e.key === 'k') {
        e.preventDefault()
        searchInputRef.current?.focus()
      }
    }
    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [])

  // Computed
  const { availableDomains, totalDomains, greeting, subtitle } = useMemo(() => {
    const available = domains?.filter(d => d.is_available) || []
    const total = domains?.length || 0
    const hour = new Date().getHours()
    const greeting = hour < 12 ? 'Good morning' : hour < 18 ? 'Good afternoon' : 'Good evening'
    
    let subtitle = ''
    if (available.length > 0) subtitle = `${available.length} domain${available.length !== 1 ? 's' : ''} ready to pounce!`
    else if (total > 0) subtitle = `Monitoring ${total} domain${total !== 1 ? 's' : ''} for you`
    else subtitle = 'Start tracking domains to find opportunities'
    
    return { availableDomains: available, totalDomains: total, greeting, subtitle }
  }, [domains])

  const tickerItems = useTickerItems(trendingTlds, availableDomains, hotAuctions)

  return (
    <TerminalLayout
      title={`${greeting}${user?.name ? `, ${user.name.split(' ')[0]}` : ''}`}
      subtitle={subtitle}
      hideHeaderSearch={true}
    >
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
      
      {/* GLOW BACKGROUND */}
      <div className="pointer-events-none absolute inset-0 -z-10 overflow-hidden">
        <div className="absolute -top-96 left-1/2 -translate-x-1/2 w-[1000px] h-[1000px] bg-emerald-500/5 blur-[120px] rounded-full" />
      </div>

      <div className="space-y-8">

        {/* 1. TICKER */}
        {tickerItems.length > 0 && (
          <div className="-mx-6 -mt-2 mb-6">
            <Ticker items={tickerItems} speed={40} />
          </div>
        )}

        {/* 2. STAT GRID */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <Link href="/terminal/watchlist" className="block group">
            <StatCard 
              label="Watchlist" 
              value={totalDomains} 
              subValue="Domains"
              icon={Eye} 
              trend="neutral"
            />
          </Link>
          <Link href="/terminal/market" className="block group">
            <StatCard 
              label="Opportunities" 
              value={hotAuctions.length} 
              subValue="Live"
              icon={Gavel} 
              trend="active"
            />
          </Link>
          <div className="block">
            <StatCard 
              label="Alerts" 
              value={availableDomains.length} 
              subValue="Action Required"
              icon={Bell} 
              trend={availableDomains.length > 0 ? 'up' : 'neutral'}
            />
          </div>
          <div className="block">
            <StatCard 
              label="System Status" 
              value="Online" 
              subValue="99.9% Uptime"
              icon={Wifi} 
              trend="up"
            />
          </div>
        </div>

        {/* 3. AWARD-WINNING SEARCH (HERO STYLE) */}
        <div className="relative py-8">
          <div className="max-w-3xl mx-auto">
            <div className={clsx(
              "relative bg-zinc-950/50 backdrop-blur-xl border rounded-2xl transition-all duration-300",
              searchFocused 
                ? "border-emerald-500/30 shadow-[0_0_40px_-10px_rgba(16,185,129,0.15)] scale-[1.01]" 
                : "border-white/10 shadow-xl"
            )}>
              <div className="relative flex items-center h-16 sm:h-20 px-6">
                <Search className={clsx(
                  "w-6 h-6 mr-4 transition-colors",
                  searchFocused ? "text-emerald-400" : "text-zinc-500"
                )} />
                <input
                  ref={searchInputRef}
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  onFocus={() => setSearchFocused(true)}
                  onBlur={() => setSearchFocused(false)}
                  placeholder="Analyze any domain..."
                  className="w-full bg-transparent text-xl sm:text-2xl text-white placeholder:text-zinc-600 font-light outline-none"
                />
                {!searchQuery && (
                  <div className="hidden sm:flex items-center gap-1.5 px-2 py-1 rounded border border-white/10 bg-white/5 text-xs text-zinc-500 font-mono">
                    <Command className="w-3 h-3" /> K
                  </div>
                )}
                {searchQuery && (
                  <button 
                    onClick={() => { setSearchQuery(''); setSearchFocused(true); }}
                    className="p-2 text-zinc-500 hover:text-white transition-colors"
                  >
                    <XCircle className="w-5 h-5" />
                  </button>
                )}
              </div>

              {/* SEARCH RESULTS DROPDOWN */}
              {searchResult && (
                <div className="border-t border-white/5 p-4 sm:p-6 animate-in slide-in-from-top-2 fade-in duration-200">
                  {searchResult.loading ? (
                    <div className="flex items-center justify-center py-8 gap-3 text-zinc-500">
                      <Loader2 className="w-5 h-5 animate-spin text-emerald-500" />
                      <span className="text-sm font-medium">Scanning global availability...</span>
                    </div>
                  ) : (
                    <div className="space-y-6">
                      {/* Availability Card */}
                      <div className={clsx(
                        "flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 rounded-xl border transition-all",
                        searchResult.available
                          ? "bg-emerald-500/10 border-emerald-500/20"
                          : "bg-white/[0.02] border-white/5"
                      )}>
                        <div className="flex items-center gap-4 mb-4 sm:mb-0">
                          {searchResult.available ? (
                            <div className="w-10 h-10 rounded-full bg-emerald-500/20 flex items-center justify-center shadow-[0_0_15px_rgba(16,185,129,0.2)]">
                              <CheckCircle2 className="w-5 h-5 text-emerald-400" />
                            </div>
                          ) : (
                            <div className="w-10 h-10 rounded-full bg-red-500/10 flex items-center justify-center">
                              <XCircle className="w-5 h-5 text-red-400" />
                            </div>
                          )}
                          <div>
                            <h3 className="text-lg font-medium text-white">
                              {searchResult.available ? 'Available' : 'Registered'}
                            </h3>
                            <p className="text-sm text-zinc-400">
                              {searchResult.available 
                                ? 'Ready for immediate registration' 
                                : 'Currently owned by someone else'}
                            </p>
                          </div>
                        </div>
                        
                        {searchResult.available && (
                          <a
                            href={`https://www.namecheap.com/domains/registration/results/?domain=${searchQuery}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="w-full sm:w-auto px-6 py-2.5 bg-emerald-500 hover:bg-emerald-400 text-black text-sm font-bold rounded-lg transition-all shadow-lg hover:shadow-emerald-500/20 text-center"
                          >
                            Register Now
                          </a>
                        )}
                      </div>

                      {/* Auction Card */}
                      {searchResult.inAuction && searchResult.auctionData && (
                        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 rounded-xl border border-amber-500/20 bg-amber-500/5">
                          <div className="flex items-center gap-4 mb-4 sm:mb-0">
                            <div className="w-10 h-10 rounded-full bg-amber-500/10 flex items-center justify-center">
                              <Gavel className="w-5 h-5 text-amber-400" />
                            </div>
                            <div>
                              <h3 className="text-lg font-medium text-white flex items-center gap-2">
                                In Auction 
                                <span className="px-2 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-400 uppercase tracking-wider font-bold">Live</span>
                              </h3>
                              <p className="text-sm text-zinc-400 font-mono mt-1">
                                Current Bid: <span className="text-white font-bold">${searchResult.auctionData.current_bid}</span> • Ends in {searchResult.auctionData.time_remaining}
                              </p>
                            </div>
                          </div>
                          
                          <a
                            href={searchResult.auctionData.affiliate_url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="w-full sm:w-auto px-6 py-2.5 bg-amber-500 hover:bg-amber-400 text-black text-sm font-bold rounded-lg transition-all shadow-lg hover:shadow-amber-500/20 text-center"
                          >
                            Place Bid
                          </a>
                        </div>
                      )}

                      {/* Add to Watchlist */}
                      <div className="flex justify-end pt-2">
                        <button
                          onClick={handleAddToWatchlist}
                          disabled={addingToWatchlist}
                          className="flex items-center gap-2 px-6 py-2.5 text-zinc-400 hover:text-white hover:bg-white/5 rounded-lg transition-all text-sm font-medium"
                        >
                          {addingToWatchlist ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
                          Add to Pounce Watchlist
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
            
            {/* Helper Text */}
            {!searchQuery && !searchFocused && (
              <div className="mt-4 text-center">
                <p className="text-sm text-zinc-500">
                  Search across <span className="text-zinc-400 font-medium">Global Registrars</span>, <span className="text-zinc-400 font-medium">Auctions</span>, and <span className="text-zinc-400 font-medium">Marketplaces</span> simultaneously.
                </p>
              </div>
            )}
          </div>
        </div>

        {/* 4. SPLIT VIEW: PULSE & ALERTS */}
        <div className="grid lg:grid-cols-2 gap-6">
          
          {/* MARKET PULSE */}
          <div className="bg-zinc-900/40 border border-white/5 rounded-xl overflow-hidden backdrop-blur-sm">
            <div className="p-4 border-b border-white/5 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Activity className="w-4 h-4 text-emerald-400" />
                <h3 className="text-sm font-bold text-white uppercase tracking-wider">Market Pulse</h3>
              </div>
              <Link href="/terminal/market" className="text-xs text-zinc-500 hover:text-white transition-colors flex items-center gap-1">
                View All <ArrowRight className="w-3 h-3" />
              </Link>
            </div>
            
            <div className="divide-y divide-white/5">
              {loadingData ? (
                <div className="p-8 text-center text-zinc-500 text-sm">Loading market data...</div>
              ) : hotAuctions.length > 0 ? (
                hotAuctions.map((auction, i) => (
                  <a 
                    key={i} 
                    href={auction.affiliate_url || '#'}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center justify-between p-4 hover:bg-white/[0.02] transition-colors group"
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-1.5 h-1.5 rounded-full bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.5)]" />
                      <div>
                        <p className="text-sm font-medium text-white font-mono group-hover:text-emerald-400 transition-colors">
                          {auction.domain}
                        </p>
                        <p className="text-[11px] text-zinc-500 flex items-center gap-2 mt-0.5">
                          {auction.platform} • {auction.time_remaining} left
                        </p>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="text-sm font-mono font-bold text-white">${auction.current_bid}</p>
                      <p className="text-[10px] text-zinc-600 uppercase tracking-wider">Current Bid</p>
                    </div>
                  </a>
                ))
              ) : (
                <div className="p-8 text-center text-zinc-500">
                  <Gavel className="w-8 h-8 mx-auto mb-2 opacity-20" />
                  <p className="text-sm">No live auctions right now</p>
                </div>
              )}
            </div>
          </div>

          {/* WATCHLIST ACTIVITY */}
          <div className="bg-zinc-900/40 border border-white/5 rounded-xl overflow-hidden backdrop-blur-sm">
            <div className="p-4 border-b border-white/5 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Bell className="w-4 h-4 text-amber-400" />
                <h3 className="text-sm font-bold text-white uppercase tracking-wider">Recent Alerts</h3>
              </div>
              <Link href="/terminal/watchlist" className="text-xs text-zinc-500 hover:text-white transition-colors flex items-center gap-1">
                Manage <ArrowRight className="w-3 h-3" />
              </Link>
            </div>

            <div className="divide-y divide-white/5">
              {availableDomains.length > 0 ? (
                availableDomains.slice(0, 5).map((domain) => (
                  <div key={domain.id} className="flex items-center justify-between p-4 hover:bg-white/[0.02] transition-colors">
                    <div className="flex items-center gap-3">
                      <div className="relative">
                        <div className="w-2 h-2 rounded-full bg-emerald-500" />
                        <div className="absolute inset-0 rounded-full bg-emerald-500 animate-ping opacity-50" />
                      </div>
                      <div>
                        <p className="text-sm font-medium text-white font-mono">{domain.name}</p>
                        <p className="text-[11px] text-emerald-400 font-medium mt-0.5">Available for Registration</p>
                      </div>
                    </div>
                    <a
                      href={`https://www.namecheap.com/domains/registration/results/?domain=${domain.name}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="px-3 py-1.5 bg-zinc-800 text-white text-[10px] font-bold uppercase tracking-wider rounded border border-zinc-700 hover:bg-zinc-700 transition-colors"
                    >
                      Register
                    </a>
                  </div>
                ))
              ) : totalDomains > 0 ? (
                <div className="p-8 text-center text-zinc-500">
                  <ShieldAlert className="w-8 h-8 mx-auto mb-2 opacity-20" />
                  <p className="text-sm">All watched domains are taken</p>
                </div>
              ) : (
                <div className="p-8 text-center text-zinc-500">
                  <Eye className="w-8 h-8 mx-auto mb-2 opacity-20" />
                  <p className="text-sm">Your watchlist is empty</p>
                  <p className="text-xs text-zinc-600 mt-1">Use search to add domains</p>
                </div>
              )}
            </div>
          </div>

        </div>
      </div>
    </TerminalLayout>
  )
}
