'use client'

import { useCallback, useMemo, useState } from 'react'
import clsx from 'clsx'
import Link from 'next/link'
import { 
  Copy, 
  Check, 
  Sparkles, 
  Lock, 
  RefreshCw, 
  Mail, 
  Target, 
  Coins, 
  Info,
  Rocket,
  Users,
  Radio,
  Lightbulb,
  ChevronRight,
} from 'lucide-react'
import { api } from '@/lib/api'
import { useStore } from '@/lib/store'

type VisionPayload = {
  domain: string
  cached: boolean
  model: string
  prompt_version: string
  generated_at: string
  result: {
    business_concept: string
    industry_vertical: string
    buyer_persona: string
    cold_email_subject: string
    cold_email_body: string
    monetization_idea: string
    radio_test_score: number
    reasoning: string
  }
}

async function copyToClipboard(text: string) {
  try {
    await navigator.clipboard.writeText(text)
    return true
  } catch {
    return false
  }
}

// Card component for consistent styling
function VisionCard({ 
  icon: Icon, 
  iconColor,
  title, 
  children,
  copyValue,
  className,
}: {
  icon: typeof Target
  iconColor: string
  title: string
  children: React.ReactNode
  copyValue?: string
  className?: string
}) {
  const [copied, setCopied] = useState(false)

  const handleCopy = async () => {
    if (!copyValue) return
    const ok = await copyToClipboard(copyValue)
    setCopied(ok)
    if (ok) setTimeout(() => setCopied(false), 1200)
  }

  return (
    <div className={clsx("border border-white/[0.06] bg-white/[0.02]", className)}>
      <div className="px-3 py-2.5 flex items-center justify-between border-b border-white/[0.04]">
        <div className="flex items-center gap-2">
          <Icon className={clsx("w-3.5 h-3.5", iconColor)} />
          <span className="text-xs font-bold text-white uppercase tracking-wider">{title}</span>
        </div>
        {copyValue && (
          <button
            onClick={handleCopy}
            className="w-7 h-7 flex items-center justify-center border border-white/[0.08] text-white/30 hover:text-white hover:bg-white/[0.05] transition-colors"
            title="Copy to clipboard"
          >
            {copied ? <Check className="w-3.5 h-3.5 text-accent" /> : <Copy className="w-3.5 h-3.5" />}
          </button>
        )}
      </div>
      <div className="p-3">
        {children}
      </div>
    </div>
  )
}

