'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,
} 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
  const [mode, setMode] = useState<'pattern' | '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(`Found ${res.items.length} domains!`, '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} available from ${res.names.length} AI names!`, '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', 'error')
    } finally {
      setTracking(null)
    }
  }

  const isGenerating = loading || aiLoading

  return (
    <div className="space-y-6">
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* HEADER */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <div className="pb-4 border-b border-white/10">
        <h2 className="text-xl font-bold text-white flex items-center gap-2">
          <Wand2 className="w-5 h-5 text-purple-400" />
          Brandable Forge
        </h2>
        <p className="text-sm text-white/60 mt-1">
          Generate unique, memorable domain names
        </p>
      </div>

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* MODE SELECTOR - BIG CLEAR BUTTONS */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <div className="grid grid-cols-2 gap-3">
        {/* Pattern Mode */}
        <button
          onClick={() => setMode('pattern')}
          className={clsx(
            "p-4 sm:p-5 border-2 transition-all text-left",
            mode === 'pattern'
              ? "border-accent bg-accent/10"
              : "border-white/10 bg-white/[0.02] hover:border-white/20"
          )}
        >
          <div className="flex items-center gap-3 mb-2">
            <div className={clsx(
              "w-10 h-10 flex items-center justify-center",
              mode === 'pattern' ? "bg-accent/20" : "bg-white/5"
            )}>
              <Dices className={clsx("w-5 h-5", mode === 'pattern' ? "text-accent" : "text-white/50")} />
            </div>
            <div>
              <p className={clsx("font-bold", mode === 'pattern' ? "text-accent" : "text-white")}>
                Pattern
              </p>
              <p className={clsx("text-xs", mode === 'pattern' ? "text-accent/70" : "text-white/50")}>
                CVCVC, CVCCV, Human
              </p>
            </div>
          </div>
          <p className="text-xs text-white/40 hidden sm:block">
            Generate random names using proven naming patterns
          </p>
        </button>

        {/* AI Mode */}
        <button
          onClick={() => hasAI && setMode('ai')}
          disabled={!hasAI}
          className={clsx(
            "p-4 sm:p-5 border-2 transition-all text-left relative",
            !hasAI && "opacity-60",
            mode === 'ai'
              ? "border-purple-500 bg-purple-500/10"
              : "border-white/10 bg-white/[0.02] hover:border-white/20"
          )}
        >
          {!hasAI && (
            <div className="absolute top-2 right-2">
              <Lock className="w-4 h-4 text-white/30" />
            </div>
          )}
          <div className="flex items-center gap-3 mb-2">
            <div className={clsx(
              "w-10 h-10 flex items-center justify-center",
              mode === 'ai' ? "bg-purple-500/20" : "bg-white/5"
            )}>
              <Brain className={clsx("w-5 h-5", mode === 'ai' ? "text-purple-400" : "text-white/50")} />
            </div>
            <div>
              <p className={clsx("font-bold", mode === 'ai' ? "text-purple-400" : "text-white")}>
                AI Concept
              </p>
              <p className={clsx("text-xs", mode === 'ai' ? "text-purple-400/70" : "text-white/50")}>
                {hasAI ? 'Describe your brand' : 'Trader+ only'}
              </p>
            </div>
          </div>
          <p className="text-xs text-white/40 hidden sm:block">
            {hasAI ? 'AI generates names based on your concept' : 'Upgrade to unlock AI naming'}
          </p>
        </button>
      </div>

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* PATTERN MODE */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {mode === 'pattern' && (
        <div className="border border-white/10 bg-white/[0.02] p-4 sm:p-5 space-y-5">
          {/* Pattern Selection */}
          <div>
            <p className="text-xs text-white/60 font-mono uppercase tracking-wider mb-3">Choose Pattern</p>
            <div className="grid grid-cols-3 gap-2">
              {PATTERNS.map(p => (
                <button
                  key={p.key}
                  onClick={() => setPattern(p.key)}
                  className={clsx(
                    "p-3 border text-center transition-all",
                    pattern === p.key
                      ? "border-accent bg-accent/10"
                      : "border-white/10 hover:border-white/20"
                  )}
                >
                  <p className={clsx(
                    "text-sm font-bold font-mono",
                    pattern === p.key ? "text-accent" : "text-white"
                  )}>
                    {p.label}
                  </p>
                  <p className="text-[10px] text-white/50 mt-0.5">{p.example}</p>
                </button>
              ))}
            </div>
          </div>

          {/* TLDs */}
          <div>
            <p className="text-xs text-white/60 font-mono uppercase tracking-wider mb-3">Select TLDs</p>
            <div className="flex flex-wrap gap-2">
              {TLDS.map(tld => (
                <button
                  key={tld}
                  onClick={() => setTlds(prev => 
                    prev.includes(tld) ? prev.filter(t => t !== tld) : [...prev, tld]
                  )}
                  className={clsx(
                    "px-3 py-2 text-sm font-mono border transition-all",
                    tlds.includes(tld)
                      ? "border-accent bg-accent/10 text-accent"
                      : "border-white/10 text-white/50 hover:text-white"
                  )}
                >
                  .{tld}
                </button>
              ))}
            </div>
          </div>

          {/* Generate */}
          <button
            onClick={generatePattern}
            disabled={isGenerating || tlds.length === 0}
            className={clsx(
              "w-full py-4 text-sm font-bold uppercase tracking-wider flex items-center justify-center gap-2 transition-all",
              isGenerating || tlds.length === 0
                ? "bg-white/10 text-white/40"
                : "bg-accent text-black hover:bg-white"
            )}
          >
            {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
            Generate {pattern.toUpperCase()} Names
          </button>
        </div>
      )}

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* AI MODE */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {mode === 'ai' && hasAI && (
        <div className="border border-purple-500/30 bg-purple-500/5 p-4 sm:p-5 space-y-5">
          {/* Concept Input */}
          <div>
            <p className="text-xs text-purple-300 font-mono uppercase tracking-wider mb-3">
              Describe Your Brand Concept
            </p>
            <textarea
              value={concept}
              onChange={(e) => setConcept(e.target.value)}
              placeholder="e.g., AI startup for legal documents, crypto wallet for teens, fitness tracking app..."
              rows={3}
              className="w-full px-4 py-3 bg-white/5 border border-purple-500/30 text-white placeholder:text-white/30 outline-none focus:border-purple-400 resize-none font-mono text-sm"
            />
          </div>

          {/* TLDs */}
          <div>
            <p className="text-xs text-purple-300 font-mono uppercase tracking-wider mb-3">Select TLDs</p>
            <div className="flex flex-wrap gap-2">
              {TLDS.map(tld => (
                <button
                  key={tld}
                  onClick={() => setTlds(prev => 
                    prev.includes(tld) ? prev.filter(t => t !== tld) : [...prev, tld]
                  )}
                  className={clsx(
                    "px-3 py-2 text-sm font-mono border transition-all",
                    tlds.includes(tld)
                      ? "border-purple-400 bg-purple-500/20 text-purple-300"
                      : "border-white/10 text-white/50 hover:text-white"
                  )}
                >
                  .{tld}
                </button>
              ))}
            </div>
          </div>

          {/* Generate */}
          <button
            onClick={generateFromConcept}
            disabled={aiLoading || !concept.trim() || tlds.length === 0}
            className={clsx(
              "w-full py-4 text-sm font-bold uppercase tracking-wider flex items-center justify-center gap-2 transition-all",
              aiLoading || !concept.trim() || tlds.length === 0
                ? "bg-white/10 text-white/40"
                : "bg-purple-500 text-white hover:bg-purple-400"
            )}
          >
            {aiLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Brain className="w-4 h-4" />}
            Generate AI Names
          </button>
        </div>
      )}

      {/* AI Upgrade CTA */}
      {mode === 'ai' && !hasAI && (
        <div className="border border-white/10 bg-white/[0.02] p-8 text-center">
          <Lock className="w-10 h-10 text-white/20 mx-auto mb-3" />
          <h3 className="text-lg font-bold text-white mb-2">AI Naming Requires Upgrade</h3>
          <p className="text-sm text-white/50 mb-4 max-w-sm mx-auto">
            Describe your brand and let AI generate unique, brandable domain names for you.
          </p>
          <Link
            href="/pricing"
            className="inline-flex items-center gap-2 px-6 py-3 bg-accent text-black text-sm font-bold uppercase hover:bg-white transition-colors"
          >
            <Sparkles className="w-4 h-4" />
            Upgrade to Trader
          </Link>
        </div>
      )}

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* RESULTS */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {results.length > 0 && (
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <p className="text-sm text-white/70">
              <span className="text-accent font-bold">{results.length}</span> available domains
            </p>
            <div className="flex gap-3">
              <button
                onClick={copyAll}
                className="text-xs font-mono text-white/50 hover:text-accent flex items-center gap-1"
              >
                <Copy className="w-3 h-3" />
                Copy all
              </button>
              <button
                onClick={mode === 'pattern' ? generatePattern : generateFromConcept}
                disabled={isGenerating}
                className="text-xs font-mono text-white/50 hover:text-white flex items-center gap-1"
              >
                <RefreshCw className={clsx("w-3 h-3", isGenerating && "animate-spin")} />
                Refresh
              </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-3 border transition-all group",
                  mode === 'ai'
                    ? "bg-purple-500/5 border-purple-500/20 hover:bg-purple-500/10"
                    : "bg-accent/5 border-accent/20 hover:bg-accent/10"
                )}
              >
                <div className="flex items-center gap-2.5 min-w-0">
                  <span className={clsx(
                    "w-6 h-6 text-[10px] font-bold font-mono flex items-center justify-center shrink-0",
                    mode === 'ai'
                      ? "bg-purple-500/20 text-purple-300"
                      : "bg-accent/20 text-accent"
                  )}>
                    {idx + 1}
                  </span>
                  <button
                    onClick={() => openAnalyze(r.domain)}
                    className={clsx(
                      "text-sm font-mono font-medium text-white truncate",
                      mode === 'ai' ? "group-hover:text-purple-300" : "group-hover:text-accent"
                    )}
                  >
                    {r.domain}
                  </button>
                </div>
                <div className="flex items-center gap-0.5 shrink-0 opacity-60 group-hover:opacity-100">
                  <button onClick={() => copy(r.domain)} className="w-7 h-7 flex items-center justify-center text-white/60 hover:text-white">
                    {copied === r.domain ? <Check className="w-3 h-3 text-accent" /> : <Copy className="w-3 h-3" />}
                  </button>
                  <button onClick={() => track(r.domain)} disabled={tracking === r.domain} className="w-7 h-7 flex items-center justify-center text-white/60 hover:text-white">
                    {tracking === r.domain ? <Loader2 className="w-3 h-3 animate-spin" /> : <Eye className="w-3 h-3" />}
                  </button>
                  <button onClick={() => openAnalyze(r.domain)} className="w-7 h-7 flex items-center justify-center text-white/60 hover:text-accent">
                    <Shield className="w-3 h-3" />
                  </button>
                  <a
                    href={`https://www.namecheap.com/domains/registration/results/?domain=${r.domain}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className={clsx(
                      "h-7 px-2 text-[10px] font-bold flex items-center",
                      mode === 'ai'
                        ? "bg-purple-500 text-white hover:bg-purple-400"
                        : "bg-accent text-black hover:bg-white"
                    )}
                  >
                    Buy
                  </a>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Empty State */}
      {results.length === 0 && !isGenerating && (
        <div className="text-center py-12 border border-dashed border-white/10">
          <Wand2 className="w-10 h-10 text-white/20 mx-auto mb-3" />
          <p className="text-white/50">
            {mode === 'pattern' 
              ? 'Choose a pattern and click Generate' 
              : 'Describe your brand concept'}
          </p>
        </div>
      )}

      {/* Loading State */}
      {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-12 bg-white/5 animate-pulse" />
          ))}
        </div>
      )}
    </div>
  )
}
