'use client'

import { useEffect, useState, useMemo, useCallback } 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 { PremiumTable, StatCard, PageContainer, Badge, SectionHeader, ActionButton } from '@/components/PremiumTable'
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,
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'

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
}

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)

  // Check for upgrade success
  useEffect(() => {
    if (searchParams.get('upgraded') === 'true') {
      showToast('Welcome to your upgraded plan! 🎉', 'success')
      window.history.replaceState({}, '', '/terminal/radar')
    }
  }, [searchParams, showToast])

  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])

  // Universal Search - simultaneous check
  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 {
      // Parallel checks
      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, // TODO: Check marketplace
        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])

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

  // Memoized computed values
  const { availableDomains, totalDomains, tierName, TierIcon, greeting, subtitle, listingsCount } = useMemo(() => {
    const availableDomains = domains?.filter(d => d.is_available) || []
    const totalDomains = domains?.length || 0
    const tierName = subscription?.tier_name || subscription?.tier || 'Scout'
    const TierIcon = tierName === 'Tycoon' ? Crown : tierName === 'Trader' ? TrendingUp : Zap
    
    const hour = new Date().getHours()
    const greeting = hour < 12 ? 'Good morning' : hour < 18 ? 'Good afternoon' : 'Good evening'
    
    let subtitle = ''
    if (availableDomains.length > 0) {
      subtitle = `${availableDomains.length} domain${availableDomains.length !== 1 ? 's' : ''} ready to pounce!`
    } else if (totalDomains > 0) {
      subtitle = `Monitoring ${totalDomains} domain${totalDomains !== 1 ? 's' : ''} for you`
    } else {
      subtitle = 'Start tracking domains to find opportunities'
    }
    
    // TODO: Get actual listings count from API
    const listingsCount = 0
    
    return { availableDomains, totalDomains, tierName, TierIcon, greeting, subtitle, listingsCount }
  }, [domains, subscription])

  // Generate ticker items
  const tickerItems = useTickerItems(trendingTlds, availableDomains, hotAuctions)

  if (isLoading || !isAuthenticated) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="w-6 h-6 border-2 border-accent border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  return (
    <TerminalLayout
      title={`${greeting}${user?.name ? `, ${user.name.split(' ')[0]}` : ''}`}
      subtitle={subtitle}
    >
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}

      {/* A. THE TICKER - Market movements */}
      {tickerItems.length > 0 && (
        <div className="-mx-4 sm:-mx-6 lg:-mx-8 mb-6">
          <Ticker items={tickerItems} speed={40} />
        </div>
      )}

      <PageContainer>
        {/* B. QUICK STATS - 3 Cards as per concept */}
        <div className="grid grid-cols-3 gap-4 mb-8">
          <Link href="/terminal/watchlist" className="group">
            <StatCard 
              title="Watching" 
              value={totalDomains}
              subtitle={availableDomains.length > 0 ? `${availableDomains.length} alerts` : undefined}
              icon={Eye}
              accent={availableDomains.length > 0}
            />
          </Link>
          <Link href="/terminal/market" className="group">
            <StatCard 
              title="Market" 
              value={hotAuctions.length > 0 ? `${hotAuctions.length}+` : '0'}
              subtitle="opportunities"
              icon={Gavel}
            />
          </Link>
          <Link href="/terminal/listing" className="group">
            <StatCard 
              title="My Listings" 
              value={listingsCount}
              subtitle="active"
              icon={Tag}
            />
          </Link>
        </div>

        {/* C. UNIVERSAL SEARCH - Hero Element */}
        <div className="relative p-6 sm:p-8 bg-gradient-to-br from-accent/10 via-accent/5 to-transparent border border-accent/20 rounded-2xl overflow-hidden mb-8">
          <div className="absolute top-0 right-0 w-96 h-96 bg-accent/5 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2" />
          
          <div className="relative">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 bg-accent/20 rounded-xl flex items-center justify-center">
                <Search className="w-5 h-5 text-accent" />
              </div>
              <div>
                <h2 className="text-lg font-semibold text-foreground">Universal Search</h2>
                <p className="text-sm text-foreground-muted">Check availability, auctions & marketplace simultaneously</p>
              </div>
            </div>
            
            <div className="relative">
              <Globe className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-foreground-subtle" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Enter domain to check (e.g., dream.com)"
                className="w-full h-14 pl-12 pr-4 bg-background/80 backdrop-blur-sm border border-border/50 rounded-xl
                           text-base text-foreground placeholder:text-foreground-subtle
                           focus:outline-none focus:border-accent focus:ring-2 focus:ring-accent/20"
              />
            </div>

            {/* Search Results */}
            {searchResult && (
              <div className="mt-4 p-4 bg-background/60 backdrop-blur-sm border border-border/40 rounded-xl">
                {searchResult.loading ? (
                  <div className="flex items-center gap-3 text-foreground-muted">
                    <Loader2 className="w-5 h-5 animate-spin" />
                    <span>Checking...</span>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {/* Availability */}
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        {searchResult.available === true ? (
                          <CheckCircle2 className="w-5 h-5 text-accent" />
                        ) : searchResult.available === false ? (
                          <XCircle className="w-5 h-5 text-red-400" />
                        ) : (
                          <Globe className="w-5 h-5 text-foreground-subtle" />
                        )}
                        <span className="text-sm text-foreground">
                          {searchResult.available === true 
                            ? 'Available for registration!' 
                            : searchResult.available === false 
                              ? 'Currently registered' 
                              : 'Could not check availability'}
                        </span>
                      </div>
                      {searchResult.available === true && (
                        <a
                          href={`https://www.namecheap.com/domains/registration/results/?domain=${searchQuery}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-xs font-medium text-accent hover:underline flex items-center gap-1"
                        >
                          Register Now <ExternalLink className="w-3 h-3" />
                        </a>
                      )}
                    </div>

                    {/* In Auction */}
                    {searchResult.inAuction && searchResult.auctionData && (
                      <div className="flex items-center justify-between p-3 bg-amber-400/10 border border-amber-400/20 rounded-lg">
                        <div className="flex items-center gap-2">
                          <Gavel className="w-5 h-5 text-amber-400" />
                          <span className="text-sm text-foreground">
                            In auction: ${searchResult.auctionData.current_bid} ({searchResult.auctionData.time_remaining})
                          </span>
                        </div>
                        <a
                          href={searchResult.auctionData.affiliate_url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-xs font-medium text-amber-400 hover:underline flex items-center gap-1"
                        >
                          Bid Now <ExternalLink className="w-3 h-3" />
                        </a>
                      </div>
                    )}

                    {/* Action Buttons */}
                    <div className="flex items-center gap-3 pt-2">
                      <button
                        onClick={handleAddToWatchlist}
                        disabled={addingToWatchlist}
                        className="flex items-center gap-2 px-4 py-2 bg-accent text-background rounded-lg font-medium
                                   hover:bg-accent/90 transition-all disabled:opacity-50"
                      >
                        {addingToWatchlist ? (
                          <Loader2 className="w-4 h-4 animate-spin" />
                        ) : (
                          <Plus className="w-4 h-4" />
                        )}
                        Add to Watchlist
                      </button>
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>

        {/* D. RECENT ALERTS + MARKET PULSE */}
        <div className="grid lg:grid-cols-2 gap-6">
          {/* Recent Alerts / Activity Feed */}
          <div className="relative overflow-hidden rounded-2xl border border-border/40 bg-gradient-to-b from-background-secondary/40 to-background-secondary/20 backdrop-blur-sm">
            <div className="p-5 border-b border-border/30">
              <SectionHeader 
                title="Recent Alerts" 
                icon={Activity}
                compact
                action={
                  <Link href="/terminal/watchlist" className="text-sm text-accent hover:text-accent/80 transition-colors flex items-center gap-1">
                    View all <ArrowRight className="w-3.5 h-3.5" />
                  </Link>
                }
              />
            </div>
            <div className="p-5">
              {availableDomains.length > 0 ? (
                <div className="space-y-3">
                  {availableDomains.slice(0, 5).map((domain) => (
                    <div 
                      key={domain.id}
                      className="flex items-center gap-4 p-3 bg-accent/5 border border-accent/20 rounded-xl"
                    >
                      <div className="relative">
                        <span className="w-3 h-3 bg-accent rounded-full block" />
                        <span className="absolute inset-0 bg-accent rounded-full animate-ping opacity-50" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-foreground font-mono truncate">{domain.name}</p>
                        <p className="text-xs text-accent">Available for registration!</p>
                      </div>
                      <a
                        href={`https://www.namecheap.com/domains/registration/results/?domain=${domain.name}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-xs font-medium text-accent hover:underline flex items-center gap-1"
                      >
                        Register <ExternalLink className="w-3 h-3" />
                      </a>
                    </div>
                  ))}
                </div>
              ) : totalDomains > 0 ? (
                <div className="text-center py-8">
                  <Bell className="w-10 h-10 text-foreground-subtle mx-auto mb-3" />
                  <p className="text-foreground-muted">All domains are still registered</p>
                  <p className="text-sm text-foreground-subtle mt-1">
                    Monitoring {totalDomains} domains for you
                  </p>
                </div>
              ) : (
                <div className="text-center py-8">
                  <Plus className="w-10 h-10 text-foreground-subtle mx-auto mb-3" />
                  <p className="text-foreground-muted">No domains tracked yet</p>
                  <p className="text-sm text-foreground-subtle mt-1">
                    Use Universal Search above to start
                  </p>
                </div>
              )}
            </div>
          </div>

          {/* Market Pulse */}
          <div className="relative overflow-hidden rounded-2xl border border-border/40 bg-gradient-to-b from-background-secondary/40 to-background-secondary/20 backdrop-blur-sm">
            <div className="p-5 border-b border-border/30">
              <SectionHeader 
                title="Market Pulse" 
                icon={Gavel}
                compact
                action={
                  <Link href="/terminal/market" className="text-sm text-accent hover:text-accent/80 transition-colors flex items-center gap-1">
                    View all <ArrowRight className="w-3.5 h-3.5" />
                  </Link>
                }
              />
            </div>
            <div className="p-5">
              {loadingData ? (
                <div className="space-y-3">
                  {[...Array(4)].map((_, i) => (
                    <div key={i} className="h-14 bg-foreground/5 rounded-xl animate-pulse" />
                  ))}
                </div>
              ) : hotAuctions.length > 0 ? (
                <div className="space-y-3">
                  {hotAuctions.map((auction, idx) => (
                    <a
                      key={`${auction.domain}-${idx}`}
                      href={auction.affiliate_url || '#'}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex items-center gap-4 p-3 bg-foreground/5 rounded-xl 
                                 hover:bg-foreground/10 transition-colors group"
                    >
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-foreground font-mono truncate">{auction.domain}</p>
                        <p className="text-xs text-foreground-muted flex items-center gap-2">
                          <Clock className="w-3 h-3" />
                          {auction.time_remaining}
                          <span className="text-foreground-subtle">• {auction.platform}</span>
                        </p>
                      </div>
                      <div className="text-right">
                        <p className="text-sm font-semibold text-foreground">${auction.current_bid}</p>
                        <p className="text-xs text-foreground-subtle">bid</p>
                      </div>
                      <ExternalLink className="w-4 h-4 text-foreground-subtle group-hover:text-foreground" />
                    </a>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8">
                  <Gavel className="w-10 h-10 text-foreground-subtle mx-auto mb-3" />
                  <p className="text-foreground-muted">No auctions ending soon</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </PageContainer>
    </TerminalLayout>
  )
}
