'use client'

import { useCallback, useEffect, useMemo, useState } from 'react'
import clsx from 'clsx'
import { 
  X, 
  RefreshCw, 
  Copy, 
  ExternalLink, 
  Shield, 
  TrendingUp, 
  AlertTriangle, 
  DollarSign,
  Check,
  Zap,
  Globe,
  Calendar,
  Link2,
  Radio,
  Eye,
  ChevronDown,
  ChevronUp,
  CheckCircle2,
  XCircle,
} from 'lucide-react'
import { api } from '@/lib/api'
import { useAnalyzePanelStore } from '@/lib/analyze-store'
import type { AnalyzeResponse, AnalyzeSection, AnalyzeItem } from '@/components/analyze/types'

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

function getStatusColor(status: string) {
  switch (status) {
    case 'pass':
      return { bg: 'bg-accent/20', text: 'text-accent', border: 'border-accent/40', icon: CheckCircle2 }
    case 'warn':
      return { bg: 'bg-amber-400/20', text: 'text-amber-300', border: 'border-amber-400/40', icon: AlertTriangle }
    case 'fail':
      return { bg: 'bg-red-500/20', text: 'text-red-400', border: 'border-red-500/40', icon: XCircle }
    default:
      return { bg: 'bg-white/10', text: 'text-white/50', border: 'border-white/20', icon: null }
  }
}

function getSectionIcon(key: string) {
  switch (key) {
    case 'authority':
      return Shield
    case 'market':
      return TrendingUp
    case 'risk':
      return AlertTriangle
    case 'value':
      return DollarSign
    default:
      return Globe
  }
}

function getSectionColor(key: string) {
  switch (key) {
    case 'authority':
      return { text: 'text-blue-400', bg: 'bg-blue-500/10', border: 'border-blue-500/30' }
    case 'market':
      return { text: 'text-emerald-400', bg: 'bg-emerald-500/10', border: 'border-emerald-500/30' }
    case 'risk':
      return { text: 'text-amber-400', bg: 'bg-amber-500/10', border: 'border-amber-500/30' }
    case 'value':
      return { text: 'text-violet-400', bg: 'bg-violet-500/10', border: 'border-violet-500/30' }
    default:
      return { text: 'text-white/60', bg: 'bg-white/5', border: 'border-white/20' }
  }
}

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

function formatValue(value: unknown): string {
  if (value === null || value === undefined) return '—'
  if (typeof value === 'string') return value
  if (typeof value === 'number') return String(value)
  if (typeof value === 'boolean') return value ? 'Yes' : 'No'
  if (Array.isArray(value)) return `${value.length} items`
  return 'Details'
}

function isMatrix(item: AnalyzeItem) {
  return item.key === 'tld_matrix' && Array.isArray(item.value)
}

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

