'use client'

import { useCallback, useState } from 'react'
import clsx from 'clsx'
import { 
  Loader2, 
  Shield, 
  Eye, 
  Wand2,
  Zap,
  Copy,
  Check,
  ShoppingCart,
  Sparkles,
  Lock,
  RefreshCw,
  Brain,
  Dices,
  ChevronRight,
  X,
} from 'lucide-react'
import Link from 'next/link'
import { api } from '@/lib/api'
import { useAnalyzePanelStore } from '@/lib/analyze-store'
import { useStore } from '@/lib/store'

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

const PATTERNS = [
  { key: 'cvcvc', label: 'CVCVC', example: 'Zalor', desc: 'Classic 5-letter' },
  { key: 'cvccv', label: 'CVCCV', example: 'Bento', desc: 'Punchy sound' },
  { key: 'human', label: 'Human', example: 'Alexa', desc: 'AI agent names' },
]

const TLDS = ['com', 'io', 'ai', 'co', 'net', 'app']

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

export function BrandableForgeTab({ showToast }: { showToast: (msg: string, type?: any) => void }) {
  const openAnalyze = useAnalyzePanelStore((s) => s.open)
  const addDomain = useStore((s) => s.addDomain)
  const subscription = useStore((s) => s.subscription)
  const tier = (subscription?.tier || '').toLowerCase()
  const hasAI = tier === 'trader' || tier === 'tycoon'

  // Mode selection - AI mode by default if available
  const [mode, setMode] = useState<'pattern' | 'ai'>(hasAI ? 'ai' : 'pattern')

  // Config
  const [pattern, setPattern] = useState('cvcvc')
  const [tlds, setTlds] = useState(['com', 'io'])
  const [concept, setConcept] = useState('')

  // State
  const [results, setResults] = useState<Array<{ domain: string }>>([])
  const [loading, setLoading] = useState(false)
  const [aiLoading, setAiLoading] = useState(false)
  const [copied, setCopied] = useState<string | null>(null)
  const [tracking, setTracking] = useState<string | null>(null)

  // Generate from pattern
  const generatePattern = useCallback(async () => {
    if (tlds.length === 0) {
      showToast('Select at least one TLD', 'error')
      return
    }
    setLoading(true)
    setResults([])
    try {
      const res = await api.huntBrandables({ pattern, tlds, limit: 24, max_checks: 300 })
      setResults(res.items.map(i => ({ domain: i.domain })))
      showToast(`Generated ${res.items.length} assets!`, 'success')
    } catch (e) {
      showToast('Generation failed', 'error')
    } finally {
      setLoading(false)
    }
  }, [pattern, tlds, showToast])

  // Generate from AI concept
  const generateFromConcept = useCallback(async () => {
    if (!concept.trim() || !hasAI) return
    setAiLoading(true)
    setResults([])
    try {
      const res = await api.generateBrandableNames(concept.trim(), undefined, 15)
      if (res.names?.length) {
        const checkRes = await api.huntKeywords({ keywords: res.names, tlds })
        const available = checkRes.items.filter(i => i.status === 'available')
        setResults(available.map(i => ({ domain: i.domain })))
        showToast(`Found ${available.length} free domains via AI!`, 'success')
      }
    } catch (e) {
      showToast('AI generation failed', 'error')
    } finally {
      setAiLoading(false)
    }
  }, [concept, hasAI, tlds, showToast])

  // Actions
  const copy = (domain: string) => {
    navigator.clipboard.writeText(domain)
    setCopied(domain)
    setTimeout(() => setCopied(null), 1500)
  }

  const copyAll = () => {
    navigator.clipboard.writeText(results.map(r => r.domain).join('\n'))
    showToast(`Copied ${results.length} domains`, 'success')
  }

  const track = async (domain: string) => {
    if (tracking) return
    setTracking(domain)
    try {
      await addDomain(domain)
      showToast(`Added: ${domain}`, 'success')
    } catch (e) {
      showToast('Failed to track', 'error')
    } finally {
      setTracking(null)
    }
  }

  const isGenerating = loading || aiLoading

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4 pb-5 border-b border-white/[0.08]">
        <div className="w-12 h-12 bg-purple-500/10 border border-purple-500/20 flex items-center justify-center shrink-0">
          <Wand2 className="w-6 h-6 text-purple-400" />
        </div>
        <div>
          <h2 className="text-xl font-bold text-white font-mono tracking-tight">Brandable Forge</h2>
          <p className="text-[10px] font-mono text-white/40 uppercase tracking-widest mt-1">Synthesize unique, high-value naming assets</p>
        </div>
      </div>

      {/* Mode Selector */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        {/* AI Mode - First/Left */}
        <button
          onClick={() => hasAI && setMode('ai')}
          disabled={!hasAI}
          className={clsx(
            "relative p-5 border transition-all duration-300 text-left group overflow-hidden",
            !hasAI && "opacity-50 grayscale",
            mode === 'ai'
              ? "border-purple-500 bg-purple-500/5 shadow-[0_0_30px_-10px_rgba(168,85,247,0.3)]"
              : "border-white/[0.08] bg-white/[0.01] hover:border-white/20 hover:bg-white/[0.03]"
          )}
        >
          {!hasAI && <div className="absolute top-2 right-2"><Lock className="w-3 h-3 text-white/20" /></div>}
          <div className="flex items-center gap-4 relative z-10">
            <div className={clsx(
              "w-12 h-12 flex items-center justify-center border transition-colors",
              mode === 'ai' ? "border-purple-500/40 bg-purple-500/10" : "border-white/10 bg-white/5"
            )}>
              <Brain className={clsx("w-6 h-6", mode === 'ai' ? "text-purple-400" : "text-white/30")} />
            </div>
            <div>
              <p className={clsx("font-bold font-mono text-sm tracking-tight", mode === 'ai' ? "text-purple-400" : "text-white/70")}>Vision Core AI</p>
              <p className="text-[10px] font-mono text-white/30 uppercase tracking-widest mt-0.5">Concept to Name</p>
            </div>
          </div>
          {mode === 'ai' && <div className="absolute top-0 right-0 w-2 h-2 bg-purple-500" />}
        </button>

        {/* Pattern Mode - Second/Right */}
        <button
          onClick={() => setMode('pattern')}
          className={clsx(
            "relative p-5 border transition-all duration-300 text-left group overflow-hidden",
            mode === 'pattern'
              ? "border-accent bg-accent/5 shadow-[0_0_30px_-10px_rgba(34,211,126,0.2)]"
              : "border-white/[0.08] bg-white/[0.01] hover:border-white/20 hover:bg-white/[0.03]"
          )}
        >
          <div className="flex items-center gap-4 relative z-10">
            <div className={clsx(
              "w-12 h-12 flex items-center justify-center border transition-colors",
              mode === 'pattern' ? "border-accent/30 bg-accent/10" : "border-white/10 bg-white/5"
            )}>
              <Dices className={clsx("w-6 h-6", mode === 'pattern' ? "text-accent" : "text-white/30")} />
            </div>
            <div>
              <p className={clsx("font-bold font-mono text-sm tracking-tight", mode === 'pattern' ? "text-accent" : "text-white/70")}>Pattern Engine</p>
              <p className="text-[10px] font-mono text-white/30 uppercase tracking-widest mt-0.5">Classic Brandables</p>
            </div>
          </div>
          {mode === 'pattern' && <div className="absolute top-0 right-0 w-2 h-2 bg-accent" />}
        </button>
      </div>

      {/* Config Panel */}
      <div className={clsx(
        "border overflow-hidden transition-all duration-500",
        mode === 'ai' ? "border-purple-500/30 bg-purple-500/[0.01]" : "border-white/[0.08] bg-white/[0.01]"
      )}>
        <div className="px-5 py-4 border-b border-white/[0.08] bg-white/[0.01] flex items-center justify-between">
          <div className="flex items-center gap-3">
            <span className="text-[10px] font-mono text-white/30 uppercase tracking-[0.2em]">Synthesis Configuration</span>
          </div>
          <div className="flex items-center gap-2">
            <div className={clsx("w-1 h-1 rounded-full", mode === 'ai' ? "bg-purple-500 animate-pulse" : "bg-accent")} />
            <span className="text-[10px] font-mono text-white/20 uppercase tracking-widest">{mode.toUpperCase()} MODE</span>
          </div>
        </div>

        <div className="p-5 space-y-6">
          {mode === 'pattern' ? (
            <div className="space-y-4">
              <span className="text-[10px] font-mono text-white/30 uppercase tracking-widest">Select Linguistic Pattern</span>
              <div className="grid grid-cols-3 gap-2">
                {PATTERNS.map(p => (
                  <button
                    key={p.key}
                    onClick={() => setPattern(p.key)}
                    className={clsx(
                      "p-3 border transition-all duration-300 group",
                      pattern === p.key
                        ? "border-accent bg-accent/10"
                        : "border-white/10 hover:border-white/20 hover:bg-white/5"
                    )}
                  >
                    <p className={clsx("text-xs font-black font-mono tracking-widest", pattern === p.key ? "text-accent" : "text-white/40 group-hover:text-white/60")}>{p.label}</p>
                    <p className="text-[9px] font-mono text-white/20 mt-1 uppercase tracking-tighter">{p.desc}</p>
                  </button>
                ))}
              </div>
            </div>
          ) : (
            <div className="space-y-4">
              <span className="text-[10px] font-mono text-purple-400 uppercase tracking-widest font-bold">Describe Your Identity Concept</span>
              <textarea
                value={concept}
                onChange={(e) => setConcept(e.target.value)}
                placeholder="e.g., A minimalist AI agent for legal risk management..."
                rows={3}
                className="w-full px-4 py-3 bg-white/[0.03] border border-purple-500/40 text-sm font-mono text-white placeholder:text-white/20 outline-none focus:border-purple-500 resize-none transition-all"
              />
            </div>
          )}

          <div className="space-y-4">
            <span className="text-[10px] font-mono text-white/30 uppercase tracking-widest">Target Extensions</span>
            <div className="flex flex-wrap gap-1.5">
              {TLDS.map(tld => (
                <button
                  key={tld}
                  onClick={() => setTlds(prev => 
                    prev.includes(tld) ? prev.filter(t => t !== tld) : [...prev, tld]
                  )}
                  className={clsx(
                    "px-3 py-1.5 text-[10px] font-mono border transition-all uppercase tracking-widest",
                    tlds.includes(tld)
                      ? mode === 'ai' ? "border-purple-500 bg-purple-500/10 text-purple-300 font-black" : "border-accent bg-accent/10 text-accent font-black"
                      : "border-white/10 text-white/40 hover:text-white hover:bg-white/5"
                  )}
                >
                  .{tld}
                </button>
              ))}
            </div>
          </div>

          <button
            onClick={mode === 'pattern' ? generatePattern : generateFromConcept}
            disabled={isGenerating || (mode === 'ai' && !concept.trim()) || tlds.length === 0}
            className={clsx(
              "w-full py-4 text-[11px] font-black uppercase tracking-[0.2em] flex items-center justify-center gap-3 transition-all",
              isGenerating || (mode === 'ai' && !concept.trim()) || tlds.length === 0
                ? "bg-white/5 text-white/20 border border-white/5"
                : mode === 'ai'
                  ? "bg-purple-600 text-white hover:bg-purple-500 shadow-[0_0_30px_-10px_rgba(168,85,247,0.4)]"
                  : "bg-accent text-black hover:bg-white shadow-[0_0_30px_-10px_rgba(34,211,126,0.4)]"
            )}
          >
            {isGenerating ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
            {mode === 'ai' ? 'Synthesize AI Assets' : `Forge ${pattern.toUpperCase()} Names`}
          </button>
        </div>
      </div>

      {/* AI Upgrade CTA */}
      {mode === 'ai' && !hasAI && (
        <div className="border border-white/10 bg-white/[0.01] p-10 text-center animate-in fade-in zoom-in-95 duration-500">
          <Lock className="w-12 h-12 text-white/5 mx-auto mb-4" />
          <h3 className="text-lg font-bold text-white font-mono tracking-tight mb-2 uppercase">Neural Forge Locked</h3>
          <p className="text-sm text-white/30 font-mono mb-6 max-w-sm mx-auto uppercase tracking-wider leading-relaxed">
            AI-driven naming requires Trader or Tycoon clearance
          </p>
          <Link
            href="/pricing"
            className="inline-flex items-center gap-3 px-8 py-3 bg-accent text-black text-[11px] font-black uppercase tracking-widest hover:bg-white transition-all active:scale-95"
          >
            <Sparkles className="w-4 h-4" />
            Upgrade Plan
          </Link>
        </div>
      )}

      {/* Results */}
      {results.length > 0 && (
        <div className="space-y-4 animate-in fade-in slide-in-from-bottom-4 duration-500">
          <div className="flex items-center justify-between px-1">
            <p className="text-[10px] font-mono text-white/30 uppercase tracking-[0.2em]">
              <span className={clsx("font-black", mode === 'ai' ? "text-purple-400" : "text-accent")}>{results.length}</span> Synthesized naming assets available
            </p>
            <div className="flex gap-4">
              <button onClick={copyAll} className="text-[9px] font-mono text-white/20 hover:text-white uppercase tracking-widest transition-colors">
                Batch Copy
              </button>
            </div>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
            {results.map((r, idx) => (
              <div
                key={r.domain}
                className={clsx(
                  "flex items-center justify-between p-4 border transition-all duration-300 group",
                  mode === 'ai'
                    ? "bg-purple-500/[0.02] border-purple-500/20 hover:border-purple-500/40 hover:bg-purple-500/[0.04]"
                    : "bg-accent/[0.02] border-accent/20 hover:border-accent/40 hover:bg-accent/[0.04]"
                )}
              >
                <div className="flex items-center gap-3 min-w-0">
                  <span className={clsx(
                    "text-[9px] font-bold font-mono px-1.5 py-0.5 border shrink-0",
                    mode === 'ai'
                      ? "bg-purple-500/10 border-purple-500/20 text-purple-300"
                      : "bg-accent/10 border-accent/20 text-accent"
                  )}>
                    {(idx + 1).toString().padStart(2, '0')}
                  </span>
                  <button
                    onClick={() => openAnalyze(r.domain)}
                    className={clsx(
                      "text-sm font-bold font-mono text-white truncate transition-colors",
                      mode === 'ai' ? "group-hover:text-purple-300" : "group-hover:text-accent"
                    )}
                  >
                    {r.domain}
                  </button>
                </div>
                <div className="flex items-center gap-1 shrink-0 opacity-0 group-hover:opacity-100 transition-all transform translate-x-2 group-hover:translate-x-0">
                  <button onClick={() => copy(r.domain)} className="w-7 h-7 flex items-center justify-center border border-white/10 text-white/30 hover:text-white hover:bg-white/5">
                    {copied === r.domain ? <Check className="w-3.5 h-3.5 text-accent" /> : <Copy className="w-3.5 h-3.5" />}
                  </button>
                  <button onClick={() => track(r.domain)} disabled={tracking === r.domain} className="w-7 h-7 flex items-center justify-center border border-white/10 text-white/30 hover:text-white hover:bg-white/5">
                    {tracking === r.domain ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Eye className="w-3.5 h-3.5" />}
                  </button>
                  <button onClick={() => openAnalyze(r.domain)} className="w-7 h-7 flex items-center justify-center border border-white/10 text-white/30 hover:text-accent hover:border-accent/20 hover:bg-accent/5">
                    <Shield className="w-3.5 h-3.5" />
                  </button>
                  <a
                    href={`https://www.namecheap.com/domains/registration/results/?domain=${r.domain}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className={clsx(
                      "h-7 px-3 text-[10px] font-black uppercase tracking-widest flex items-center transition-all",
                      mode === 'ai'
                        ? "bg-purple-600 text-white hover:bg-purple-500"
                        : "bg-accent text-black hover:bg-white"
                    )}
                  >
                    Buy
                  </a>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Empty State */}
      {results.length === 0 && !isGenerating && (
        <div className="text-center py-24 border border-dashed border-white/[0.08] bg-white/[0.01]">
          <Wand2 className="w-12 h-12 text-white/5 mx-auto mb-4" />
          <p className="text-white/40 text-sm font-mono uppercase tracking-widest font-bold">Forge is currently idle</p>
          <p className="text-white/20 text-[10px] font-mono mt-3 uppercase tracking-wider max-w-xs mx-auto leading-relaxed">
            Select a generation mode above to synthesize available brandable assets
          </p>
        </div>
      )}

      {/* Loading Grid */}
      {isGenerating && results.length === 0 && (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
          {[...Array(12)].map((_, i) => (
            <div key={i} className="h-14 bg-white/[0.01] border border-white/[0.05] animate-pulse" />
          ))}
        </div>
      )}
    </div>
  )
}
