'use client'

import { useState, useCallback, useEffect, useRef } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { useAnalyzePanelStore } from '@/lib/analyze-store'
import {
  Search,
  X,
  Loader2,
  CheckCircle2,
  XCircle,
  Eye,
  ArrowRight,
  Shield,
  Globe,
  Calendar,
  Building,
  Clock,
  RefreshCw,
  Sparkles,
  ExternalLink,
  History,
} from 'lucide-react'
import clsx from 'clsx'

// ============================================================================
// TYPES & CONSTANTS
// ============================================================================

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

interface TldCheckResult {
  tld: string
  domain: string
  is_available: boolean | null
  loading: boolean
  error?: string
}

// Popular TLDs to check when user enters only a name without extension
// Ordered by popularity/importance - most common first for faster perceived loading
const POPULAR_TLDS = ['com', 'ch', 'io', 'net', 'org', 'de', 'ai', 'co', 'app', 'dev']

// Known valid TLDs (subset for quick validation)
const KNOWN_TLDS = new Set([
  'com', 'net', 'org', 'io', 'ch', 'de', 'app', 'dev', 'co', 'ai', 'me', 'tv', 'cc',
  'xyz', 'info', 'biz', 'online', 'site', 'tech', 'store', 'club', 'shop', 'blog',
  'uk', 'fr', 'nl', 'eu', 'be', 'at', 'us', 'ca', 'au', 'li', 'it', 'es', 'pl',
  'pro', 'mobi', 'name', 'page', 'new', 'day', 'world', 'email', 'link', 'click',
  'digital', 'media', 'agency', 'studio', 'design', 'marketing', 'solutions',
])

// ============================================================================
// COMPONENT
// ============================================================================

interface SearchTabProps {
  showToast: (message: string, type?: 'success' | 'error' | 'info') => void
}

