'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,
  ExternalLink,
  Plus,
  Activity,
  ArrowRight,
  CheckCircle2,
  XCircle,
  Loader2,
  Crosshair,
  Zap,
  Globe,
  Target
} 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 SearchResult {
  domain: string
  status: string
  is_available: boolean | null
  registrar: string | null
  expiration_date: string | null
  loading: boolean
  inAuction: boolean
  auctionData?: HotAuction
}

// ============================================================================
// 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-16 bg-gradient-to-r from-[#020202] to-transparent z-10" />
      <div className="absolute right-0 top-0 bottom-0 w-16 bg-gradient-to-l from-[#020202] to-transparent z-10" />
      
      <div className="flex animate-[ticker_30s_linear_infinite] py-2.5" style={{ width: 'max-content' }}>
        {[...items, ...items, ...items].map((item, i) => (
          <div key={i} className="flex items-center gap-3 px-6 border-r border-white/[0.08]">
            <span className="text-[10px] font-mono tracking-wide text-white/30">{item.label}</span>
            <span className={clsx(
              "text-xs font-mono font-medium",
              item.highlight ? "text-accent" : "text-white/70"
            )}>{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, 5))
      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: 'Status', value: 'ONLINE', highlight: true },
    { label: 'Tracking', value: totalDomains.toString() },
    { label: 'Available', value: availableDomains.length.toString(), highlight: availableDomains.length > 0 },
    { label: 'Auctions', value: marketStats.totalAuctions.toString() },
  ]

  return (
    <CommandCenterLayout minimal>
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
      
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* HERO - Compact for Laptops */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <section className="pt-6 lg:pt-8 pb-10">
        <div className="grid lg:grid-cols-2 gap-10 lg:gap-16 items-center">
          
          {/* Left: Typography */}
          <div className="space-y-5">
            <div className="inline-flex items-center gap-3">
              <div className="w-1.5 h-1.5 bg-accent rounded-full animate-pulse shadow-[0_0_10px_rgba(16,185,129,0.8)]" />
              <span className="text-[10px] font-mono tracking-[0.15em] text-accent">
                Intelligence Hub
              </span>
            </div>
            
            <h1 className="font-display text-[2rem] sm:text-[2.5rem] lg:text-[2.75rem] leading-[1] tracking-[-0.02em]">
              <span className="block text-white">Domain Radar</span>
              <span className="block text-white/30">Find your next acquisition.</span>
            </h1>
            
            <p className="text-sm text-white/50 max-w-md font-light leading-relaxed">
              Real-time monitoring across {marketStats.totalAuctions.toLocaleString()}+ auctions. 
              <span className="text-white/70"> Your targets. Your intel.</span>
            </p>
            
            {/* Stats Row */}
            <div className="flex gap-8 lg:gap-10 pt-5 border-t border-white/[0.08]">
              <div>
                <div className="text-xl lg:text-2xl font-display text-white">{totalDomains}</div>
                <div className="text-[9px] tracking-wide text-white/30 font-mono mt-1">Tracking</div>
              </div>
              <div>
                <div className="text-xl lg:text-2xl font-display text-accent">{availableDomains.length}</div>
                <div className="text-[9px] tracking-wide text-white/30 font-mono mt-1">Available</div>
              </div>
              <div>
                <div className="text-xl lg:text-2xl font-display text-white">{marketStats.endingSoon}</div>
                <div className="text-[9px] tracking-wide text-white/30 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-30" />
            
            <div className="relative bg-[#0A0A0A] border border-white/10 overflow-hidden">
              {/* Header Bar */}
              <div className="flex items-center justify-between px-5 py-3 border-b border-white/[0.06] bg-black/40">
                <span className="text-[10px] font-mono text-white/40 flex items-center gap-2">
                  <Crosshair className="w-3 h-3 text-accent" />
                  Domain Search
                </span>
                <div className="flex gap-1.5">
                  <div className="w-2 h-2 rounded-full bg-white/10" />
                  <div className="w-2 h-2 rounded-full bg-white/10" />
                  <div className="w-2 h-2 rounded-full bg-accent/50" />
                </div>
              </div>
              
              <div className="p-5 lg:p-6">
                {/* Input */}
                <div className={clsx(
                  "relative border-2 transition-all duration-300 bg-black/30",
                  searchFocused ? "border-accent/60 shadow-[0_0_30px_-10px_rgba(16,185,129,0.3)]" : "border-white/10"
                )}>
                  <input
                    ref={searchInputRef}
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    onFocus={() => setSearchFocused(true)}
                    onBlur={() => setSearchFocused(false)}
                    placeholder="example.com"
                    className="w-full bg-transparent px-4 py-4 text-lg text-white placeholder:text-white/20 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 transition-colors"
                    >
                      <XCircle className="w-5 h-5" />
                    </button>
                  )}
                </div>
                
                {/* Results */}
                {searchResult && (
                  <div className="mt-5">
                    {searchResult.loading ? (
                      <div className="flex items-center justify-center gap-3 py-6 text-white/40">
                        <Loader2 className="w-4 h-4 animate-spin" />
                        <span className="text-sm">Checking availability...</span>
                      </div>
                    ) : (
                      <div className={clsx(
                        "p-5 border-2 transition-all",
                        searchResult.is_available 
                          ? "bg-accent/5 border-accent/40" 
                          : "bg-white/[0.02] border-white/10"
                      )}>
                        {/* Status Header */}
                        <div className="flex items-center justify-between mb-4">
                          <div className="flex items-center gap-3">
                            {searchResult.is_available ? (
                              <CheckCircle2 className="w-5 h-5 text-accent" />
                            ) : (
                              <XCircle className="w-5 h-5 text-white/30" />
                            )}
                            <span className="text-lg font-medium text-white">{searchResult.domain}</span>
                          </div>
                          <span className={clsx(
                            "text-xs font-medium px-3 py-1",
                            searchResult.is_available 
                              ? "text-accent bg-accent/10" 
                              : "text-white/40 bg-white/5"
                          )}>
                            {searchResult.is_available ? 'Available' : 'Taken'}
                          </span>
                        </div>
                        
                        {/* Registrar Info */}
                        {!searchResult.is_available && searchResult.registrar && (
                          <p className="text-xs text-white/30 mb-4">
                            Registered with {searchResult.registrar}
                          </p>
                        )}
                        
                        {/* Actions - Always show */}
                        <div className="flex gap-3">
                          <button
                            onClick={handleAddToWatchlist}
                            disabled={addingToWatchlist}
                            className={clsx(
                              "py-3 text-sm font-medium transition-colors flex items-center justify-center gap-2",
                              searchResult.is_available 
                                ? "flex-1 border border-white/20 text-white/80 hover:bg-white/5"
                                : "flex-1 border border-accent/30 text-accent hover:bg-accent/10"
                            )}
                          >
                            {addingToWatchlist ? <Loader2 className="w-4 h-4 animate-spin" /> : <Eye className="w-4 h-4" />}
                            {searchResult.is_available ? 'Add to Watchlist' : 'Track for Availability'}
                          </button>
                          {searchResult.is_available && (
                            <a
                              href={`https://www.namecheap.com/domains/registration/results/?domain=${searchResult.domain}`}
                              target="_blank"
                              className="flex-1 py-3 bg-accent text-black text-sm font-bold hover:bg-white transition-colors flex items-center justify-center gap-2"
                            >
                              Register Now <ArrowRight className="w-4 h-4" />
                            </a>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                )}
                
                {/* Hint */}
                {!searchResult && (
                  <p className="text-xs text-white/20 mt-4 text-center">
                    Enter a domain name to check availability
                  </p>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>

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

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* CONTENT GRID */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <section className="py-8 lg:py-10">
        <div className="grid lg:grid-cols-3 gap-px bg-white/[0.08] border border-white/[0.08]">
          
          {/* Hot Auctions - 2 cols */}
          <div className="lg:col-span-2 bg-[#020202] p-6 lg:p-8">
            <div className="flex items-center justify-between mb-5">
              <div className="flex items-center gap-2">
                <Gavel className="w-4 h-4 text-accent" />
                <span className="text-sm font-semibold text-white">Live Auctions</span>
              </div>
              <Link href="/terminal/market" className="text-xs text-white/40 hover:text-white transition-colors">
                View all →
              </Link>
            </div>
            
            {loadingData ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="w-5 h-5 text-accent animate-spin" />
              </div>
            ) : hotAuctions.length > 0 ? (
              <div className="space-y-1">
                {hotAuctions.map((auction, i) => (
                  <a
                    key={i}
                    href={auction.affiliate_url || '#'}
                    target="_blank"
                    className="flex items-center justify-between p-3 bg-white/[0.02] hover:bg-white/[0.05] transition-colors group"
                  >
                    <div className="flex items-center gap-3">
                      <span className="text-[10px] font-mono text-white/25 w-6">{auction.platform.substring(0, 3)}</span>
                      <div>
                        <div className="text-sm text-white group-hover:text-accent transition-colors">{auction.domain}</div>
                        <div className="text-[10px] text-white/30">{auction.time_remaining}</div>
                      </div>
                    </div>
                    <div className="font-mono text-sm text-accent font-medium">${auction.current_bid.toLocaleString()}</div>
                  </a>
                ))}
              </div>
            ) : (
              <div className="text-center py-8 text-white/20 text-sm">No active auctions</div>
            )}
          </div>
          
          {/* Quick Links */}
          <div className="bg-[#020202] p-6 lg:p-8">
            <div className="flex items-center gap-2 mb-5">
              <Zap className="w-4 h-4 text-white/50" />
              <span className="text-sm font-semibold text-white">Quick Access</span>
            </div>
            
            <div className="space-y-2">
              {[
                { label: 'Watchlist', href: '/terminal/watchlist', icon: Eye },
                { label: 'Market', href: '/terminal/market', icon: Gavel },
                { label: 'Intel', href: '/terminal/intel', icon: Globe },
              ].map((item) => (
                <Link
                  key={item.href}
                  href={item.href}
                  className="flex items-center gap-3 p-3 border border-white/[0.05] hover:border-accent/30 hover:bg-accent/5 transition-all group"
                >
                  <item.icon className="w-4 h-4 text-white/30 group-hover:text-accent transition-colors" />
                  <span className="text-sm text-white/70 group-hover:text-white transition-colors flex-1">{item.label}</span>
                  <ArrowRight className="w-3 h-3 text-white/15 group-hover:text-accent group-hover:translate-x-0.5 transition-all" />
                </Link>
              ))}
            </div>
            
            {/* Status */}
            <div className="mt-6 pt-4 border-t border-white/[0.05]">
              <div className="flex items-center gap-2">
                <div className="w-1.5 h-1.5 bg-accent rounded-full animate-pulse" />
                <span className="text-[10px] font-mono text-white/30">System online</span>
              </div>
            </div>
          </div>
          
        </div>
      </section>
      
      <style jsx global>{`
        @keyframes ticker {
          0% { transform: translateX(0); }
          100% { transform: translateX(-33.33%); }
        }
      `}</style>
    </CommandCenterLayout>
  )
}