'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 {
  Globe,
  TrendingUp,
  TrendingDown,
  Minus,
  DollarSign,
  Calendar,
  Building,
  AlertTriangle,
  ExternalLink,
  ChevronLeft,
  Lock,
  ArrowRight,
  Search,
  Check,
  X,
  Loader2,
  BarChart3
} from 'lucide-react'
import Link from 'next/link'
import clsx from 'clsx'

interface TldData {
  tld: string
  type: string | null
  registration_price: number | null
  renewal_price: number | null
  registrar_count: number
  description?: string | null
  introduced?: string | null
  registry?: string | null
}

interface PriceHistory {
  date: string
  price: number
}

interface RegistrarPrice {
  registrar: string
  registration: number
  renewal: number
  transfer: number
}

interface Props {
  tld: string
  initialData: TldData | null
}

export default function TldDetailClient({ tld, initialData }: Props) {
  const { isAuthenticated, checkAuth, subscription } = useStore()
  const [data, setData] = useState<TldData | null>(initialData)
  const [priceHistory, setPriceHistory] = useState<PriceHistory[]>([])
  const [registrars, setRegistrars] = useState<RegistrarPrice[]>([])
  const [loading, setLoading] = useState(!initialData)
  const [checkDomain, setCheckDomain] = useState('')
  const [checking, setChecking] = useState(false)
  const [checkResult, setCheckResult] = useState<{ available: boolean; domain: string } | null>(null)

  const tier = subscription?.tier || 'scout'
  const canSeeRenewal = tier !== 'scout'
  const canSeeHistory = tier === 'tycoon'

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

  useEffect(() => {
    loadTldData()
  }, [tld])

  const loadTldData = async () => {
    setLoading(true)
    try {
      const [tldInfo, prices] = await Promise.all([
        api.getTldInfo(tld),
        api.getTldPrices(tld),
      ])
      
      if (tldInfo) {
        setData(tldInfo)
      }
      
      if (prices) {
        setRegistrars(prices.registrars || [])
        setPriceHistory(prices.history || [])
      }
    } catch (error) {
      console.error('Failed to load TLD data:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleCheckDomain = async () => {
    if (!checkDomain.trim()) return
    setChecking(true)
    try {
      const domain = checkDomain.includes('.') ? checkDomain : `${checkDomain}.${tld}`
      const result = await api.checkDomain(domain)
      setCheckResult({ available: result.is_available, domain })
    } catch (error) {
      console.error('Domain check failed:', error)
    } finally {
      setChecking(false)
    }
  }

  const getRiskLevel = () => {
    if (!data?.registration_price || !data?.renewal_price) return 'unknown'
    const ratio = data.renewal_price / data.registration_price
    if (ratio > 5) return 'high'
    if (ratio > 2) return 'medium'
    return 'low'
  }

  const riskLevel = getRiskLevel()

  return (
    <div className="min-h-screen bg-[#020202] flex flex-col">
      <Header />
      
      <main className="flex-1">
        {/* Hero Section */}
        <section className="relative pt-24 sm:pt-32 pb-12 sm:pb-16 overflow-hidden">
          <div className="absolute inset-0 bg-[linear-gradient(rgba(255,255,255,0.02)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.02)_1px,transparent_1px)] bg-[size:60px_60px]" />
          
          <div className="relative max-w-6xl mx-auto px-4 sm:px-6">
            {/* Breadcrumb */}
            <Link 
              href="/discover" 
              className="inline-flex items-center gap-2 text-sm text-white/50 hover:text-white transition-colors mb-8"
            >
              <ChevronLeft className="w-4 h-4" />
              <span>Back to TLD Intelligence</span>
            </Link>
            
            {/* TLD Header */}
            <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-8 mb-12">
              <div className="flex items-start gap-6">
                <div className="w-20 h-20 bg-accent/10 border border-accent/20 flex items-center justify-center shrink-0">
                  <Globe className="w-10 h-10 text-accent" />
                </div>
                <div>
                  <h1 className="text-4xl sm:text-5xl lg:text-6xl font-display font-bold text-white tracking-tight">
                    .{tld.toUpperCase()}
                  </h1>
                  <p className="text-white/50 text-lg mt-2">
                    {data?.type || 'Domain Extension'} {data?.registry && `• ${data.registry}`}
                  </p>
                  {data?.description && (
                    <p className="text-white/70 mt-4 max-w-xl">{data.description}</p>
                  )}
                </div>
              </div>
              
              {/* Risk Badge */}
              <div className={clsx(
                "px-6 py-4 border",
                riskLevel === 'high' && "bg-red-500/10 border-red-500/30",
                riskLevel === 'medium' && "bg-yellow-500/10 border-yellow-500/30",
                riskLevel === 'low' && "bg-green-500/10 border-green-500/30",
                riskLevel === 'unknown' && "bg-white/5 border-white/10"
              )}>
                <div className="text-[10px] font-mono uppercase tracking-wider text-white/40 mb-1">
                  Renewal Risk
                </div>
                <div className={clsx(
                  "text-2xl font-bold capitalize",
                  riskLevel === 'high' && "text-red-400",
                  riskLevel === 'medium' && "text-yellow-400",
                  riskLevel === 'low' && "text-green-400",
                  riskLevel === 'unknown' && "text-white/50"
                )}>
                  {riskLevel === 'unknown' ? 'N/A' : riskLevel}
                </div>
              </div>
            </div>
            
            {/* Stats Grid */}
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="bg-white/[0.02] border border-white/[0.06] p-6">
                <div className="text-[10px] font-mono uppercase tracking-wider text-white/40 mb-2">
                  Registration
                </div>
                <div className="text-2xl font-bold text-white">
                  {data?.registration_price ? `$${data.registration_price.toFixed(2)}` : '—'}
                </div>
              </div>
              
              <div className="bg-white/[0.02] border border-white/[0.06] p-6 relative">
                <div className="text-[10px] font-mono uppercase tracking-wider text-white/40 mb-2">
                  Renewal
                </div>
                {canSeeRenewal ? (
                  <div className="text-2xl font-bold text-white">
                    {data?.renewal_price ? `$${data.renewal_price.toFixed(2)}` : '—'}
                  </div>
                ) : (
                  <div className="flex items-center gap-2">
                    <Lock className="w-4 h-4 text-white/30" />
                    <span className="text-white/30 text-sm">Trader+</span>
                  </div>
                )}
              </div>
              
              <div className="bg-white/[0.02] border border-white/[0.06] p-6">
                <div className="text-[10px] font-mono uppercase tracking-wider text-white/40 mb-2">
                  Registrars
                </div>
                <div className="text-2xl font-bold text-white">
                  {data?.registrar_count || registrars.length || '—'}
                </div>
              </div>
              
              <div className="bg-white/[0.02] border border-white/[0.06] p-6">
                <div className="text-[10px] font-mono uppercase tracking-wider text-white/40 mb-2">
                  Introduced
                </div>
                <div className="text-2xl font-bold text-white">
                  {data?.introduced || '—'}
                </div>
              </div>
            </div>
          </div>
        </section>
        
        {/* Domain Checker */}
        <section className="py-12 border-y border-white/[0.06]">
          <div className="max-w-6xl mx-auto px-4 sm:px-6">
            <h2 className="text-xl font-bold text-white mb-6">Check .{tld.toUpperCase()} Availability</h2>
            
            <div className="flex gap-4">
              <div className="flex-1 relative">
                <input
                  type="text"
                  value={checkDomain}
                  onChange={(e) => setCheckDomain(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && handleCheckDomain()}
                  placeholder={`yourname.${tld}`}
                  className="w-full bg-white/[0.02] border border-white/[0.08] px-4 py-3 text-white placeholder:text-white/30 focus:outline-none focus:border-accent font-mono"
                />
              </div>
              <button
                onClick={handleCheckDomain}
                disabled={checking}
                className="px-6 py-3 bg-accent text-black font-bold hover:bg-accent/90 transition-colors disabled:opacity-50"
              >
                {checking ? <Loader2 className="w-5 h-5 animate-spin" /> : 'Check'}
              </button>
            </div>
            
            {checkResult && (
              <div className={clsx(
                "mt-4 p-4 border flex items-center gap-4",
                checkResult.available 
                  ? "bg-green-500/10 border-green-500/30" 
                  : "bg-red-500/10 border-red-500/30"
              )}>
                {checkResult.available ? (
                  <>
                    <Check className="w-6 h-6 text-green-400" />
                    <div>
                      <div className="font-bold text-white">{checkResult.domain} is available!</div>
                      <a 
                        href={`https://www.namecheap.com/domains/registration/results/?domain=${checkResult.domain}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-accent text-sm hover:underline inline-flex items-center gap-1"
                      >
                        Register now <ExternalLink className="w-3 h-3" />
                      </a>
                    </div>
                  </>
                ) : (
                  <>
                    <X className="w-6 h-6 text-red-400" />
                    <div className="font-bold text-white">{checkResult.domain} is taken</div>
                  </>
                )}
              </div>
            )}
          </div>
        </section>
        
        {/* Price History Chart */}
        <section className="py-12">
          <div className="max-w-6xl mx-auto px-4 sm:px-6">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold text-white">Price History</h2>
              {!canSeeHistory && (
                <Link 
                  href="/pricing"
                  className="text-sm text-accent hover:underline inline-flex items-center gap-1"
                >
                  Unlock with Tycoon <ArrowRight className="w-3 h-3" />
                </Link>
              )}
            </div>
            
            <div className="bg-white/[0.02] border border-white/[0.06] p-8 min-h-[300px] relative">
              {canSeeHistory ? (
                priceHistory.length > 0 ? (
                  <div className="text-white/50 text-center py-12">
                    <BarChart3 className="w-12 h-12 mx-auto mb-4 text-white/20" />
                    Price chart visualization here
                  </div>
                ) : (
                  <div className="text-white/50 text-center py-12">
                    No historical data available yet
                  </div>
                )
              ) : (
                <div className="absolute inset-0 bg-[#020202]/80 backdrop-blur-sm flex items-center justify-center">
                  <div className="text-center">
                    <Lock className="w-12 h-12 text-white/20 mx-auto mb-4" />
                    <p className="text-white/50 mb-4">Historical data requires Tycoon</p>
                    <Link 
                      href="/pricing"
                      className="px-6 py-2 bg-accent text-black font-bold text-sm hover:bg-accent/90 transition-colors inline-block"
                    >
                      Upgrade to Tycoon
                    </Link>
                  </div>
                </div>
              )}
            </div>
          </div>
        </section>
        
        {/* Registrar Comparison */}
        <section className="py-12 border-t border-white/[0.06]">
          <div className="max-w-6xl mx-auto px-4 sm:px-6">
            <h2 className="text-xl font-bold text-white mb-6">Compare Registrars</h2>
            
            {registrars.length > 0 ? (
              <div className="border border-white/[0.06] overflow-hidden">
                <table className="w-full">
                  <thead>
                    <tr className="bg-white/[0.02] border-b border-white/[0.06]">
                      <th className="text-left p-4 text-[10px] font-mono uppercase tracking-wider text-white/40">
                        Registrar
                      </th>
                      <th className="text-right p-4 text-[10px] font-mono uppercase tracking-wider text-white/40">
                        Registration
                      </th>
                      <th className="text-right p-4 text-[10px] font-mono uppercase tracking-wider text-white/40">
                        Renewal
                      </th>
                      <th className="text-right p-4 text-[10px] font-mono uppercase tracking-wider text-white/40">
                        Transfer
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {registrars.map((reg, i) => (
                      <tr 
                        key={reg.registrar}
                        className={clsx(
                          "border-b border-white/[0.06] hover:bg-white/[0.02] transition-colors",
                          i === 0 && "bg-accent/5"
                        )}
                      >
                        <td className="p-4">
                          <div className="flex items-center gap-3">
                            {i === 0 && (
                              <span className="text-[9px] font-mono uppercase bg-accent/20 text-accent px-2 py-0.5">
                                Best
                              </span>
                            )}
                            <span className="font-medium text-white">{reg.registrar}</span>
                          </div>
                        </td>
                        <td className="p-4 text-right font-mono text-white">
                          ${reg.registration.toFixed(2)}
                        </td>
                        <td className="p-4 text-right font-mono text-white">
                          {canSeeRenewal ? `$${reg.renewal.toFixed(2)}` : (
                            <span className="text-white/30">—</span>
                          )}
                        </td>
                        <td className="p-4 text-right font-mono text-white">
                          ${reg.transfer.toFixed(2)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <div className="bg-white/[0.02] border border-white/[0.06] p-12 text-center">
                <Building className="w-12 h-12 text-white/20 mx-auto mb-4" />
                <p className="text-white/50">No registrar data available</p>
              </div>
            )}
          </div>
        </section>
        
        {/* CTA Section */}
        <section className="py-16 border-t border-white/[0.06]">
          <div className="max-w-4xl mx-auto px-4 sm:px-6 text-center">
            <h2 className="text-3xl font-bold text-white mb-4">
              Track .{tld.toUpperCase()} Prices
            </h2>
            <p className="text-white/60 mb-8 max-w-xl mx-auto">
              Get alerts when .{tld.toUpperCase()} prices change. Monitor domains and never miss a deal.
            </p>
            <Link
              href="/register"
              className="inline-flex items-center gap-2 px-8 py-4 bg-accent text-black font-bold hover:bg-accent/90 transition-colors"
            >
              Enter Terminal <ArrowRight className="w-4 h-4" />
            </Link>
          </div>
        </section>
      </main>
      
      <Footer />
    </div>
  )
}

