'use client'

import { useEffect, useState } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { CommandCenterLayout } from '@/components/CommandCenterLayout'
import { PremiumTable, Badge, StatCard, PageContainer, SectionHeader } from '@/components/PremiumTable'
import {
  Search,
  TrendingUp,
  TrendingDown,
  Minus,
  ChevronRight,
  Globe,
  ArrowUpDown,
  DollarSign,
  BarChart3,
  RefreshCw,
  X,
  AlertTriangle,
  Shield,
  Zap,
  Cpu,
  MapPin,
  Coins,
  Crown,
  Info,
} from 'lucide-react'
import clsx from 'clsx'

interface TLDData {
  tld: string
  min_price: number
  avg_price: number
  max_price: number
  min_renewal_price: number
  avg_renewal_price: number
  cheapest_registrar?: string
  cheapest_registrar_url?: string
  price_change_7d: number
  price_change_1y: number
  price_change_3y: number
  risk_level: 'low' | 'medium' | 'high'
  risk_reason: string
  popularity_rank?: number
  type?: string // generic, ccTLD, new
}

// Category definitions for filtering
const CATEGORIES = {
  all: { label: 'All', icon: Globe, filter: () => true },
  tech: { label: 'Tech', icon: Cpu, filter: (tld: TLDData) => ['ai', 'io', 'app', 'dev', 'tech', 'code', 'cloud', 'data', 'api', 'software'].includes(tld.tld) },
  geo: { label: 'Geo', icon: MapPin, filter: (tld: TLDData) => ['ch', 'de', 'uk', 'us', 'fr', 'it', 'es', 'nl', 'at', 'eu', 'co', 'ca', 'au', 'nz', 'jp', 'cn', 'in', 'br', 'mx', 'nyc', 'london', 'paris', 'berlin', 'tokyo', 'swiss'].includes(tld.tld) },
  budget: { label: 'Budget', icon: Coins, filter: (tld: TLDData) => tld.min_price < 5 },
  premium: { label: 'Premium', icon: Crown, filter: (tld: TLDData) => tld.min_price >= 50 },
}

type CategoryKey = keyof typeof CATEGORIES

// Risk level now comes from backend, but keep helper for UI
function getRiskInfo(tld: TLDData): { level: 'low' | 'medium' | 'high', reason: string } {
  return {
    level: tld.risk_level || 'low',
    reason: tld.risk_reason || 'Stable'
  }
}

// Sparkline component for mini trend visualization
function Sparkline({ trend, className }: { trend: number, className?: string }) {
  const isPositive = trend > 0
  const isNeutral = trend === 0
  
  return (
    <div className={clsx("flex items-center gap-1", className)}>
      <svg width="40" height="16" viewBox="0 0 40 16" className="overflow-visible">
        {isNeutral ? (
          <line x1="0" y1="8" x2="40" y2="8" stroke="currentColor" className="text-foreground-muted" strokeWidth="1.5" />
        ) : isPositive ? (
          <polyline
            points="0,14 10,12 20,10 30,6 40,2"
            fill="none"
            stroke="currentColor"
            className="text-orange-400"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        ) : (
          <polyline
            points="0,2 10,4 20,8 30,12 40,14"
            fill="none"
            stroke="currentColor"
            className="text-accent"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        )}
      </svg>
    </div>
  )
}