export function SearchTab({ showToast }: SearchTabProps) {
  const { addDomain } = useStore()
  const openAnalyze = useAnalyzePanelStore((s) => s.open)

  const [searchQuery, setSearchQuery] = useState('')
  const [searchResult, setSearchResult] = useState<SearchResult | null>(null)
  const [tldResults, setTldResults] = useState<TldCheckResult[]>([])
  const [addingToWatchlist, setAddingToWatchlist] = useState(false)
  const [searchFocused, setSearchFocused] = useState(false)
  const [recentSearches, setRecentSearches] = useState<string[]>([])
  const [searchMode, setSearchMode] = useState<'single' | 'multi'>('single')
  const searchInputRef = useRef<HTMLInputElement>(null)

  // Load recent searches from localStorage
  useEffect(() => {
    const stored = localStorage.getItem('pounce_recent_searches')
    if (stored) {
      try {
        setRecentSearches(JSON.parse(stored).slice(0, 8))
      } catch {
        // Ignore invalid JSON
      }
    }
  }, [])

  // Save to recent searches
  const saveToRecent = useCallback((domain: string) => {
    setRecentSearches((prev) => {
      const filtered = prev.filter((d) => d !== domain)
      const updated = [domain, ...filtered].slice(0, 8)
      localStorage.setItem('pounce_recent_searches', JSON.stringify(updated))
      return updated
    })
  }, [])

  // Check if TLD is valid
  const isValidTld = useCallback((tld: string): boolean => {
    return KNOWN_TLDS.has(tld.toLowerCase())
  }, [])

  // Check single domain
  const checkSingleDomain = useCallback(async (domain: string): Promise<SearchResult> => {
    try {
      const result = await api.checkDomain(domain)
      return {
        domain: result.domain,
        status: result.status,
        is_available: result.is_available,
        registrar: result.registrar,
        expiration_date: result.expiration_date,
        loading: false,
      }
    } catch (err: any) {
      return {
        domain,
        status: 'error',
        is_available: null,
        registrar: null,
        expiration_date: null,
        loading: false,
        error: err?.message || 'Check failed',
      }
    }
  }, [])

  // Check multiple TLDs for a name - with progressive loading and quick mode
  const checkMultipleTlds = useCallback(async (name: string) => {
    // Initialize results with loading state
    const initialResults: TldCheckResult[] = POPULAR_TLDS.map(tld => ({
      tld,
      domain: `${name}.${tld}`,
      is_available: null,
      loading: true,
    }))
    setTldResults(initialResults)

    // Check each TLD in parallel with progressive updates (using quick=true for speed)
    POPULAR_TLDS.forEach(async (tld, index) => {
      const domain = `${name}.${tld}`
      try {
        // Use quick=true for DNS-only check (much faster!)
        const result = await api.checkDomain(domain, true)
        setTldResults(prev => {
          const updated = [...prev]
          updated[index] = {
            tld,
            domain,
            is_available: result.is_available,
            loading: false,
          }
          return updated
        })
      } catch {
        setTldResults(prev => {
          const updated = [...prev]
          updated[index] = {
            tld,
            domain,
            is_available: null,
            loading: false,
            error: 'Check failed',
          }
          return updated
        })
      }
    })
  }, [])

  // Search Handler
  const handleSearch = useCallback(async (domainInput: string) => {
    if (!domainInput.trim()) {
      setSearchResult(null)
      setTldResults([])
      return
    }
    
    const cleanInput = domainInput.trim().toLowerCase().replace(/\s+/g, '')
    
    // Check if input contains a dot (has TLD)
    if (cleanInput.includes('.')) {
      // Single domain mode
      setSearchMode('single')
      setTldResults([])
      
      const parts = cleanInput.split('.')
      const tld = parts[parts.length - 1]
      
      // Check if TLD is valid
      if (!isValidTld(tld)) {
        setSearchResult({
          domain: cleanInput,
          status: 'invalid_tld',
          is_available: null,
          registrar: null,
          expiration_date: null,
          loading: false,
          error: `".${tld}" is not a valid domain extension`,
        })
        return
      }
      
      setSearchResult({ domain: cleanInput, status: 'checking', is_available: null, registrar: null, expiration_date: null, loading: true })
      
      const result = await checkSingleDomain(cleanInput)
      setSearchResult(result)
      if (!result.error) saveToRecent(cleanInput)
    } else {
      // Multi-TLD mode - check multiple extensions
      setSearchMode('multi')
      setSearchResult(null)
      
      // Validate the name part
      if (cleanInput.length < 1 || cleanInput.length > 63) {
        setTldResults([])
        showToast('Domain name must be 1-63 characters', 'error')
        return
      }
      
      if (!/^[a-z0-9-]+$/.test(cleanInput) || cleanInput.startsWith('-') || cleanInput.endsWith('-')) {
        setTldResults([])
        showToast('Domain name contains invalid characters', 'error')
        return
      }
      
      await checkMultipleTlds(cleanInput)
      saveToRecent(cleanInput)
    }
  }, [saveToRecent, checkSingleDomain, checkMultipleTlds, isValidTld, showToast])

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

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

  // Focus input on mount
  useEffect(() => {
    searchInputRef.current?.focus()
  }, [])

  return (
    <div className="space-y-4">
      {/* Search Input */}
      <div className={clsx(
        "relative border-2 transition-all duration-200",
        searchFocused ? "border-accent/50 bg-accent/[0.02]" : "border-white/[0.08] bg-white/[0.02]"
      )}>
        <div className="flex items-center">
          <Search className={clsx("w-5 h-5 ml-4 transition-colors", searchFocused ? "text-accent" : "text-white/30")} />
          <input
            ref={searchInputRef}
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            onFocus={() => setSearchFocused(true)}
            onBlur={() => setSearchFocused(false)}
            onKeyDown={(e) => e.key === 'Enter' && handleSearch(searchQuery)}
            placeholder="domain or name.tld"
            className="flex-1 bg-transparent px-3 py-4 text-base lg:text-lg text-white placeholder:text-white/20 outline-none font-mono"
          />
          {searchQuery && (
            <button
              onClick={() => { setSearchQuery(''); setSearchResult(null) }}
              className="p-4 text-white/30 hover:text-white transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          )}
          <button
            onClick={() => handleSearch(searchQuery)}
            disabled={!searchQuery.trim()}
            className={clsx(
              "h-full px-6 py-4 text-xs font-bold uppercase tracking-widest transition-all shrink-0 border-l border-white/10",
              searchQuery.trim() ? "bg-accent text-black hover:bg-white" : "bg-white/5 text-white/20"
            )}
          >
            Check
          </button>
        </div>
      </div>

      {/* Stats Bar */}
      <div className="flex items-center justify-between px-1 text-[10px] font-mono text-white/30 uppercase tracking-[0.1em]">
        <div className="flex items-center gap-2">
          <div className="w-1 h-1 bg-accent rounded-full animate-pulse" />
          <span>Enter a name or full domain</span>
        </div>
        <div className="flex items-center gap-2">
          <Sparkles className="w-3 h-3 text-accent/60" />
          <span>RDAP/WHOIS READY</span>
        </div>
      </div>

      {/* Single Domain Result */}
      {searchMode === 'single' && searchResult && (
        <div className="animate-in fade-in slide-in-from-bottom-2 duration-300">
          {searchResult.loading ? (
            <div className="flex flex-col items-center justify-center py-20 border border-white/[0.08] bg-white/[0.01]">
              <div className="relative">
                <div className="absolute inset-0 bg-accent/20 blur-xl rounded-full animate-pulse" />
                <Loader2 className="w-8 h-8 animate-spin text-accent relative z-10" />
              </div>
              <span className="text-[10px] text-white/40 font-mono mt-4 uppercase tracking-[0.2em]">Checking global availability...</span>
            </div>
          ) : searchResult.error ? (
            // Error state
            <div className="border border-rose-500/30 bg-rose-500/[0.02]">
              <div className="p-4 lg:p-6">
                <div className="flex items-center gap-4">
                  <div className="w-14 h-14 flex items-center justify-center border border-rose-500/30 bg-rose-500/10 shrink-0">
                    <XCircle className="w-6 h-6 text-rose-500" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="text-xl font-bold text-white font-mono truncate tracking-tight">{searchResult.domain}</div>
                    <div className="text-[11px] font-mono text-rose-400 mt-1 uppercase tracking-wider">{searchResult.error}</div>
                  </div>
                </div>
              </div>
            </div>
          ) : (
            <div className={clsx(
              "border bg-[#020202] transition-all duration-500",
              searchResult.is_available ? "border-accent/30 shadow-[0_0_40px_-20px_rgba(34,211,126,0.2)]" : "border-rose-500/20"
            )}>
              {/* Result Row */}
              <div className="p-4 lg:p-6">
                <div className="flex flex-col lg:grid lg:grid-cols-[1fr_auto] gap-6 items-center">
                  <div className="flex items-center gap-5 min-w-0 w-full">
                    {/* Status Indicator */}
                    <div className={clsx(
                      "w-16 h-16 flex items-center justify-center border shrink-0 transition-colors duration-500",
                      searchResult.is_available ? "bg-accent/10 border-accent/20" : "bg-rose-500/5 border-rose-500/20"
                    )}>
                      {searchResult.is_available ? (
                        <CheckCircle2 className="w-8 h-8 text-accent" />
                      ) : (
                        <XCircle className="w-8 h-8 text-rose-500" />
                      )}
                    </div>

                    {/* Domain Info */}
                    <div className="min-w-0 flex-1">
                      <div className={clsx(
                        "text-2xl lg:text-3xl font-bold font-mono truncate tracking-tight",
                        searchResult.is_available ? "text-white" : "text-rose-400"
                      )}>
                        {searchResult.domain}
                      </div>
                      
                      <div className="flex flex-wrap items-center gap-y-2 gap-x-4 mt-2">
                        <span className={clsx(
                          "px-2 py-0.5 text-[9px] font-bold uppercase tracking-widest border",
                          searchResult.is_available 
                            ? "bg-accent/10 border-accent/20 text-accent" 
                            : "bg-rose-500/10 border-rose-500/20 text-rose-400"
                        )}>
                          {searchResult.is_available ? 'Available' : 'Taken'}
                        </span>
                        
                        {searchResult.registrar && (
                          <div className="flex items-center gap-1.5 text-[10px] font-mono text-white/30 uppercase tracking-wider">
                            <Building className="w-3 h-3" />
                            {searchResult.registrar}
                          </div>
                        )}
                        
                        {searchResult.expiration_date && (
                          <div className="flex items-center gap-1.5 text-[10px] font-mono text-white/30 uppercase tracking-wider">
                            <Clock className="w-3 h-3" />
                            Expires {new Date(searchResult.expiration_date).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* Actions */}
                  <div className="flex items-center gap-2 w-full lg:w-auto">
                    <button
                      onClick={() => openAnalyze(searchResult.domain)}
                      className="flex-1 lg:w-12 lg:h-12 h-12 flex items-center justify-center border border-white/10 text-white/30 hover:text-accent hover:border-accent/30 hover:bg-accent/5 transition-all"
                      title="Deep Analysis"
                    >
                      <Shield className="w-5 h-5" />
                    </button>

                    <button
                      onClick={handleAddToWatchlist}
                      disabled={addingToWatchlist}
                      className={clsx(
                        "flex-1 lg:w-12 lg:h-12 h-12 flex items-center justify-center border transition-all",
                        searchResult.is_available 
                          ? "border-white/10 text-white/30 hover:text-white hover:bg-white/5"
                          : "border-rose-500/20 text-rose-400/40 hover:text-rose-400 hover:bg-rose-500/5"
                      )}
                      title={searchResult.is_available ? "Track domain" : "Monitor drop"}
                    >
                      {addingToWatchlist ? <Loader2 className="w-5 h-5 animate-spin" /> : <Eye className="w-5 h-5" />}
                    </button>

                    {searchResult.is_available ? (
                      <a
                        href={`https://www.namecheap.com/domains/registration/results/?domain=${searchResult.domain}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex-[2] lg:flex-none h-12 px-8 bg-accent text-black text-[11px] font-black uppercase tracking-[0.1em] flex items-center justify-center gap-2 hover:bg-white transition-all shadow-[0_0_20px_-10px_rgba(34,211,126,0.5)]"
                      >
                        Buy Now
                        <ArrowRight className="w-4 h-4" />
                      </a>
                    ) : (
                      <button
                        onClick={handleAddToWatchlist}
                        disabled={addingToWatchlist}
                        className="flex-[2] lg:flex-none h-12 px-8 bg-rose-500/10 text-rose-400 text-[11px] font-bold uppercase tracking-[0.1em] flex items-center justify-center gap-2 hover:bg-rose-500/20 border border-rose-500/20 transition-all"
                      >
                        {addingToWatchlist ? <Loader2 className="w-4 h-4 animate-spin" /> : <Eye className="w-4 h-4" />}
                        Monitor
                      </button>
                    )}
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Multi-TLD Results */}
      {searchMode === 'multi' && tldResults.length > 0 && (
        <div className="animate-in fade-in slide-in-from-bottom-2 duration-400">
          <div className="border border-white/[0.08] bg-[#020202]">
            {/* Header */}
            <div className="px-5 py-4 border-b border-white/[0.08] flex items-center justify-between bg-white/[0.01]">
              <div className="flex items-center gap-3">
                <Globe className="w-4 h-4 text-accent/60" />
                <span className="text-[10px] font-mono text-white/50 uppercase tracking-[0.2em]">
                  Global availability check: <span className="text-white">"{searchQuery}"</span>
                </span>
              </div>
              <div className="flex items-center gap-4">
                <div className="flex items-center gap-1.5">
                  <div className="w-1.5 h-1.5 rounded-full bg-accent" />
                  <span className="text-[10px] font-mono text-accent uppercase font-bold">
                    {tldResults.filter(r => r.is_available === true).length} Free
                  </span>
                </div>
                <div className="flex items-center gap-1.5">
                  <div className="w-1.5 h-1.5 rounded-full bg-rose-500/40" />
                  <span className="text-[10px] font-mono text-white/20 uppercase">
                    {tldResults.filter(r => r.is_available === false).length} Taken
                  </span>
                </div>
              </div>
            </div>

            {/* TLD Grid */}
            <div className="p-4 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-3">
              {tldResults.map((result) => (
                <div
                  key={result.tld}
                  className={clsx(
                    "relative p-4 border transition-all duration-300 group",
                    result.loading 
                      ? "border-white/[0.05] bg-white/[0.01]"
                      : result.is_available 
                        ? "border-accent/20 bg-accent/[0.02] hover:border-accent/60 hover:bg-accent/[0.08] cursor-pointer"
                        : "border-white/[0.05] bg-white/[0.01] opacity-60"
                  )}
                  onClick={() => {
                    if (result.is_available && !result.loading) {
                      setSearchQuery(result.domain)
                      setSearchMode('single')
                      setTldResults([])
                      handleSearch(result.domain)
                    }
                  }}
                >
                  {result.loading ? (
                    <div className="flex items-center justify-center py-2">
                      <Loader2 className="w-5 h-5 animate-spin text-white/10" />
                    </div>
                  ) : (
                    <>
                      <div className="flex items-center justify-between mb-2">
                        <span className={clsx(
                          "text-sm font-mono font-black tracking-tight",
                          result.is_available ? "text-white group-hover:text-accent" : "text-white/20"
                        )}>
                          .{result.tld}
                        </span>
                        {result.is_available ? (
                          <div className="w-5 h-5 rounded-full bg-accent/10 border border-accent/20 flex items-center justify-center">
                            <CheckCircle2 className="w-3 h-3 text-accent" />
                          </div>
                        ) : (
                          <XCircle className="w-4 h-4 text-white/10" />
                        )}
                      </div>
                      <div className={clsx(
                        "text-[9px] font-mono uppercase tracking-[0.1em] font-bold",
                        result.is_available ? "text-accent" : "text-white/20"
                      )}>
                        {result.is_available ? 'Available' : 'Taken'}
                      </div>
                      
                      {result.is_available && (
                        <div className="absolute bottom-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity">
                          <ArrowRight className="w-3 h-3 text-accent" />
                        </div>
                      )}
                    </>
                  )}
                </div>
              ))}
            </div>

            {/* Footer hint */}
            <div className="px-4 py-3 border-t border-white/[0.04] bg-white/[0.01] text-[9px] font-mono text-white/20 text-center uppercase tracking-widest">
              Click an available extension to analyze and buy
            </div>
          </div>
        </div>
      )}

      {/* Recent Searches */}
      {!searchResult && recentSearches.length > 0 && (
        <div className="border border-white/[0.08] bg-white/[0.01]">
          <div className="px-5 py-3 border-b border-white/[0.08] flex items-center justify-between bg-white/[0.01]">
            <div className="flex items-center gap-2">
              <History className="w-4 h-4 text-white/20" />
              <span className="text-[10px] font-mono text-white/40 uppercase tracking-[0.2em]">Recent History</span>
            </div>
            <button
              onClick={() => {
                setRecentSearches([])
                localStorage.removeItem('pounce_recent_searches')
              }}
              className="text-[10px] font-mono text-white/20 hover:text-white transition-colors uppercase tracking-widest"
            >
              Clear All
            </button>
          </div>
          <div className="p-4">
            <div className="flex flex-wrap gap-2">
              {recentSearches.map((domain) => (
                <button
                  key={domain}
                  onClick={() => {
                    setSearchQuery(domain)
                    handleSearch(domain)
                  }}
                  className="group px-4 py-2 border border-white/[0.08] bg-white/[0.01] hover:border-accent/30 hover:bg-accent/[0.03] transition-all"
                >
                  <span className="text-xs font-mono text-white/40 group-hover:text-accent transition-colors">{domain}</span>
                </button>
              ))}
            </div>
          </div>
        </div>
      )}

    </div>
  )
}