export function VisionSection({ domain }: { domain: string }) {
  const subscription = useStore((s) => s.subscription)
  const tier = (subscription?.tier || 'scout').toLowerCase()
  const canUse = tier === 'trader' || tier === 'tycoon'

  const [data, setData] = useState<VisionPayload | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const headline = useMemo(() => domain?.trim().toLowerCase() || '', [domain])

  const run = useCallback(async (opts?: { refresh?: boolean }) => {
    setLoading(true)
    setError(null)
    try {
      const res = await api.getVision(headline, Boolean(opts?.refresh))
      setData(res)
    } catch (e) {
      setData(null)
      setError(e instanceof Error ? e.message : String(e))
    } finally {
      setLoading(false)
    }
  }, [headline])

  // Upgrade CTA for Scout users
  if (!canUse) {
    return (
      <div className="border border-white/[0.08] bg-white/[0.02] p-4">
        <div className="flex items-start gap-3">
          <div className="w-10 h-10 flex items-center justify-center border border-white/[0.08] bg-white/[0.02] shrink-0">
            <Lock className="w-5 h-5 text-white/30" />
          </div>
          <div className="min-w-0 flex-1">
            <div className="text-sm font-bold text-white flex items-center gap-2">
              <span className="text-white/60">VISION</span>
              <span className="px-1.5 py-0.5 text-[9px] font-mono uppercase bg-white/[0.08] text-white/50 border border-white/[0.08]">
                Trader+
              </span>
            </div>
            <p className="text-xs text-white/40 mt-1">
              AI-powered business concept, buyer persona, and outreach strategy for this domain.
            </p>
            <div className="mt-3 flex items-center gap-2">
              <Link
                href="/pricing"
                className="inline-flex items-center gap-2 px-3 py-2 bg-accent text-black text-[10px] font-bold uppercase tracking-wider hover:bg-white transition-colors"
              >
                Upgrade to unlock
                <ChevronRight className="w-3.5 h-3.5" />
              </Link>
            </div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-3">
      {/* Controls */}
      <div className="flex items-center justify-between gap-3">
        <div className="text-[10px] font-mono text-white/40">
          <Sparkles className="w-3.5 h-3.5 text-accent inline mr-1.5" />
          Generates business insights via AI
        </div>
        <div className="flex items-center gap-1.5">
          <button
            onClick={() => run({ refresh: false })}
            disabled={loading}
            className={clsx(
              "h-8 px-3 border text-[10px] font-bold uppercase tracking-wider transition-colors flex items-center gap-1.5",
              "border-white/[0.08] text-white/50 hover:text-white hover:bg-white/[0.05]",
              loading && "opacity-60"
            )}
            title="Generate (uses cache if available)"
          >
            {loading ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}
            {data ? 'Regenerate' : 'Generate'}
          </button>
          {data && (
            <button
              onClick={() => run({ refresh: true })}
              disabled={loading}
              className="h-8 w-8 flex items-center justify-center border border-white/[0.08] text-white/40 hover:text-white hover:bg-white/[0.05] transition-colors"
              title="Force refresh"
            >
              <RefreshCw className={clsx("w-3.5 h-3.5", loading && "animate-spin")} />
            </button>
          )}
        </div>
      </div>

      {/* Error */}
      {error && (
        <div className="p-3 border border-rose-500/30 bg-rose-500/10 text-rose-300 text-xs font-mono">
          {error}
        </div>
      )}

      {/* Empty State */}
      {!data && !loading && !error && (
        <div className="p-6 border border-dashed border-white/[0.08] text-center">
          <Sparkles className="w-8 h-8 text-white/10 mx-auto mb-2" />
          <p className="text-xs text-white/30 font-mono">
            Click <span className="text-white/50 font-bold">Generate</span> to create AI insights
          </p>
        </div>
      )}

      {/* Results */}
      {data && (
        <div className="space-y-2">
          {/* Business Concept */}
          <VisionCard 
            icon={Rocket} 
            iconColor="text-accent" 
            title="Business Concept"
            copyValue={data.result.business_concept}
          >
            <p className="text-sm text-white/80 leading-relaxed">{data.result.business_concept}</p>
            <div className="mt-2 flex items-center gap-2">
              <span className="text-[9px] font-mono text-white/30 uppercase">Vertical:</span>
              <span className="text-[10px] font-mono text-white/50 px-1.5 py-0.5 bg-white/[0.05] border border-white/[0.08]">
                {data.result.industry_vertical}
              </span>
            </div>
          </VisionCard>

          {/* Ideal Buyer */}
          <VisionCard 
            icon={Users} 
            iconColor="text-emerald-400" 
            title="Ideal Buyer"
            copyValue={data.result.buyer_persona}
          >
            <p className="text-sm text-white/70">{data.result.buyer_persona}</p>
          </VisionCard>

          {/* Outreach Draft */}
          <VisionCard 
            icon={Mail} 
            iconColor="text-sky-400" 
            title="Outreach Draft"
            copyValue={`Subject: ${data.result.cold_email_subject}\n\n${data.result.cold_email_body}`}
          >
            <div className="space-y-2">
              <div>
                <div className="text-[9px] font-mono text-white/30 uppercase mb-1">Subject</div>
                <div className="text-sm text-white/70">{data.result.cold_email_subject}</div>
              </div>
              <div>
                <div className="text-[9px] font-mono text-white/30 uppercase mb-1">Body</div>
                <div className="text-xs text-white/50 whitespace-pre-wrap leading-relaxed">
                  {data.result.cold_email_body}
                </div>
              </div>
            </div>
          </VisionCard>

          {/* Monetization + Radio Test Row */}
          <div className="grid grid-cols-2 gap-2">
            <VisionCard 
              icon={Coins} 
              iconColor="text-amber-400" 
              title="Monetization"
              copyValue={data.result.monetization_idea}
            >
              <p className="text-xs text-white/60 leading-relaxed">{data.result.monetization_idea}</p>
            </VisionCard>

            <VisionCard 
              icon={Radio} 
              iconColor="text-violet-400" 
              title="Radio Test"
              copyValue={String(data.result.radio_test_score)}
            >
              <div className="flex items-end justify-between">
                <div className="text-3xl font-bold font-mono text-white">{data.result.radio_test_score}</div>
                <div className="text-[9px] font-mono text-white/30 text-right">
                  1–10<br/>higher = better
                </div>
              </div>
            </VisionCard>
          </div>

          {/* Reasoning */}
          <VisionCard 
            icon={Lightbulb} 
            iconColor="text-white/40" 
            title="Why This Domain Has Value"
            copyValue={data.result.reasoning}
          >
            <p className="text-xs text-white/50 leading-relaxed">{data.result.reasoning}</p>
            <div className="mt-3 pt-2 border-t border-white/[0.04] flex items-center justify-between text-[9px] font-mono text-white/20">
              <span>{data.cached ? 'Cached' : 'Fresh'} • {new Date(data.generated_at).toLocaleDateString()}</span>
              <span>{data.model}</span>
            </div>
          </VisionCard>
        </div>
      )}
    </div>
  )
}