export default function TLDPricingPage() {
  const { subscription } = useStore()
  
  const [tldData, setTldData] = useState<TLDData[]>([])
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const [sortBy, setSortBy] = useState<'popularity' | 'price_asc' | 'price_desc' | 'change' | 'risk'>('popularity')
  const [category, setCategory] = useState<CategoryKey>('all')
  const [page, setPage] = useState(0)
  const [total, setTotal] = useState(0)
  const [hoveredTld, setHoveredTld] = useState<string | null>(null)

  useEffect(() => {
    loadTLDData()
  }, [page, sortBy])

  const loadTLDData = async () => {
    setLoading(true)
    try {
      const response = await api.getTldOverview(
        50,
        page * 50,
        sortBy === 'risk' ? 'popularity' : sortBy === 'change' ? 'popularity' : sortBy,
      )
      // Map API response to component interface
      const mapped: TLDData[] = (response.tlds || []).map((tld) => ({
        tld: tld.tld,
        min_price: tld.min_registration_price,
        avg_price: tld.avg_registration_price,
        max_price: tld.max_registration_price,
        min_renewal_price: tld.min_renewal_price,
        avg_renewal_price: tld.avg_renewal_price,
        price_change_7d: tld.price_change_7d,
        price_change_1y: tld.price_change_1y,
        price_change_3y: tld.price_change_3y,
        risk_level: tld.risk_level,
        risk_reason: tld.risk_reason,
        popularity_rank: tld.popularity_rank,
        type: tld.type,
      }))
      setTldData(mapped)
      setTotal(response.total || 0)
    } catch (error) {
      console.error('Failed to load TLD data:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleRefresh = async () => {
    setRefreshing(true)
    await loadTLDData()
    setRefreshing(false)
  }

  // Apply category and search filters
  const filteredData = tldData
    .filter(tld => CATEGORIES[category].filter(tld))
    .filter(tld => tld.tld.toLowerCase().includes(searchQuery.toLowerCase()))
  
  // Sort by risk if selected
  const sortedData = sortBy === 'risk'
    ? [...filteredData].sort((a, b) => {
        const riskOrder = { high: 0, medium: 1, low: 2 }
        return riskOrder[getRiskInfo(a).level] - riskOrder[getRiskInfo(b).level]
      })
    : filteredData

  const getTrendIcon = (change: number | undefined) => {
    if (!change || change === 0) return <Minus className="w-4 h-4 text-foreground-muted" />
    if (change > 0) return <TrendingUp className="w-4 h-4 text-orange-400" />
    return <TrendingDown className="w-4 h-4 text-accent" />
  }

  // Calculate stats
  const lowestPrice = tldData.length > 0 
    ? tldData.reduce((min, tld) => Math.min(min, tld.min_price), Infinity) 
    : 0.99
  const hottestTld = tldData.find(tld => (tld.price_change_7d || 0) > 5)?.tld || 'ai'
  const trapCount = tldData.filter(tld => tld.risk_level === 'high' || tld.risk_level === 'medium').length

  // Dynamic subtitle
  const getSubtitle = () => {
    if (loading && total === 0) return 'Loading TLD pricing data...'
    if (total === 0) return 'No TLD data available'
    return `Tracking ${total.toLocaleString()} TLDs • Updated daily`
  }

  const getRiskBadge = (tld: TLDData) => {
    const { level, reason } = getRiskInfo(tld)
    return (
      <span className={clsx(
        "inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium",
        level === 'high' && "bg-red-500/10 text-red-400",
        level === 'medium' && "bg-amber-500/10 text-amber-400",
        level === 'low' && "bg-accent/10 text-accent"
      )}>
        <span className={clsx(
          "w-2.5 h-2.5 rounded-full",
          level === 'high' && "bg-red-400",
          level === 'medium' && "bg-amber-400",
          level === 'low' && "bg-accent"
        )} />
        <span className="hidden sm:inline ml-1">{reason}</span>
      </span>
    )
  }

  const getRenewalTrap = (tld: TLDData) => {
    const ratio = tld.min_renewal_price / tld.min_price
    if (ratio > 2) {
      return (
        <span className="inline-flex items-center gap-1 text-amber-400" title={`Renewal is ${ratio.toFixed(1)}x the registration price`}>
          <AlertTriangle className="w-3.5 h-3.5" />
        </span>
      )
    }
    return null
  }

  return (
    <CommandCenterLayout
      title="TLD Pricing"
      subtitle={getSubtitle()}
      actions={
        <button
          onClick={handleRefresh}
          disabled={refreshing}
          className="flex items-center gap-2 px-4 py-2 text-sm text-foreground-muted hover:text-foreground 
                     hover:bg-foreground/5 rounded-lg transition-all disabled:opacity-50"
        >
          <RefreshCw className={clsx("w-4 h-4", refreshing && "animate-spin")} />
          <span className="hidden sm:inline">Refresh</span>
        </button>
      }
    >
      <PageContainer>
        {/* Stats Overview */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <StatCard 
            title="TLDs Tracked" 
            value={total > 0 ? total.toLocaleString() : '—'} 
            subtitle="updated daily" 
            icon={Globe} 
            accent 
          />
          <StatCard 
            title="Lowest Price" 
            value={total > 0 ? `$${lowestPrice.toFixed(2)}` : '—'} 
            icon={DollarSign} 
          />
          <StatCard 
            title="Hottest TLD" 
            value={total > 0 ? `.${hottestTld}` : '—'} 
            subtitle="rising prices" 
            icon={TrendingUp} 
          />
          <StatCard 
            title="Renewal Traps" 
            value={trapCount > 0 ? trapCount.toString() : '0'} 
            subtitle="high renewal ratio" 
            icon={AlertTriangle} 
          />
        </div>

        {/* Category Tabs */}
        <div className="flex items-center gap-2 overflow-x-auto pb-1 scrollbar-hide">
          {(Object.keys(CATEGORIES) as CategoryKey[]).map((key) => {
            const cat = CATEGORIES[key]
            const Icon = cat.icon
            return (
              <button
                key={key}
                onClick={() => setCategory(key)}
                className={clsx(
                  "flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-medium whitespace-nowrap transition-all",
                  category === key
                    ? "bg-accent/10 text-accent border border-accent/20"
                    : "bg-foreground/5 text-foreground-muted hover:text-foreground hover:bg-foreground/10 border border-transparent"
                )}
              >
                <Icon className="w-4 h-4" />
                {cat.label}
              </button>
            )
          })}
        </div>

        {/* Filters */}
        <div className="flex flex-col sm:flex-row gap-3">
          <div className="relative flex-1 max-w-md">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-foreground-muted" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search TLDs (e.g. com, io, dev)..."
              className="w-full h-11 pl-11 pr-10 bg-background-secondary/50 border border-border/50 rounded-xl
                         text-sm text-foreground placeholder:text-foreground-subtle
                         focus:outline-none focus:border-accent/50 transition-all"
            />
            {searchQuery && (
              <button 
                onClick={() => setSearchQuery('')} 
                className="absolute right-3 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground"
              >
                <X className="w-4 h-4" />
              </button>
            )}
          </div>
          <div className="relative">
            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value as any)}
              className="h-11 pl-4 pr-10 bg-background-secondary/50 border border-border/50 rounded-xl
                         text-sm text-foreground appearance-none cursor-pointer
                         focus:outline-none focus:border-accent/50"
            >
              <option value="popularity">By Popularity</option>
              <option value="price_asc">Price: Low → High</option>
              <option value="price_desc">Price: High → Low</option>
              <option value="change">By Price Change</option>
              <option value="risk">By Risk Level</option>
            </select>
            <ArrowUpDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-foreground-muted pointer-events-none" />
          </div>
        </div>

        {/* Legend */}
        <div className="flex flex-wrap items-center gap-4 text-xs text-foreground-muted">
          <div className="flex items-center gap-2">
            <Info className="w-3.5 h-3.5" />
            <span>Tip: Renewal traps show ⚠️ when renewal price is &gt;2x registration</span>
          </div>
        </div>

        {/* TLD Table */}
        <PremiumTable
          data={sortedData}
          keyExtractor={(tld) => tld.tld}
          loading={loading}
          onRowClick={(tld) => window.location.href = `/command/pricing/${tld.tld}`}
          emptyIcon={<Globe className="w-12 h-12 text-foreground-subtle" />}
          emptyTitle="No TLDs found"
          emptyDescription={searchQuery ? `No TLDs matching "${searchQuery}"` : "Check back later for TLD data"}
          columns={[
            {
              key: 'tld',
              header: 'TLD',
              width: '100px',
              render: (tld) => (
                <span className="font-mono text-lg font-semibold text-foreground group-hover:text-accent transition-colors">
                  .{tld.tld}
                </span>
              ),
            },
            {
              key: 'trend',
              header: 'Trend',
              width: '80px',
              hideOnMobile: true,
              render: (tld) => (
                <Sparkline trend={tld.price_change_1y || 0} />
              ),
            },
            {
              key: 'buy_price',
              header: 'Buy (1y)',
              align: 'right',
              width: '100px',
              render: (tld) => (
                <span className="font-semibold text-foreground tabular-nums">${tld.min_price.toFixed(2)}</span>
              ),
            },
            {
              key: 'renew_price',
              header: 'Renew (1y)',
              align: 'right',
              width: '120px',
              render: (tld) => (
                <div className="flex items-center gap-1 justify-end">
                  <span className="text-foreground-muted tabular-nums">
                    ${tld.min_renewal_price.toFixed(2)}
                  </span>
                  {getRenewalTrap(tld)}
                </div>
              ),
            },
            {
              key: 'change_1y',
              header: '1y Change',
              align: 'right',
              width: '100px',
              hideOnMobile: true,
              render: (tld) => {
                const change = tld.price_change_1y || 0
                return (
                  <span className={clsx(
                    "font-medium tabular-nums",
                    change > 0 ? "text-orange-400" : change < 0 ? "text-accent" : "text-foreground-muted"
                  )}>
                    {change > 0 ? '+' : ''}{change.toFixed(0)}%
                  </span>
                )
              },
            },
            {
              key: 'change_3y',
              header: '3y Change',
              align: 'right',
              width: '100px',
              hideOnMobile: true,
              render: (tld) => {
                const change = tld.price_change_3y || 0
                return (
                  <span className={clsx(
                    "font-medium tabular-nums",
                    change > 0 ? "text-orange-400" : change < 0 ? "text-accent" : "text-foreground-muted"
                  )}>
                    {change > 0 ? '+' : ''}{change.toFixed(0)}%
                  </span>
                )
              },
            },
            {
              key: 'risk',
              header: 'Risk',
              align: 'center',
              width: '130px',
              render: (tld) => getRiskBadge(tld),
            },
            {
              key: 'actions',
              header: '',
              align: 'right',
              width: '80px',
              render: () => (
                <ChevronRight className="w-5 h-5 text-foreground-subtle group-hover:text-accent transition-colors" />
              ),
            },
          ]}
        />

        {/* Pagination */}
        {total > 50 && (
          <div className="flex items-center justify-center gap-4 pt-2">
            <button
              onClick={() => setPage(Math.max(0, page - 1))}
              disabled={page === 0}
              className="px-4 py-2 text-sm font-medium text-foreground-muted hover:text-foreground 
                         bg-foreground/5 hover:bg-foreground/10 rounded-lg
                         disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              Previous
            </button>
            <span className="text-sm text-foreground-muted tabular-nums">
              Page {page + 1} of {Math.ceil(total / 50)}
            </span>
            <button
              onClick={() => setPage(page + 1)}
              disabled={(page + 1) * 50 >= total}
              className="px-4 py-2 text-sm font-medium text-foreground-muted hover:text-foreground 
                         bg-foreground/5 hover:bg-foreground/10 rounded-lg
                         disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              Next
            </button>
          </div>
        )}
      </PageContainer>
    </CommandCenterLayout>
  )
}
