'use client'

import { useCallback, useEffect, useMemo, useState } from 'react'
import clsx from 'clsx'
import { 
  ExternalLink, 
  Loader2, 
  Search, 
  Shield, 
  Sparkles, 
  Eye, 
  TrendingUp,
  RefreshCw,
  Globe,
  Zap,
  X,
  Check,
  Copy,
  ShoppingCart,
  Flame,
  ArrowRight,
  AlertCircle
} from 'lucide-react'
import { api } from '@/lib/api'
import { useAnalyzePanelStore } from '@/lib/analyze-store'
import { useStore } from '@/lib/store'

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

const GEO_OPTIONS = [
  { value: 'US', label: 'United States', flag: '🇺🇸' },
  { value: 'CH', label: 'Switzerland', flag: '🇨🇭' },
  { value: 'DE', label: 'Germany', flag: '🇩🇪' },
  { value: 'GB', label: 'United Kingdom', flag: '🇬🇧' },
  { value: 'FR', label: 'France', flag: '🇫🇷' },
  { value: 'CA', label: 'Canada', flag: '🇨🇦' },
  { value: 'AU', label: 'Australia', flag: '🇦🇺' },
]

const POPULAR_TLDS = ['com', 'io', 'ai', 'co', 'net', 'org', 'app', 'dev']

// ============================================================================
// HELPERS
// ============================================================================

function normalizeKeyword(s: string) {
  return s.trim().replace(/\s+/g, ' ')
}

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