export function AnalyzePanel() {
  const { 
    isOpen, 
    domain, 
    close, 
    fastMode, 
    setFastMode, 
    sectionVisibility, 
    setSectionVisibility 
  } = useAnalyzePanelStore()

  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [data, setData] = useState<AnalyzeResponse | null>(null)
  const [copied, setCopied] = useState(false)
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
    authority: true,
    market: true,
    risk: true,
    value: true
  })

  const refresh = useCallback(async () => {
    if (!domain) return
    setLoading(true)
    setError(null)
    try {
      const res = await api.analyzeDomain(domain, { fast: fastMode, refresh: true })
      setData(res)
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e))
      setData(null)
    } finally {
      setLoading(false)
    }
  }, [domain, fastMode])

  useEffect(() => {
    if (!isOpen || !domain) return
    let cancelled = false
    const run = async () => {
      setLoading(true)
      setError(null)
      try {
        const res = await api.analyzeDomain(domain, { fast: fastMode, refresh: false })
        if (!cancelled) setData(res)
      } catch (e) {
        if (!cancelled) {
          setError(e instanceof Error ? e.message : String(e))
          setData(null)
        }
      } finally {
        if (!cancelled) setLoading(false)
      }
    }
    run()
    return () => { cancelled = true }
  }, [isOpen, domain, fastMode])

  // ESC to close
  useEffect(() => {
    if (!isOpen) return
    const onKey = (ev: KeyboardEvent) => {
      if (ev.key === 'Escape') close()
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [isOpen, close])

  const toggleSection = useCallback((key: string) => {
    setExpandedSections(prev => ({ ...prev, [key]: !prev[key] }))
  }, [])

  const visibleSections = useMemo(() => {
    const sections = data?.sections || []
    const order = ['authority', 'market', 'risk', 'value']
    return [...sections]
      .sort((a, b) => order.indexOf(a.key) - order.indexOf(b.key))
      .filter((s) => sectionVisibility[s.key] !== false)
  }, [data, sectionVisibility])

  // Calculate overall score
  const overallScore = useMemo(() => {
    if (!data?.sections) return null
    let pass = 0, warn = 0, fail = 0
    data.sections.forEach(s => {
      s.items.forEach(item => {
        if (item.status === 'pass') pass++
        else if (item.status === 'warn') warn++
        else if (item.status === 'fail') fail++
      })
    })
    const total = pass + warn + fail
    if (total === 0) return null
    const score = Math.round((pass * 100 + warn * 50) / total)
    return { score, pass, warn, fail, total }
  }, [data])

  const headerDomain = data?.domain || domain || ''

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 z-[200]">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/85 backdrop-blur-md" onClick={close} />

      {/* Panel - WIDER & MORE READABLE */}
      <div className="absolute right-0 top-0 bottom-0 w-full sm:w-[600px] lg:w-[680px] bg-[#0A0A0A] border-l border-white/10 flex flex-col overflow-hidden shadow-2xl">
        
        {/* Header */}
        <div className="shrink-0 border-b border-white/10 bg-[#050505]">
          {/* Top Bar */}
          <div className="px-6 py-5 flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 bg-accent/15 border border-accent/30 flex items-center justify-center">
                <Shield className="w-6 h-6 text-accent" />
              </div>
              <div>
                <div className="text-xs font-mono text-accent uppercase tracking-widest mb-1">Domain Analysis</div>
                <div className="text-xl font-bold text-white font-mono truncate max-w-[300px]">
                  {headerDomain}
                </div>
              </div>
            </div>
            
            <div className="flex items-center gap-2">
              <button
                onClick={async () => {
                  const ok = await copyToClipboard(headerDomain)
                  setCopied(ok)
                  setTimeout(() => setCopied(false), 1500)
                }}
                className={clsx(
                  "w-10 h-10 flex items-center justify-center border transition-all",
                  copied ? "border-accent bg-accent/20 text-accent" : "border-white/20 text-white/50 hover:text-white hover:bg-white/10"
                )}
              >
                {copied ? <Check className="w-5 h-5" /> : <Copy className="w-5 h-5" />}
              </button>
              <a
                href={`https://${encodeURIComponent(headerDomain)}`}
                target="_blank"
                rel="noopener noreferrer"
                className="w-10 h-10 flex items-center justify-center border border-white/20 text-white/50 hover:text-white hover:bg-white/10 transition-colors"
              >
                <ExternalLink className="w-5 h-5" />
              </a>
              <button
                onClick={refresh}
                disabled={loading}
                className="w-10 h-10 flex items-center justify-center border border-white/20 text-white/50 hover:text-white hover:bg-white/10 transition-colors disabled:opacity-50"
              >
                <RefreshCw className={clsx('w-5 h-5', loading && 'animate-spin')} />
              </button>
              <button 
                onClick={close} 
                className="w-10 h-10 flex items-center justify-center border border-white/20 text-white/50 hover:text-white hover:bg-white/10 transition-colors ml-2"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
          </div>

          {/* Score Bar - LARGER */}
          {overallScore && !loading && (
            <div className="px-6 pb-5">
              <div className="flex items-center gap-4 p-4 bg-white/[0.03] border border-white/10">
                <div className={clsx(
                  "text-4xl font-bold font-mono",
                  overallScore.score >= 70 ? "text-accent" : overallScore.score >= 40 ? "text-amber-400" : "text-red-400"
                )}>
                  {overallScore.score}
                </div>
                <div className="flex-1">
                  <div className="text-xs font-mono text-white/50 uppercase tracking-wider mb-2">Overall Score</div>
                  <div className="h-3 bg-white/10 overflow-hidden flex">
                    <div 
                      className="h-full bg-accent transition-all" 
                      style={{ width: `${(overallScore.pass / overallScore.total) * 100}%` }} 
                    />
                    <div 
                      className="h-full bg-amber-400 transition-all" 
                      style={{ width: `${(overallScore.warn / overallScore.total) * 100}%` }} 
                    />
                    <div 
                      className="h-full bg-red-500 transition-all" 
                      style={{ width: `${(overallScore.fail / overallScore.total) * 100}%` }} 
                    />
                  </div>
                </div>
                <div className="flex flex-col gap-1 text-sm font-mono">
                  <span className="text-accent flex items-center gap-2"><CheckCircle2 className="w-4 h-4" /> {overallScore.pass}</span>
                  <span className="text-amber-400 flex items-center gap-2"><AlertTriangle className="w-4 h-4" /> {overallScore.warn}</span>
                  <span className="text-red-400 flex items-center gap-2"><XCircle className="w-4 h-4" /> {overallScore.fail}</span>
                </div>
              </div>
            </div>
          )}

          {/* Mode Toggle */}
          <div className="px-6 pb-4 flex items-center gap-3">
            <button
              onClick={() => setFastMode(!fastMode)}
              className={clsx(
                "flex items-center gap-2 px-4 py-2 text-sm font-bold uppercase tracking-wider border transition-all",
                fastMode 
                  ? "border-accent/40 bg-accent/15 text-accent" 
                  : "border-white/20 text-white/50 hover:text-white hover:bg-white/10"
              )}
            >
              <Zap className="w-4 h-4" />
              Fast Mode
            </button>
            {data?.cached && (
              <span className="text-sm font-mono text-white/40 px-3 py-2 border border-white/20 bg-white/5">
                ⚡ Cached
              </span>
            )}
          </div>
        </div>

        {/* Body - BETTER SPACING */}
        <div className="flex-1 overflow-y-auto">
          {loading ? (
            <div className="flex items-center justify-center py-24">
              <div className="text-center">
                <RefreshCw className="w-10 h-10 text-accent animate-spin mx-auto mb-4" />
                <div className="text-base font-mono text-white/50">Analyzing domain...</div>
              </div>
            </div>
          ) : error ? (
            <div className="p-6">
              <div className="border border-red-500/30 bg-red-500/10 p-6">
                <div className="text-lg font-bold text-red-400 mb-2">Analysis Failed</div>
                <div className="text-sm font-mono text-white/60">{error}</div>
              </div>
            </div>
          ) : !data ? (
            <div className="flex items-center justify-center py-24">
              <div className="text-base font-mono text-white/40">No data available</div>
            </div>
          ) : (
            <div className="p-6 space-y-4">
              {visibleSections.map((section) => {
                const SectionIcon = getSectionIcon(section.key)
                const sectionStyle = getSectionColor(section.key)
                const isExpanded = expandedSections[section.key] !== false

                return (
                  <div key={section.key} className={clsx("border overflow-hidden", sectionStyle.border, "bg-[#050505]")}>
                    {/* Section Header - LARGER */}
                    <button
                      onClick={() => toggleSection(section.key)}
                      className={clsx(
                        "w-full px-5 py-4 flex items-center justify-between transition-colors",
                        sectionStyle.bg, "hover:brightness-110"
                      )}
                    >
                      <div className="flex items-center gap-3">
                        <SectionIcon className={clsx("w-5 h-5", sectionStyle.text)} />
                        <span className={clsx("text-sm font-bold uppercase tracking-wider", sectionStyle.text)}>
                          {section.title}
                        </span>
                        <span className="text-sm font-mono text-white/40 ml-2">
                          {section.items.length} checks
                        </span>
                      </div>
                      {isExpanded ? (
                        <ChevronUp className="w-5 h-5 text-white/40" />
                      ) : (
                        <ChevronDown className="w-5 h-5 text-white/40" />
                      )}
                    </button>

                    {/* Section Items - BETTER CONTRAST */}
                    {isExpanded && (
                      <div className="border-t border-white/10">
                        {section.items.map((item) => {
                          const statusStyle = getStatusColor(item.status)
                          const StatusIcon = statusStyle.icon

                          return (
                            <div 
                              key={item.key} 
                              className="px-5 py-4 border-b border-white/[0.06] last:border-0 hover:bg-white/[0.03] transition-colors"
                            >
                              <div className="flex items-start gap-4">
                                {/* Status Indicator - LARGER */}
                                <div className={clsx(
                                  "w-10 h-10 flex items-center justify-center shrink-0",
                                  statusStyle.bg, statusStyle.border, "border"
                                )}>
                                  {StatusIcon && <StatusIcon className={clsx("w-5 h-5", statusStyle.text)} />}
                                </div>

                                {/* Content - BETTER READABILITY */}
                                <div className="flex-1 min-w-0">
                                  <div className="flex items-center justify-between gap-4 mb-2">
                                    <span className="text-base font-medium text-white">
                                      {item.label}
                                    </span>
                                    <span className="text-xs font-mono text-white/40 uppercase tracking-wider">
                                      {item.source}
                                    </span>
                                  </div>
                                  
                                  {/* Value - LARGER TEXT */}
                                  <div>
                                    {isMatrix(item) ? (
                                      <div className="grid grid-cols-4 gap-2">
                                        {(item.value as any[]).slice(0, 12).map((row: any) => (
                                          <div
                                            key={String(row.domain)}
                                            className={clsx(
                                              "px-3 py-2 text-sm font-mono flex items-center justify-between border",
                                              row.status === 'available'
                                                ? "border-accent/30 bg-accent/10 text-accent"
                                                : "border-white/10 bg-white/[0.03] text-white/50"
                                            )}
                                          >
                                            <span className="truncate">{String(row.domain)}</span>
                                            {row.status === 'available' && <Check className="w-4 h-4 shrink-0 ml-2" />}
                                          </div>
                                        ))}
                                      </div>
                                    ) : (
                                      <div className={clsx(
                                        "text-base font-mono",
                                        item.status === 'pass' ? "text-white/80" : 
                                        item.status === 'warn' ? "text-amber-300" :
                                        item.status === 'fail' ? "text-red-300" : "text-white/50"
                                      )}>
                                        {formatValue(item.value)}
                                      </div>
                                    )}
                                  </div>

                                  {/* Details Toggle */}
                                  {item.details && Object.keys(item.details).length > 0 && (
                                    <details className="mt-3">
                                      <summary className="text-sm font-mono text-white/40 cursor-pointer hover:text-white/60 select-none">
                                        View raw details
                                      </summary>
                                      <pre className="mt-2 text-xs font-mono text-white/50 bg-black/50 border border-white/10 p-4 overflow-x-auto">
                                        {JSON.stringify(item.details, null, 2)}
                                      </pre>
                                    </details>
                                  )}
                                </div>
                              </div>
                            </div>
                          )
                        })}
                      </div>
                    )}
                  </div>
                )
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
