'use client'

import { useCallback, useState } from 'react'
import clsx from 'clsx'
import { 
  ExternalLink, 
  Loader2, 
  Shield, 
  Sparkles, 
  Eye, 
  Wand2,
  Settings,
  Zap,
  Copy,
  Check,
  ShoppingCart,
  Star,
  Lightbulb,
  RefreshCw,
} from 'lucide-react'
import { api } from '@/lib/api'
import { useAnalyzePanelStore } from '@/lib/analyze-store'
import { useStore } from '@/lib/store'

// ============================================================================
// CONSTANTS
// ============================================================================

const PATTERNS = [
  { 
    key: 'cvcvc', 
    label: 'CVCVC', 
    desc: 'Classic 5-letter brandables',
    examples: ['Zalor', 'Mivex', 'Ronix'],
    color: 'accent'
  },
  { 
    key: 'cvccv', 
    label: 'CVCCV', 
    desc: 'Punchy 5-letter names',
    examples: ['Bento', 'Salvo', 'Vento'],
    color: 'blue'
  },
  { 
    key: 'human', 
    label: 'Human', 
    desc: 'AI agent ready names',
    examples: ['Siri', 'Alexa', 'Levi'],
    color: 'purple'
  },
]

const TLDS = [
  { tld: 'com', premium: true, label: '.com' },
  { tld: 'io', premium: true, label: '.io' },
  { tld: 'ai', premium: true, label: '.ai' },
  { tld: 'co', premium: false, label: '.co' },
  { tld: 'net', premium: false, label: '.net' },
  { tld: 'org', premium: false, label: '.org' },
  { tld: 'app', premium: false, label: '.app' },
  { tld: 'dev', premium: false, label: '.dev' },
]

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