export function TrendSurferTab({ showToast }: { showToast: (message: string, type?: any) => void }) {
  const openAnalyze = useAnalyzePanelStore((s) => s.open)
  const addDomain = useStore((s) => s.addDomain)
  
  // Trends State
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [geo, setGeo] = useState('US')
  const [trends, setTrends] = useState<Array<{ title: string; approx_traffic?: string | null; link?: string | null }>>([])
  const [selected, setSelected] = useState<string>('')
  const [refreshing, setRefreshing] = useState(false)

  // Keyword Check State
  const [keywordInput, setKeywordInput] = useState('')
  const [keywordFocused, setKeywordFocused] = useState(false)
  const [selectedTlds, setSelectedTlds] = useState<string[]>(['com', 'io', 'ai'])
  const [availability, setAvailability] = useState<Array<{ domain: string; status: string; is_available: boolean | null }>>([])
  const [checking, setChecking] = useState(false)

  // Typo Check State
  const [brand, setBrand] = useState('')
  const [brandFocused, setBrandFocused] = useState(false)
  const [typos, setTypos] = useState<Array<{ domain: string; status: string }>>([])
  const [typoLoading, setTypoLoading] = useState(false)
  
  // Tracking & Copy State
  const [tracking, setTracking] = useState<string | null>(null)
  const [copied, setCopied] = useState<string | null>(null)

  const copyDomain = useCallback((domain: string) => {
    navigator.clipboard.writeText(domain)
    setCopied(domain)
    setTimeout(() => setCopied(null), 1500)
  }, [])

  const track = useCallback(
    async (domain: string) => {
      if (tracking) return
      setTracking(domain)
      try {
        await addDomain(domain)
        showToast(`Added to watchlist: ${domain}`, 'success')
      } catch (e) {
        showToast(e instanceof Error ? e.message : 'Failed to track domain', 'error')
      } finally {
        setTracking(null)
      }
    },
    [addDomain, showToast, tracking]
  )

  const loadTrends = useCallback(async (isRefresh = false) => {
    if (isRefresh) setRefreshing(true)
    setError(null)
    try {
      const res = await api.getHuntTrends(geo)
      setTrends(res.items || [])
      if (!selected && res.items?.[0]?.title) setSelected(res.items[0].title)
    } catch (e) {
      const msg = e instanceof Error ? e.message : String(e)
      setError(msg)
      setTrends([])
    } finally {
      if (isRefresh) setRefreshing(false)
    }
  }, [geo, selected])

  useEffect(() => {
    let cancelled = false
    const run = async () => {
      setLoading(true)
      try {
        await loadTrends()
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : String(e))
      } finally {
        if (!cancelled) setLoading(false)
      }
    }
    run()
    return () => { cancelled = true }
  }, [loadTrends])

  const keyword = useMemo(() => normalizeKeyword(keywordInput || selected || ''), [keywordInput, selected])

  const toggleTld = useCallback((tld: string) => {
    setSelectedTlds(prev => 
      prev.includes(tld) ? prev.filter(t => t !== tld) : [...prev, tld]
    )
  }, [])

  const runCheck = useCallback(async () => {
    if (!keyword) return
    if (selectedTlds.length === 0) {
      showToast('Select at least one TLD', 'error')
      return
    }
    setChecking(true)
    try {
      const kw = keyword.toLowerCase().replace(/\s+/g, '')
      const res = await api.huntKeywords({ keywords: [kw], tlds: selectedTlds })
      setAvailability(res.items.map((r) => ({ domain: r.domain, status: r.status, is_available: r.is_available })))
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Failed to check availability'
      showToast(msg, 'error')
      setAvailability([])
    } finally {
      setChecking(false)
    }
  }, [keyword, selectedTlds, showToast])

  const runTypos = useCallback(async () => {
    const b = brand.trim()
    if (!b) return
    setTypoLoading(true)
    try {
      const res = await api.huntTypos({ brand: b, tlds: ['com'], limit: 50 })
      setTypos(res.items.map((i) => ({ domain: i.domain, status: i.status })))
      if (res.items.length === 0) {
        showToast('No available typo domains found', 'info')
      }
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Failed to run typo check'
      showToast(msg, 'error')
      setTypos([])
    } finally {
      setTypoLoading(false)
    }
  }, [brand, showToast])

  const availableCount = useMemo(() => availability.filter(a => a.status === 'available').length, [availability])
  const currentGeo = GEO_OPTIONS.find(g => g.value === geo)

  if (loading) {
    return (
      <div className="space-y-4">
        {/* Skeleton Loader */}
        <div className="border border-white/[0.08] bg-[#020202] animate-pulse">
          <div className="px-4 py-4 border-b border-white/[0.08]">
            <div className="h-5 w-48 bg-white/10 rounded mb-2" />
            <div className="h-3 w-32 bg-white/5 rounded" />
          </div>
          <div className="p-4 flex flex-wrap gap-2">
            {[...Array(8)].map((_, i) => (
              <div key={i} className="h-10 w-24 bg-white/5 rounded" />
            ))}
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* TRENDING TOPICS */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <div className="border border-white/[0.08] bg-[#020202]">
        <div className="px-4 py-4 border-b border-white/[0.08]">
          <div className="flex items-start justify-between gap-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-gradient-to-br from-accent/20 to-accent/5 border border-accent/30 flex items-center justify-center">
                <Flame className="w-5 h-5 text-accent" />
              </div>
              <div>
                <h3 className="text-base font-bold text-white">Trending Now</h3>
                <p className="text-[11px] font-mono text-white/40">
                  Real-time Google Trends • {currentGeo?.flag} {currentGeo?.label}
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <select
                value={geo}
                onChange={(e) => { setGeo(e.target.value); setSelected(''); setAvailability([]) }}
                className="bg-white/[0.03] border border-white/10 px-3 py-2 text-xs font-mono text-white/70 outline-none focus:border-accent/40 cursor-pointer hover:bg-white/[0.05] transition-colors"
              >
                {GEO_OPTIONS.map(g => (
                  <option key={g.value} value={g.value}>{g.flag} {g.label}</option>
                ))}
              </select>
              <button
                onClick={() => loadTrends(true)}
                disabled={refreshing}
                className="w-9 h-9 flex items-center justify-center border border-white/10 text-white/40 hover:text-white hover:bg-white/5 transition-all"
              >
                <RefreshCw className={clsx("w-4 h-4", refreshing && "animate-spin")} />
              </button>
            </div>
          </div>
        </div>

        {error ? (
          <div className="p-4 flex items-center gap-3 bg-rose-500/5 border-b border-rose-500/20">
            <AlertCircle className="w-4 h-4 text-rose-400 shrink-0" />
            <p className="text-xs font-mono text-rose-400">{error}</p>
            <button 
              onClick={() => loadTrends(true)} 
              className="ml-auto text-[10px] font-mono text-rose-400 underline hover:no-underline"
            >
              Retry
            </button>
          </div>
        ) : (
          <div className="p-4">
            <div className="flex flex-wrap gap-2">
              {trends.slice(0, 16).map((t, idx) => {
                const active = selected === t.title
                const isHot = idx < 3
                return (
                  <button
                    key={t.title}
                    onClick={() => {
                      setSelected(t.title)
                      setKeywordInput('')
                      setAvailability([])
                    }}
                    className={clsx(
                      'group relative px-4 py-2.5 border text-left transition-all',
                      active 
                        ? 'border-accent bg-accent/10' 
                        : 'border-white/[0.08] hover:border-white/20 bg-white/[0.02] hover:bg-white/[0.04]'
                    )}
                  >
                    <div className="flex items-center gap-2">
                      {isHot && (
                        <span className="text-[9px] font-bold text-orange-400 bg-orange-400/10 px-1 py-0.5">
                          🔥
                        </span>
                      )}
                      <span className={clsx(
                        "text-xs font-medium truncate max-w-[140px]",
                        active ? "text-accent" : "text-white/70 group-hover:text-white"
                      )}>
                        {t.title}
                      </span>
                    </div>
                    {t.approx_traffic && (
                      <div className="text-[9px] text-white/30 mt-0.5 font-mono">{t.approx_traffic}</div>
                    )}
                  </button>
                )
              })}
            </div>
            {trends.length === 0 && (
              <div className="text-center py-6 text-white/30 text-xs font-mono">
                No trends available for this region
              </div>
            )}
          </div>
        )}
      </div>

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* DOMAIN AVAILABILITY CHECKER */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <div className="border border-white/[0.08] bg-[#020202]">
        <div className="px-4 py-4 border-b border-white/[0.08]">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-white/[0.03] border border-white/[0.08] flex items-center justify-center">
              <Globe className="w-5 h-5 text-white/50" />
            </div>
            <div>
              <h3 className="text-base font-bold text-white">Check Availability</h3>
              <p className="text-[11px] font-mono text-white/40">
                {keyword ? `Find ${keyword.toLowerCase().replace(/\s+/g, '')} across multiple TLDs` : 'Select a trend or enter a keyword'}
              </p>
            </div>
          </div>
        </div>

        <div className="p-4 space-y-4">
          {/* Keyword Input */}
          <div className="flex gap-2">
            <div className={clsx(
              "flex-1 relative border-2 transition-all",
              keywordFocused ? "border-accent bg-accent/[0.03]" : "border-white/[0.08] bg-white/[0.02]"
            )}>
              <div className="flex items-center">
                <Search className={clsx("w-4 h-4 ml-4 transition-colors", keywordFocused ? "text-accent" : "text-white/30")} />
                <input
                  value={keywordInput || selected}
                  onChange={(e) => setKeywordInput(e.target.value)}
                  onFocus={() => setKeywordFocused(true)}
                  onBlur={() => setKeywordFocused(false)}
                  onKeyDown={(e) => e.key === 'Enter' && runCheck()}
                  placeholder="Enter keyword or select trend above..."
                  className="flex-1 bg-transparent px-3 py-3.5 text-sm text-white placeholder:text-white/25 outline-none font-mono"
                />
                {(keywordInput || selected) && (
                  <button 
                    onClick={() => { setKeywordInput(''); setSelected(''); setAvailability([]) }} 
                    className="p-3 text-white/30 hover:text-white transition-colors"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
            </div>
            <button
              onClick={runCheck}
              disabled={!keyword || checking}
              className={clsx(
                "px-6 py-3 text-sm font-bold uppercase tracking-wider transition-all flex items-center gap-2",
                !keyword || checking
                  ? "bg-white/5 text-white/20 cursor-not-allowed"
                  : "bg-accent text-black hover:bg-white"
              )}
            >
              {checking ? <Loader2 className="w-4 h-4 animate-spin" /> : <Zap className="w-4 h-4" />}
              Check
            </button>
          </div>

          {/* TLD Selection */}
          <div>
            <div className="flex items-center gap-2 mb-2">
              <span className="text-[10px] font-mono text-white/40 uppercase tracking-wider">Select TLDs</span>
              <span className="text-[10px] font-mono text-white/20">({selectedTlds.length} selected)</span>
            </div>
            <div className="flex flex-wrap gap-1.5">
              {POPULAR_TLDS.map(tld => (
                <button
                  key={tld}
                  onClick={() => toggleTld(tld)}
                  className={clsx(
                    "px-3 py-1.5 text-[11px] font-mono uppercase border transition-all",
                    selectedTlds.includes(tld)
                      ? "border-accent bg-accent/10 text-accent"
                      : "border-white/[0.08] text-white/40 hover:text-white/60 hover:border-white/20"
                  )}
                >
                  .{tld}
                </button>
              ))}
            </div>
          </div>

          {/* Results */}
          {availability.length > 0 && (
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-[10px] font-mono text-white/40 uppercase tracking-wider">
                  Results • {availableCount} available
                </span>
              </div>
              <div className="space-y-1">
                {availability.map((a) => {
                  const isAvailable = a.status === 'available'
                  return (
                    <div 
                      key={a.domain} 
                      className={clsx(
                        "p-3 flex items-center justify-between gap-3 border transition-all",
                        isAvailable 
                          ? "bg-accent/[0.03] border-accent/20 hover:bg-accent/[0.06]" 
                          : "bg-white/[0.02] border-white/[0.06] hover:bg-white/[0.04]"
                      )}
                    >
                      <div className="flex items-center gap-3 min-w-0 flex-1">
                        <div className={clsx(
                          "w-2.5 h-2.5 rounded-full shrink-0",
                          isAvailable ? "bg-accent" : "bg-white/20"
                        )} />
                        <button
                          onClick={() => openAnalyze(a.domain)}
                          className={clsx(
                            "text-sm font-mono truncate text-left transition-colors",
                            isAvailable ? "text-white hover:text-accent" : "text-white/50"
                          )}
                        >
                          {a.domain}
                        </button>
                      </div>
                      
                      <div className="flex items-center gap-2 shrink-0">
                        <span className={clsx(
                          "text-[10px] font-mono font-bold px-2 py-1 border",
                          isAvailable 
                            ? "text-accent bg-accent/10 border-accent/30" 
                            : "text-white/30 bg-white/5 border-white/10"
                        )}>
                          {isAvailable ? '✓ AVAIL' : 'TAKEN'}
                        </span>
                        
                        <button
                          onClick={() => copyDomain(a.domain)}
                          className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/30 hover:text-white hover:bg-white/5 transition-all"
                          title="Copy"
                        >
                          {copied === a.domain ? <Check className="w-3.5 h-3.5 text-accent" /> : <Copy className="w-3.5 h-3.5" />}
                        </button>
                        
                        <button
                          onClick={() => track(a.domain)}
                          disabled={tracking === a.domain}
                          className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/30 hover:text-white hover:bg-white/5 transition-all"
                          title="Add to Watchlist"
                        >
                          {tracking === a.domain ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Eye className="w-3.5 h-3.5" />}
                        </button>
                        
                        <button
                          onClick={() => openAnalyze(a.domain)}
                          className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/30 hover:text-accent hover:border-accent/20 hover:bg-accent/10 transition-all"
                          title="Analyze"
                        >
                          <Shield className="w-3.5 h-3.5" />
                        </button>
                        
                        {isAvailable && (
                          <a
                            href={`https://www.namecheap.com/domains/registration/results/?domain=${a.domain}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="h-8 px-3 bg-accent text-black text-[10px] font-bold uppercase flex items-center gap-1.5 hover:bg-white transition-colors"
                          >
                            <ShoppingCart className="w-3 h-3" />
                            Buy
                          </a>
                        )}
                      </div>
                    </div>
                  )
                })}
              </div>
            </div>
          )}

          {/* Empty State */}
          {availability.length === 0 && keyword && !checking && (
            <div className="text-center py-10 border border-dashed border-white/[0.08] bg-white/[0.01]">
              <Zap className="w-8 h-8 text-white/10 mx-auto mb-3" />
              <p className="text-white/40 text-sm font-mono mb-1">Ready to check</p>
              <p className="text-white/25 text-xs font-mono">
                Click "Check" to find available domains for <span className="text-accent">{keyword.toLowerCase().replace(/\s+/g, '')}</span>
              </p>
            </div>
          )}
        </div>
      </div>

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* TYPO FINDER */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <div className="border border-white/[0.08] bg-[#020202]">
        <div className="px-4 py-4 border-b border-white/[0.08]">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-purple-500/10 border border-purple-500/20 flex items-center justify-center">
              <Sparkles className="w-5 h-5 text-purple-400" />
            </div>
            <div>
              <h3 className="text-base font-bold text-white">Typo Finder</h3>
              <p className="text-[11px] font-mono text-white/40">
                Find available misspellings of popular brands
              </p>
            </div>
          </div>
        </div>

        <div className="p-4 space-y-4">
          <div className="flex gap-2">
            <div className={clsx(
              "flex-1 relative border-2 transition-all",
              brandFocused ? "border-purple-400/50 bg-purple-400/[0.03]" : "border-white/[0.08] bg-white/[0.02]"
            )}>
              <div className="flex items-center">
                <Sparkles className={clsx("w-4 h-4 ml-4 transition-colors", brandFocused ? "text-purple-400" : "text-white/30")} />
                <input
                  value={brand}
                  onChange={(e) => setBrand(e.target.value)}
                  onFocus={() => setBrandFocused(true)}
                  onBlur={() => setBrandFocused(false)}
                  onKeyDown={(e) => e.key === 'Enter' && runTypos()}
                  placeholder="Enter a brand name (e.g. Google, Amazon, Shopify)..."
                  className="flex-1 bg-transparent px-3 py-3.5 text-sm text-white placeholder:text-white/25 outline-none font-mono"
                />
                {brand && (
                  <button onClick={() => { setBrand(''); setTypos([]) }} className="p-3 text-white/30 hover:text-white">
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
            </div>
            <button
              onClick={runTypos}
              disabled={!brand.trim() || typoLoading}
              className={clsx(
                "px-6 py-3 text-sm font-bold uppercase tracking-wider transition-all flex items-center gap-2",
                !brand.trim() || typoLoading
                  ? "bg-white/5 text-white/20 cursor-not-allowed"
                  : "bg-purple-500 text-white hover:bg-purple-400"
              )}
            >
              {typoLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <ArrowRight className="w-4 h-4" />}
              Find
            </button>
          </div>

          {/* Typo Results */}
          {typos.length > 0 && (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
              {typos.map((t) => (
                <div 
                  key={t.domain} 
                  className="group border border-white/[0.08] bg-white/[0.02] px-3 py-2.5 flex items-center justify-between hover:border-purple-400/30 hover:bg-purple-400/[0.03] transition-all"
                >
                  <button
                    onClick={() => openAnalyze(t.domain)}
                    className="text-xs font-mono text-white/70 group-hover:text-purple-400 truncate text-left transition-colors"
                  >
                    {t.domain}
                  </button>
                  <div className="flex items-center gap-1.5 shrink-0 ml-2">
                    <button
                      onClick={() => copyDomain(t.domain)}
                      className="w-6 h-6 flex items-center justify-center text-white/30 hover:text-white transition-colors"
                      title="Copy"
                    >
                      {copied === t.domain ? <Check className="w-3 h-3 text-accent" /> : <Copy className="w-3 h-3" />}
                    </button>
                    <button
                      onClick={() => track(t.domain)}
                      disabled={tracking === t.domain}
                      className="w-6 h-6 flex items-center justify-center text-white/30 hover:text-white transition-colors"
                      title="Track"
                    >
                      {tracking === t.domain ? <Loader2 className="w-3 h-3 animate-spin" /> : <Eye className="w-3 h-3" />}
                    </button>
                    <a
                      href={`https://www.namecheap.com/domains/registration/results/?domain=${t.domain}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="w-6 h-6 flex items-center justify-center text-white/30 hover:text-accent transition-colors"
                      title="Buy"
                    >
                      <ExternalLink className="w-3 h-3" />
                    </a>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Empty State */}
          {typos.length === 0 && !typoLoading && (
            <div className="text-center py-8 border border-dashed border-white/[0.08] bg-white/[0.01]">
              <p className="text-white/30 text-xs font-mono">
                Enter a brand name to discover available typo domains
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
