'use client'

import { useEffect, useState } from 'react'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { 
  Search, 
  ShieldAlert, 
  Lock, 
  Zap,
  AlertTriangle,
  BarChart3,
  ArrowUpRight,
  Globe,
  DollarSign,
  Loader2
} from 'lucide-react'
import Link from 'next/link'
import clsx from 'clsx'

interface TldData {
  tld: string
  registration_price: number | null
  renewal_price: number | null
  type: string | null
  registrar_count: number
}

function getRiskLevel(regPrice: number | null, renewPrice: number | null): 'Low' | 'Medium' | 'High' {
  if (!regPrice || !renewPrice) return 'Medium'
  const ratio = renewPrice / regPrice
  if (ratio > 5) return 'High'
  if (ratio > 2) return 'Medium'
  return 'Low'
}

export default function DiscoverPage() {
  const { isAuthenticated, checkAuth, isLoading: authLoading } = useStore()
  const [tlds, setTlds] = useState<TldData[]>([])
  const [loading, setLoading] = useState(true)
  const [searchQuery, setSearchQuery] = useState('')
  const [sortBy, setSortBy] = useState<'popular' | 'price' | 'renewal' | 'risk'>('popular')

  useEffect(() => {
    checkAuth()
    loadTlds()
  }, [checkAuth])

  const loadTlds = async () => {
    setLoading(true)
    try {
      // Load real TLD data from the API
      const response = await api.getTldOverview(100, 0)
      
      // Transform the API response to our format
      const tldList: TldData[] = response.tlds.map((tld: any) => ({
        tld: tld.tld.replace('.', ''),
        registration_price: tld.min_registration_price || tld.avg_registration_price,
        renewal_price: tld.min_renewal_price || tld.avg_renewal_price,
        type: tld.type,
        registrar_count: tld.registrar_count || 1
      }))
      
      setTlds(tldList)
    } catch (error) {
      console.error('Failed to load TLDs:', error)
      // Fallback to basic data if API fails
      setTlds([
        { tld: 'com', registration_price: 12, renewal_price: 14, type: 'gTLD', registrar_count: 25 },
        { tld: 'net', registration_price: 10, renewal_price: 12, type: 'gTLD', registrar_count: 20 },
        { tld: 'org', registration_price: 11, renewal_price: 13, type: 'gTLD', registrar_count: 18 },
        { tld: 'io', registration_price: 35, renewal_price: 45, type: 'ccTLD', registrar_count: 15 },
        { tld: 'ai', registration_price: 65, renewal_price: 85, type: 'ccTLD', registrar_count: 10 },
        { tld: 'co', registration_price: 28, renewal_price: 32, type: 'ccTLD', registrar_count: 12 },
        { tld: 'app', registration_price: 18, renewal_price: 22, type: 'gTLD', registrar_count: 8 },
        { tld: 'dev', registration_price: 16, renewal_price: 20, type: 'gTLD', registrar_count: 8 },
      ])
    } finally {
      setLoading(false)
    }
  }

  const filteredTlds = tlds
    .filter(t => t.tld.toLowerCase().includes(searchQuery.toLowerCase()))
    .sort((a, b) => {
      if (sortBy === 'popular') return b.registrar_count - a.registrar_count
      if (sortBy === 'price') return (a.registration_price || 999) - (b.registration_price || 999)
      if (sortBy === 'renewal') return (a.renewal_price || 999) - (b.renewal_price || 999)
      if (sortBy === 'risk') {
        const riskA = getRiskLevel(a.registration_price, a.renewal_price)
        const riskB = getRiskLevel(b.registration_price, b.renewal_price)
        const order = { 'High': 0, 'Medium': 1, 'Low': 2 }
        return order[riskA] - order[riskB]
      }
      return 0
    })

  // Stats
  const cheapestTld = [...tlds].filter(t => t.registration_price).sort((a, b) => (a.registration_price || 999) - (b.registration_price || 999))[0]
  const mostExpensive = [...tlds].filter(t => t.registration_price).sort((a, b) => (b.registration_price || 0) - (a.registration_price || 0))[0]
  const highRiskTld = [...tlds].find(t => getRiskLevel(t.registration_price, t.renewal_price) === 'High')

  // Gatekeeper Logic
  const isPublicTld = (tld: string) => ['com', 'net', 'org'].includes(tld)

  if (authLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-[#020202]">
        <Loader2 className="w-8 h-8 text-accent animate-spin" />
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-[#020202] text-white relative overflow-x-hidden">
      {/* Background */}
      <div className="fixed inset-0 pointer-events-none z-0">
        <div className="absolute inset-0 bg-[url('/noise.png')] opacity-[0.03] mix-blend-overlay" />
        <div 
          className="absolute inset-0 opacity-[0.02]"
          style={{
            backgroundImage: `linear-gradient(rgba(255,255,255,0.3) 0.5px, transparent 0.5px), linear-gradient(90deg, rgba(255,255,255,0.3) 0.5px, transparent 0.5px)`,
            backgroundSize: '80px 80px',
          }}
        />
      </div>

      <Header />

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* MOBILE HEADER */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <header className="lg:hidden sticky top-14 z-40 bg-[#020202]/95 backdrop-blur-md border-b border-white/[0.08]">
        <div className="px-4 py-3">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
              <span className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">TLD Intel</span>
            </div>
            <div className="flex items-center gap-2 text-[10px] font-mono text-white/40">
              <span>{tlds.length} TLDs</span>
            </div>
          </div>
          
          <div className="grid grid-cols-3 gap-2">
            <div className="bg-white/[0.02] border border-white/[0.08] p-2">
              <div className="text-lg font-bold text-white tabular-nums">{tlds.length}</div>
              <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Total</div>
            </div>
            <div className="bg-accent/[0.05] border border-accent/20 p-2">
              <div className="text-lg font-bold text-accent tabular-nums">
                ${cheapestTld?.registration_price || '—'}
              </div>
              <div className="text-[9px] font-mono text-accent/60 uppercase tracking-wider">Cheapest</div>
            </div>
            <div className="bg-white/[0.02] border border-white/[0.08] p-2">
              <div className="text-lg font-bold text-white tabular-nums">
                ${mostExpensive?.registration_price || '—'}
              </div>
              <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Premium</div>
            </div>
          </div>
        </div>
      </header>

      {/* MOBILE SEARCH & FILTERS */}
      <section className="lg:hidden px-4 py-3 border-b border-white/[0.08]">
        <div className="relative border-2 border-white/[0.08] bg-white/[0.02] mb-3">
          <div className="flex items-center">
            <Search className="w-4 h-4 text-white/30 ml-3" />
            <input
              type="text"
              placeholder="search tlds..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="flex-1 bg-transparent px-3 py-2.5 text-sm font-mono text-white placeholder:text-white/20 outline-none"
            />
          </div>
        </div>

        <div className="flex gap-2 overflow-x-auto pb-1">
          {[
            { id: 'popular' as const, label: 'Popular' },
            { id: 'price' as const, label: 'Price' },
            { id: 'renewal' as const, label: 'Renewal' },
            { id: 'risk' as const, label: 'Risk' },
          ].map((filter) => (
            <button
              key={filter.id}
              onClick={() => setSortBy(filter.id)}
              className={clsx(
                "px-3 py-2 text-[10px] font-mono uppercase tracking-wider border transition-all whitespace-nowrap",
                sortBy === filter.id
                  ? "bg-accent text-black border-accent"
                  : "bg-white/[0.02] border-white/[0.08] text-white/50"
              )}
            >
              {filter.label}
            </button>
          ))}
        </div>
      </section>

      {/* MOBILE TLD LIST */}
      <section className="lg:hidden px-4 py-4 pb-20">
        {!isAuthenticated && (
          <div className="mb-4 p-3 bg-accent/5 border border-accent/20">
            <div className="flex items-center gap-3">
              <Lock className="w-4 h-4 text-accent shrink-0" />
              <div className="flex-1">
                <p className="text-xs font-bold text-white">Unlock Full Data</p>
                <p className="text-[10px] text-white/50">Renewal prices & risk levels</p>
              </div>
              <Link href="/register" className="px-3 py-1.5 bg-accent text-black text-[10px] font-bold uppercase">
                Join
              </Link>
            </div>
          </div>
        )}

        {loading ? (
          <div className="flex items-center justify-center py-20">
            <Loader2 className="w-6 h-6 text-accent animate-spin" />
          </div>
        ) : filteredTlds.length === 0 ? (
          <div className="text-center py-20 text-white/30 font-mono text-sm">No TLDs found</div>
        ) : (
          <div className="space-y-2">
            {filteredTlds.slice(0, 50).map((tld) => {
              const isLocked = !isAuthenticated && !isPublicTld(tld.tld)
              const riskLevel = getRiskLevel(tld.registration_price, tld.renewal_price)
              
              return (
                <Link
                  key={tld.tld}
                  href={`/terminal/intel/${tld.tld}`}
                  className="block p-3 bg-[#0A0A0A] border border-white/[0.08] active:bg-white/[0.03] transition-all"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 bg-white/[0.02] border border-white/[0.06] flex items-center justify-center">
                        <Globe className="w-4 h-4 text-white/40" />
                      </div>
                      <div>
                        <div className="text-sm font-bold text-white font-mono">.{tld.tld}</div>
                        <div className="text-[10px] text-white/30 font-mono uppercase">{tld.type || 'TLD'}</div>
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="text-sm font-bold text-accent font-mono">
                        ${tld.registration_price || '—'}
                      </div>
                      <div className="flex items-center gap-1 justify-end">
                        {isLocked ? (
                          <span className="text-[10px] text-white/20 flex items-center gap-1">
                            <Lock className="w-3 h-3" /> Renew
                          </span>
                        ) : (
                          <span className={clsx(
                            "text-[10px] font-mono",
                            riskLevel === 'High' ? 'text-red-400' : 
                            riskLevel === 'Medium' ? 'text-amber-400' : 'text-white/40'
                          )}>
                            ${tld.renewal_price || '—'}/yr
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                </Link>
              )
            })}
          </div>
        )}
      </section>

      {/* ═══════════════════════════════════════════════════════════════════════ */}
      {/* DESKTOP LAYOUT */}
      {/* ═══════════════════════════════════════════════════════════════════════ */}
      <main className="hidden lg:block relative pt-32 pb-24 px-6">
        <div className="max-w-[1400px] mx-auto">
          
          {/* Header Section */}
          <div className="mb-12 animate-fade-in">
            <div className="flex justify-between items-end gap-8 border-b border-white/[0.08] pb-10">
              <div>
                <span className="text-accent font-mono text-xs uppercase tracking-[0.2em] mb-4 block flex items-center gap-2">
                  <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
                  TLD Intelligence
                </span>
                <h1 className="font-display text-[5rem] leading-[0.9] tracking-[-0.03em] text-white">
                  Discover TLDs.
                </h1>
                <p className="mt-6 text-lg text-white/50 max-w-2xl font-light leading-relaxed">
                  Compare registration and renewal prices across {tlds.length}+ top-level domains.
                  <span className="block mt-2 text-white/80">Find the best value for your next domain.</span>
                </p>
              </div>
              <div className="grid grid-cols-3 gap-8 text-right">
                <div>
                  <div className="text-3xl font-display text-white mb-1">{tlds.length}</div>
                  <div className="text-[10px] uppercase tracking-widest text-white/30 font-mono">TLDs</div>
                </div>
                <div>
                  <div className="text-3xl font-display text-accent mb-1">${cheapestTld?.registration_price || '—'}</div>
                  <div className="text-[10px] uppercase tracking-widest text-accent/60 font-mono">Cheapest</div>
                </div>
                <div>
                  <div className="text-3xl font-display text-white mb-1">${mostExpensive?.registration_price || '—'}</div>
                  <div className="text-[10px] uppercase tracking-widest text-white/30 font-mono">Premium</div>
                </div>
              </div>
            </div>
          </div>

          {/* Stats Cards */}
          {cheapestTld && mostExpensive && highRiskTld && (
            <div className="grid grid-cols-3 gap-4 mb-10">
              <div className="bg-[#050505] border border-white/10 p-6">
                <div className="flex items-center gap-2 mb-3">
                  <div className="w-8 h-8 bg-accent/10 border border-accent/20 flex items-center justify-center">
                    <DollarSign className="w-4 h-4 text-accent" />
                  </div>
                  <span className="text-xs font-mono text-white/40 uppercase">Best Value</span>
                </div>
                <div className="text-2xl font-display text-white">.{cheapestTld.tld.toUpperCase()}</div>
                <div className="text-sm text-accent font-mono">${cheapestTld.registration_price}/yr</div>
              </div>
              <div className="bg-[#050505] border border-white/10 p-6">
                <div className="flex items-center gap-2 mb-3">
                  <div className="w-8 h-8 bg-blue-500/10 border border-blue-500/20 flex items-center justify-center">
                    <BarChart3 className="w-4 h-4 text-blue-400" />
                  </div>
                  <span className="text-xs font-mono text-white/40 uppercase">Most Tracked</span>
                </div>
                <div className="text-2xl font-display text-white">.COM</div>
                <div className="text-sm text-blue-400 font-mono">Industry Standard</div>
              </div>
              <div className="bg-[#050505] border border-white/10 p-6">
                <div className="flex items-center gap-2 mb-3">
                  <div className="w-8 h-8 bg-red-500/10 border border-red-500/20 flex items-center justify-center">
                    <AlertTriangle className="w-4 h-4 text-red-400" />
                  </div>
                  <span className="text-xs font-mono text-white/40 uppercase">Watch Renewal</span>
                </div>
                <div className="text-2xl font-display text-white">.{highRiskTld.tld.toUpperCase()}</div>
                <div className="text-sm text-red-400 font-mono">High renewal cost</div>
              </div>
            </div>
          )}

          {/* Login Banner */}
          {!isAuthenticated && (
            <div className="mb-8 p-1 border border-accent/20 bg-accent/5 max-w-3xl">
              <div className="bg-[#050505] p-6 flex items-center justify-between gap-6">
                <div className="flex items-center gap-4">
                  <div className="w-10 h-10 bg-accent/10 border border-accent/20 flex items-center justify-center text-accent">
                    <Lock className="w-5 h-5" />
                  </div>
                  <div>
                    <p className="text-base font-bold text-white mb-0.5">Unlock Full Intelligence</p>
                    <p className="text-sm font-mono text-white/50">See renewal prices and risk levels for all TLDs.</p>
                  </div>
                </div>
                <Link
                  href="/register"
                  className="shrink-0 px-6 py-3 bg-accent text-black text-xs font-bold uppercase tracking-widest hover:bg-white transition-all"
                >
                  Sign Up Free
                </Link>
              </div>
            </div>
          )}

          {/* Search & Filters Bar */}
          <div className="mb-6 sticky top-20 z-30 backdrop-blur-xl bg-[#020202]/90 border-y border-white/[0.08] py-4 -mx-6 px-6">
            <div className="flex gap-4 justify-between items-center">
              <div className="relative w-[400px] group">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40 group-focus-within:text-accent transition-colors" />
                <input
                  type="text"
                  placeholder="Search TLDs..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-12 pr-4 py-3 bg-[#0A0A0A] border border-white/10 text-white placeholder:text-white/20 font-mono text-sm focus:outline-none focus:border-accent transition-all"
                />
              </div>
              
              <div className="flex gap-2">
                {[
                  { id: 'popular' as const, label: 'Popular' },
                  { id: 'price' as const, label: 'Price' },
                  { id: 'renewal' as const, label: 'Renewal' },
                  { id: 'risk' as const, label: 'Risk' },
                ].map((filter) => (
                  <button
                    key={filter.id}
                    onClick={() => setSortBy(filter.id)}
                    className={clsx(
                      "px-5 py-3 text-xs font-bold uppercase tracking-widest transition-all border",
                      sortBy === filter.id
                        ? "bg-white/10 text-white border-accent"
                        : "bg-[#0A0A0A] border-white/10 text-white/40 hover:text-white"
                    )}
                  >
                    {filter.label}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Desktop Table */}
          <div className="border border-white/[0.08] bg-[#050505]">
            {/* Table Header */}
            <div className="grid grid-cols-[1fr_120px_120px_100px_80px] gap-4 px-6 py-4 bg-[#0A0A0A] border-b border-white/[0.08] text-[10px] font-mono text-white/40 uppercase tracking-wider">
              <div>Extension</div>
              <div className="text-right">Registration</div>
              <div className="text-right">Renewal</div>
              <div className="text-center">Risk</div>
              <div></div>
            </div>

            {/* Table Body */}
            {loading ? (
              <div className="flex items-center justify-center py-20">
                <Loader2 className="w-6 h-6 text-accent animate-spin" />
              </div>
            ) : filteredTlds.length === 0 ? (
              <div className="text-center py-20 text-white/30 font-mono">No TLDs found</div>
            ) : (
              <div>
                {filteredTlds.map((tld) => {
                  const isLocked = !isAuthenticated && !isPublicTld(tld.tld)
                  const riskLevel = getRiskLevel(tld.registration_price, tld.renewal_price)
                  
                  return (
                    <Link
                      key={tld.tld}
                      href={`/terminal/intel/${tld.tld}`}
                      className="grid grid-cols-[1fr_120px_120px_100px_80px] gap-4 items-center px-6 py-4 border-b border-white/[0.03] hover:bg-white/[0.02] transition-all group"
                    >
                      <div className="flex items-center gap-3">
                        <span className="font-mono text-xl text-white group-hover:text-accent transition-colors">.{tld.tld}</span>
                        <span className="text-[10px] text-white/30 font-mono uppercase">{tld.type}</span>
                      </div>
                      <div className="text-right font-mono text-base text-accent">
                        ${tld.registration_price || '—'}
                      </div>
                      <div className="text-right">
                        {isLocked ? (
                          <span className="text-white/20 flex items-center gap-1 justify-end">
                            <Lock className="w-3 h-3" />
                            <span className="blur-[3px]">$XX</span>
                          </span>
                        ) : (
                          <span className={clsx(
                            "font-mono text-base",
                            riskLevel === 'High' ? 'text-red-400' : 'text-white/60'
                          )}>
                            ${tld.renewal_price || '—'}
                          </span>
                        )}
                      </div>
                      <div className="flex justify-center">
                        {isLocked ? (
                          <span className="text-[10px] text-white/20 blur-[2px]">---</span>
                        ) : (
                          <span className={clsx(
                            "text-[10px] font-bold uppercase tracking-widest px-2 py-1 border",
                            riskLevel === 'Low' ? "border-accent/20 text-accent bg-accent/5" :
                            riskLevel === 'Medium' ? "border-amber-500/20 text-amber-500 bg-amber-500/5" :
                            "border-red-500/20 text-red-500 bg-red-500/5"
                          )}>
                            {riskLevel}
                          </span>
                        )}
                      </div>
                      <div className="flex justify-end">
                        <div className="w-8 h-8 border border-white/10 flex items-center justify-center text-white/30 group-hover:bg-white group-hover:text-black transition-all">
                          <ArrowUpRight className="w-4 h-4" />
                        </div>
                      </div>
                    </Link>
                  )
                })}
              </div>
            )}
          </div>

          {/* Stats Footer */}
          {!loading && (
            <div className="mt-4 flex justify-between text-[10px] font-mono text-white/30 uppercase tracking-widest">
              <span>Data updated daily</span>
              <span>TLDs: {filteredTlds.length}</span>
            </div>
          )}

          {/* Bottom CTA */}
          {!isAuthenticated && (
            <div className="mt-16 p-px bg-gradient-to-r from-accent/20 via-white/5 to-accent/20 max-w-3xl">
              <div className="bg-[#080808] p-10 text-left">
                <div className="inline-flex items-center justify-center w-10 h-10 border border-accent/20 bg-accent/5 text-accent mb-4">
                  <ShieldAlert className="w-5 h-5" />
                </div>
                <h3 className="text-xl font-display text-white mb-2">Avoid Hidden Costs.</h3>
                <p className="text-white/50 mb-6 max-w-md text-sm">
                  Some TLDs have renewal prices 5-10x higher than registration. 
                  Unlock full pricing data to make informed decisions.
                </p>
                <Link
                  href="/pricing"
                  className="inline-flex items-center gap-2 px-6 py-3 bg-accent text-black text-xs font-bold uppercase tracking-widest hover:bg-white transition-all"
                >
                  Unlock Intel <Zap className="w-4 h-4" />
                </Link>
              </div>
            </div>
          )}
        </div>
      </main>

      <Footer />
    </div>
  )
}