export function BrandableForgeTab({ showToast }: { showToast: (message: string, type?: any) => void }) {
  const openAnalyze = useAnalyzePanelStore((s) => s.open)
  const addDomain = useStore((s) => s.addDomain)

  // Config State
  const [pattern, setPattern] = useState('cvcvc')
  const [selectedTlds, setSelectedTlds] = useState<string[]>(['com', 'io'])
  const [limit, setLimit] = useState(30)
  const [showConfig, setShowConfig] = useState(false)

  // Results State
  const [loading, setLoading] = useState(false)
  const [items, setItems] = useState<Array<{ domain: string; status: string }>>([])
  const [error, setError] = useState<string | null>(null)
  const [tracking, setTracking] = useState<string | null>(null)
  const [copied, setCopied] = useState<string | null>(null)

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

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

  const copyAll = useCallback(() => {
    if (items.length === 0) return
    navigator.clipboard.writeText(items.map(i => i.domain).join('\n'))
    showToast(`Copied ${items.length} domains to clipboard`, 'success')
  }, [items, showToast])

  const run = useCallback(async () => {
    if (selectedTlds.length === 0) {
      showToast('Select at least one TLD', 'error')
      return
    }
    setLoading(true)
    setError(null)
    setItems([])
    try {
      const res = await api.huntBrandables({ pattern, tlds: selectedTlds, limit, max_checks: 400 })
      setItems(res.items.map((i) => ({ domain: i.domain, status: i.status })))
      if (res.items.length === 0) {
        showToast('No available domains found. Try different settings.', 'info')
      } else {
        showToast(`Found ${res.items.length} available brandable domains!`, 'success')
      }
    } catch (e) {
      const msg = e instanceof Error ? e.message : String(e)
      setError(msg)
      showToast(msg, 'error')
      setItems([])
    } finally {
      setLoading(false)
    }
  }, [pattern, selectedTlds, limit, showToast])

  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 currentPattern = PATTERNS.find(p => p.key === pattern)

  return (
    <div className="space-y-6">
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* MAIN GENERATOR CARD */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <div className="border border-white/[0.08] bg-[#020202]">
        {/* Header */}
        <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-purple-500/10 border border-accent/30 flex items-center justify-center">
                <Wand2 className="w-5 h-5 text-accent" />
              </div>
              <div>
                <h3 className="text-base font-bold text-white">Brandable Forge</h3>
                <p className="text-[11px] font-mono text-white/40">
                  AI-powered brandable name generator
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => setShowConfig(!showConfig)}
                className={clsx(
                  "w-9 h-9 flex items-center justify-center border transition-all",
                  showConfig 
                    ? "border-accent/30 bg-accent/10 text-accent" 
                    : "border-white/10 text-white/40 hover:text-white hover:bg-white/5"
                )}
                title="Settings"
              >
                <Settings className="w-4 h-4" />
              </button>
              <button
                onClick={run}
                disabled={loading || selectedTlds.length === 0}
                className={clsx(
                  "h-9 px-5 text-sm font-bold uppercase tracking-wider transition-all flex items-center gap-2",
                  loading || selectedTlds.length === 0
                    ? "bg-white/5 text-white/20 cursor-not-allowed" 
                    : "bg-accent text-black hover:bg-white"
                )}
              >
                {loading ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Generating...
                  </>
                ) : (
                  <>
                    <Sparkles className="w-4 h-4" />
                    Generate
                  </>
                )}
              </button>
            </div>
          </div>
        </div>

        {/* Pattern Selection */}
        <div className="p-4 border-b border-white/[0.08]">
          <div className="flex items-center gap-2 mb-3">
            <Lightbulb className="w-3.5 h-3.5 text-white/30" />
            <span className="text-[10px] font-mono text-white/40 uppercase tracking-wider">Choose Pattern</span>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
            {PATTERNS.map((p) => {
              const isActive = pattern === p.key
              const colorClass = p.color === 'accent' ? 'accent' : p.color === 'blue' ? 'blue-400' : 'purple-400'
              return (
                <button
                  key={p.key}
                  onClick={() => setPattern(p.key)}
                  className={clsx(
                    "p-4 border text-left transition-all group",
                    isActive 
                      ? `border-${colorClass}/40 bg-${colorClass}/10` 
                      : "border-white/[0.08] hover:border-white/20 bg-white/[0.02] hover:bg-white/[0.04]"
                  )}
                >
                  <div className="flex items-center justify-between mb-2">
                    <span className={clsx(
                      "text-sm font-bold font-mono",
                      isActive ? `text-${colorClass}` : "text-white/70 group-hover:text-white"
                    )}>
                      {p.label}
                    </span>
                    {isActive && (
                      <div className={`w-2 h-2 rounded-full bg-${colorClass}`} />
                    )}
                  </div>
                  <p className="text-[11px] text-white/40 mb-2">{p.desc}</p>
                  <div className="flex items-center gap-1.5">
                    {p.examples.map((ex, i) => (
                      <span 
                        key={ex} 
                        className={clsx(
                          "text-[10px] font-mono px-1.5 py-0.5 border",
                          isActive 
                            ? "text-white/60 border-white/20 bg-white/5" 
                            : "text-white/30 border-white/10"
                        )}
                      >
                        {ex}
                      </span>
                    ))}
                  </div>
                </button>
              )
            })}
          </div>
        </div>

        {/* TLD Selection */}
        <div className="p-4 border-b border-white/[0.08]">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-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>
            <button
              onClick={() => setSelectedTlds(selectedTlds.length === TLDS.length ? ['com'] : TLDS.map(t => t.tld))}
              className="text-[10px] font-mono text-accent hover:text-white transition-colors"
            >
              {selectedTlds.length === TLDS.length ? 'Select .com only' : 'Select all'}
            </button>
          </div>
          <div className="flex flex-wrap gap-2">
            {TLDS.map((t) => (
              <button
                key={t.tld}
                onClick={() => toggleTld(t.tld)}
                className={clsx(
                  "px-3 py-2 text-[11px] font-mono uppercase border transition-all flex items-center gap-1.5",
                  selectedTlds.includes(t.tld)
                    ? "border-accent bg-accent/10 text-accent"
                    : "border-white/[0.08] text-white/40 hover:text-white/60 hover:border-white/20"
                )}
              >
                {t.premium && <Star className="w-3 h-3" />}
                {t.label}
              </button>
            ))}
          </div>
        </div>

        {/* Advanced Config */}
        {showConfig && (
          <div className="p-4 border-b border-white/[0.08] bg-white/[0.01] animate-in fade-in slide-in-from-top-2 duration-200">
            <div className="flex items-center gap-6">
              <div>
                <label className="block text-[10px] font-mono text-white/40 mb-1.5 uppercase tracking-wider">Results Count</label>
                <div className="flex items-center gap-2">
                  <input
                    type="range"
                    value={limit}
                    onChange={(e) => setLimit(Number(e.target.value))}
                    min={10}
                    max={100}
                    step={10}
                    className="w-32 accent-accent"
                  />
                  <span className="text-sm font-mono text-white w-8">{limit}</span>
                </div>
              </div>
              <div className="flex-1 text-[10px] font-mono text-white/30 border-l border-white/10 pl-6">
                <p>We'll check up to 400 random combinations and return the first {limit} verified available domains.</p>
              </div>
            </div>
          </div>
        )}

        {/* Stats Bar */}
        <div className="px-4 py-3 flex items-center justify-between bg-white/[0.01]">
          <span className="text-[11px] font-mono text-white/40">
            {items.length > 0 ? (
              <span className="flex items-center gap-2">
                <span className="w-2 h-2 rounded-full bg-accent animate-pulse" />
                {items.length} brandable domains ready
              </span>
            ) : (
              'Configure settings and click Generate'
            )}
          </span>
          {items.length > 0 && (
            <button
              onClick={copyAll}
              className="flex items-center gap-1.5 text-[10px] font-mono text-accent hover:text-white transition-colors"
            >
              <Copy className="w-3 h-3" />
              Copy All
            </button>
          )}
        </div>
      </div>

      {/* Error Message */}
      {error && (
        <div className="p-4 border border-rose-500/20 bg-rose-500/5 flex items-center gap-3">
          <div className="w-8 h-8 bg-rose-500/10 border border-rose-500/20 flex items-center justify-center shrink-0">
            <Zap className="w-4 h-4 text-rose-400" />
          </div>
          <div>
            <p className="text-xs font-mono text-rose-400">{error}</p>
            <button onClick={run} className="text-[10px] font-mono text-rose-400/60 hover:text-rose-400 mt-1">
              Try again →
            </button>
          </div>
        </div>
      )}

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* RESULTS */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {items.length > 0 && (
        <div className="space-y-2">
          <div className="flex items-center justify-between px-1">
            <span className="text-[10px] font-mono text-white/40 uppercase tracking-wider">
              Generated Domains
            </span>
            <button
              onClick={run}
              disabled={loading}
              className="flex items-center gap-1.5 text-[10px] font-mono text-white/40 hover:text-accent transition-colors"
            >
              <RefreshCw className={clsx("w-3 h-3", loading && "animate-spin")} />
              Regenerate
            </button>
          </div>
          
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-2">
            {items.map((i, idx) => (
              <div 
                key={i.domain} 
                className={clsx(
                  "group p-3 border bg-[#020202] hover:bg-accent/[0.03] transition-all",
                  "border-white/[0.06] hover:border-accent/20"
                )}
              >
                <div className="flex items-center justify-between gap-3">
                  <div className="flex items-center gap-3 min-w-0 flex-1">
                    <div className="w-8 h-8 bg-accent/10 border border-accent/20 flex items-center justify-center shrink-0 text-[10px] font-mono text-accent font-bold">
                      {String(idx + 1).padStart(2, '0')}
                    </div>
                    <button
                      onClick={() => openAnalyze(i.domain)}
                      className="text-sm font-bold text-white font-mono truncate group-hover:text-accent transition-colors text-left"
                    >
                      {i.domain}
                    </button>
                  </div>
                  
                  <div className="flex items-center gap-1.5 shrink-0">
                    <span className="hidden sm:inline-flex text-[9px] font-mono font-bold text-accent bg-accent/10 px-2 py-1 border border-accent/20">
                      ✓ AVAIL
                    </span>
                    
                    <button
                      onClick={() => copyDomain(i.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 === i.domain ? <Check className="w-3.5 h-3.5 text-accent" /> : <Copy className="w-3.5 h-3.5" />}
                    </button>
                    
                    <button
                      onClick={() => track(i.domain)}
                      disabled={tracking === i.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 === i.domain ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Eye className="w-3.5 h-3.5" />}
                    </button>
                    
                    <button
                      onClick={() => openAnalyze(i.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>
                    
                    <a
                      href={`https://www.namecheap.com/domains/registration/results/?domain=${encodeURIComponent(i.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" />
                      <span className="hidden sm:inline">Buy</span>
                    </a>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Empty State */}
      {items.length === 0 && !loading && (
        <div className="text-center py-16 border border-dashed border-white/[0.08] bg-white/[0.01]">
          <div className="w-16 h-16 mx-auto mb-4 bg-accent/5 border border-accent/20 flex items-center justify-center">
            <Wand2 className="w-8 h-8 text-accent/40" />
          </div>
          <h3 className="text-white/60 text-sm font-medium mb-1">Ready to forge</h3>
          <p className="text-white/30 text-xs font-mono max-w-xs mx-auto">
            Select a pattern and TLDs, then click "Generate" to discover available brandable domain names
          </p>
          <div className="mt-6 flex items-center justify-center gap-3 text-[10px] font-mono text-white/20">
            <span className="flex items-center gap-1"><Zap className="w-3 h-3" /> Verified available</span>
            <span>•</span>
            <span className="flex items-center gap-1"><Shield className="w-3 h-3" /> DNS checked</span>
          </div>
        </div>
      )}

      {/* Loading State */}
      {loading && items.length === 0 && (
        <div className="space-y-2">
          {[...Array(6)].map((_, i) => (
            <div key={i} className="p-3 border border-white/[0.06] bg-[#020202] animate-pulse">
              <div className="flex items-center gap-3">
                <div className="w-8 h-8 bg-white/10 rounded" />
                <div className="h-4 w-32 bg-white/10 rounded" />
                <div className="ml-auto flex gap-2">
                  <div className="w-8 h-8 bg-white/5 rounded" />
                  <div className="w-8 h-8 bg-white/5 rounded" />
                  <div className="w-16 h-8 bg-white/5 rounded" />
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
