'use client'

import { useEffect, useState } from 'react'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import { PremiumTable } from '@/components/PremiumTable'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import {
  TrendingUp,
  ChevronRight,
  ChevronLeft,
  Search,
  X,
  Lock,
  Globe,
  AlertTriangle,
  ArrowUpDown,
} from 'lucide-react'
import Link from 'next/link'
import clsx from 'clsx'

interface TldData {
  tld: string
  type: string
  description: string
  avg_registration_price: number
  min_registration_price: number
  max_registration_price: number
  min_renewal_price: number
  avg_renewal_price: number
  registrar_count: number
  trend: string
  price_change_7d: number
  price_change_1y: number
  price_change_3y: number
  risk_level: 'low' | 'medium' | 'high'
  risk_reason: string
  popularity_rank?: number
}

interface TrendingTld {
  tld: string
  reason: string
  price_change: number
  current_price: number
}

interface PaginationData {
  total: number
  limit: number
  offset: number
  has_more: boolean
}

// Sparkline component - matching Command Center exactly
function Sparkline({ trend }: { trend: number }) {
  const isPositive = trend > 0
  const isNeutral = trend === 0
  
  return (
    <div className="flex items-center gap-1">
      <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,6 20,10 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 { isAuthenticated, checkAuth, isLoading: authLoading } = useStore()
  const [tlds, setTlds] = useState<TldData[]>([])
  const [trending, setTrending] = useState<TrendingTld[]>([])
  const [loading, setLoading] = useState(true)
  const [pagination, setPagination] = useState<PaginationData>({ total: 0, limit: 50, offset: 0, has_more: false })
  
  // Search & Sort state
  const [searchQuery, setSearchQuery] = useState('')
  const [debouncedSearch, setDebouncedSearch] = useState('')
  const [sortBy, setSortBy] = useState('popularity')
  const [page, setPage] = useState(0)

  // Debounce search
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearch(searchQuery)
    }, 300)
    return () => clearTimeout(timer)
  }, [searchQuery])

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

  // Load TLDs with pagination, search, and sort
  useEffect(() => {
    loadTlds()
  }, [debouncedSearch, sortBy, page])

  const loadTlds = async () => {
    setLoading(true)
    try {
      const data = await api.getTldOverview(
        50,
        page * 50,
        sortBy,
        debouncedSearch || undefined
      )
      
      setTlds(data?.tlds || [])
      setPagination({
        total: data?.total || 0,
        limit: 50,
        offset: page * 50,
        has_more: data?.has_more || false,
      })
    } catch (error) {
      console.error('Failed to load TLD data:', error)
      setTlds([])
    } finally {
      setLoading(false)
    }
  }

  const loadTrending = async () => {
    try {
      const data = await api.getTrendingTlds()
      setTrending(data?.trending || [])
    } catch (error) {
      console.error('Failed to load trending:', error)
    }
  }

  // Risk badge - matching Command Center exactly
  const getRiskBadge = (tld: TldData) => {
    const level = tld.risk_level || 'low'
    const reason = tld.risk_reason || 'Stable'
    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>
    )
  }

  // Get renewal trap indicator
  const getRenewalTrap = (tld: TldData) => {
    if (!tld.min_renewal_price || !tld.min_registration_price) return null
    const ratio = tld.min_renewal_price / tld.min_registration_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
  }

  // Pagination calculations
  const currentPage = Math.floor(pagination.offset / pagination.limit) + 1
  const totalPages = Math.ceil(pagination.total / pagination.limit)

  if (authLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="w-5 h-5 border-2 border-accent border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background relative overflow-hidden">
      {/* Background Effects - matching landing page */}
      <div className="fixed inset-0 pointer-events-none">
        <div className="absolute top-[-20%] left-1/2 -translate-x-1/2 w-[1200px] h-[800px] bg-accent/[0.03] rounded-full blur-[120px]" />
        <div className="absolute bottom-[-10%] right-[-10%] w-[600px] h-[600px] bg-accent/[0.02] rounded-full blur-[100px]" />
        <div 
          className="absolute inset-0 opacity-[0.015]"
          style={{
            backgroundImage: `linear-gradient(rgba(255,255,255,.1) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.1) 1px, transparent 1px)`,
            backgroundSize: '64px 64px',
          }}
        />
      </div>

      <Header />

      <main className="relative pt-32 sm:pt-40 pb-20 sm:pb-28 px-4 sm:px-6 flex-1">
        <div className="max-w-7xl mx-auto">
          {/* Header */}
          <div className="text-center mb-12 sm:mb-16 animate-fade-in">
            <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-accent/10 border border-accent/20 text-accent text-sm mb-6">
              <TrendingUp className="w-4 h-4" />
              <span>Real-time Market Data</span>
            </div>
            <h1 className="font-display text-[2.5rem] sm:text-[3.5rem] md:text-[4.5rem] leading-[0.95] tracking-[-0.03em] text-foreground">
              {pagination.total}+ TLDs.
              <span className="block text-accent">True Costs.</span>
            </h1>
            <p className="mt-5 text-lg sm:text-xl text-foreground-muted max-w-2xl mx-auto">
              Don&apos;t fall for promo prices. See renewal costs, spot traps, and track price trends across every extension.
            </p>
            
            {/* Feature Pills */}
            <div className="flex flex-wrap items-center justify-center gap-3 mt-8">
              <div className="flex items-center gap-2 px-4 py-2 bg-foreground/5 rounded-full text-sm">
                <AlertTriangle className="w-4 h-4 text-amber-400" />
                <span className="text-foreground-muted">Renewal Trap Detection</span>
              </div>
              <div className="flex items-center gap-2 px-4 py-2 bg-foreground/5 rounded-full text-sm">
                <div className="flex items-center gap-1">
                  <span className="w-2 h-2 rounded-full bg-accent" />
                  <span className="w-2 h-2 rounded-full bg-amber-400" />
                  <span className="w-2 h-2 rounded-full bg-red-400" />
                </div>
                <span className="text-foreground-muted">Risk Levels</span>
              </div>
              <div className="flex items-center gap-2 px-4 py-2 bg-foreground/5 rounded-full text-sm">
                <TrendingUp className="w-4 h-4 text-orange-400" />
                <span className="text-foreground-muted">1y/3y Trends</span>
              </div>
            </div>
          </div>

          {/* Login Banner for non-authenticated users */}
          {!isAuthenticated && (
            <div className="mb-8 p-6 bg-gradient-to-r from-accent/10 to-accent/5 border border-accent/20 rounded-2xl animate-fade-in">
              <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
                <div className="flex items-center gap-4">
                  <div className="w-12 h-12 bg-accent/20 rounded-xl flex items-center justify-center">
                    <Lock className="w-6 h-6 text-accent" />
                  </div>
                  <div>
                    <p className="font-medium text-foreground">Stop overpaying. Know the true costs.</p>
                    <p className="text-sm text-foreground-muted">
                      Unlock renewal traps, 1y/3y trends, and risk analysis for {pagination.total}+ TLDs.
                    </p>
                  </div>
                </div>
                <Link
                  href="/register"
                  className="shrink-0 px-6 py-3 bg-accent text-background font-medium rounded-xl
                             hover:bg-accent-hover transition-all shadow-lg shadow-accent/20"
                >
                  Start Free
                </Link>
              </div>
            </div>
          )}

          {/* Trending Section */}
          {trending.length > 0 && (
            <div className="mb-12 sm:mb-16 animate-slide-up">
              <h2 className="text-body-lg sm:text-heading-sm font-medium text-foreground mb-4 sm:mb-6 flex items-center gap-2">
                <TrendingUp className="w-5 h-5 text-accent" />
                Moving Now
              </h2>
              <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
                {trending.map((item) => (
                  <Link
                    key={item.tld}
                    href={isAuthenticated ? `/tld-pricing/${item.tld}` : '/register'}
                    className="p-4 sm:p-5 bg-background-secondary/50 border border-border rounded-xl hover:border-border-hover hover:bg-background-secondary transition-all duration-300 text-left group"
                  >
                    <div className="flex items-center justify-between mb-3">
                      <span className="font-mono text-body-lg sm:text-heading-sm text-foreground">.{item.tld}</span>
                      <span className={clsx(
                        "text-ui-sm font-medium px-2 py-0.5 rounded-full",
                        item.price_change > 0 
                          ? "text-[#f97316] bg-[#f9731615]"
                          : "text-accent bg-accent-muted"
                      )}>
                        {item.price_change > 0 ? '+' : ''}{item.price_change.toFixed(1)}%
                      </span>
                    </div>
                    <p className="text-body-sm text-foreground-muted mb-2 line-clamp-2">
                      {item.reason}
                    </p>
                    <div className="flex items-center justify-between">
                      <span className="text-body-sm text-foreground-subtle">
                        ${item.current_price.toFixed(2)}/yr
                      </span>
                      <ChevronRight className="w-4 h-4 text-foreground-subtle group-hover:text-accent transition-colors" />
                    </div>
                  </Link>
                ))}
              </div>
            </div>
          )}

          {/* Search & Sort Controls */}
          <div className="flex flex-col sm:flex-row gap-4 mb-6 animate-slide-up">
            {/* Search */}
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-foreground-subtle" />
              <input
                type="text"
                placeholder="Search TLDs (e.g., com, io, ai)..."
                value={searchQuery}
                onChange={(e) => {
                  setSearchQuery(e.target.value)
                  setPage(0)
                }}
                className="w-full pl-12 pr-10 py-3 bg-background-secondary/50 border border-border rounded-xl
                           text-body text-foreground placeholder:text-foreground-subtle
                           focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent
                           transition-all duration-300"
              />
              {searchQuery && (
                <button
                  onClick={() => {
                    setSearchQuery('')
                    setPage(0)
                  }}
                  className="absolute right-4 top-1/2 -translate-y-1/2 p-1 text-foreground-subtle hover:text-foreground transition-colors"
                >
                  <X className="w-4 h-4" />
                </button>
              )}
            </div>
            
            {/* Sort */}
            <div className="relative">
              <select
                value={sortBy}
                onChange={(e) => {
                  setSortBy(e.target.value)
                  setPage(0)
                }}
                className="appearance-none pl-4 pr-10 py-3 bg-background-secondary/50 border border-border rounded-xl
                           text-body text-foreground focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent
                           transition-all cursor-pointer min-w-[180px]"
              >
                <option value="popularity">Most Popular</option>
                <option value="name">Alphabetical</option>
                <option value="price_asc">Price: Low → High</option>
                <option value="price_desc">Price: High → Low</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>

          {/* TLD Table using PremiumTable - matching Command Center exactly */}
          <PremiumTable
            data={tlds}
            keyExtractor={(tld) => tld.tld}
            loading={loading}
            onRowClick={(tld) => {
              if (isAuthenticated) {
                window.location.href = `/tld-pricing/${tld.tld}`
              } else {
                window.location.href = `/login?redirect=/tld-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, idx) => (
                  <div className="flex items-center gap-2">
                    <span className="font-mono text-lg font-semibold text-foreground group-hover:text-accent transition-colors">
                      .{tld.tld}
                    </span>
                    {!isAuthenticated && idx === 0 && page === 0 && (
                      <span className="text-xs text-accent">Preview</span>
                    )}
                  </div>
                ),
              },
              {
                key: 'trend',
                header: 'Trend',
                width: '80px',
                hideOnMobile: true,
                render: (tld, idx) => {
                  const showData = isAuthenticated || (page === 0 && idx === 0)
                  if (!showData) {
                    return <div className="w-10 h-4 bg-foreground/5 rounded blur-[3px]" />
                  }
                  return <Sparkline trend={tld.price_change_1y || 0} />
                },
              },
              {
                key: 'buy_price',
                header: 'Buy (1y)',
                align: 'right',
                width: '100px',
                render: (tld, idx) => {
                  const showData = isAuthenticated || (page === 0 && idx === 0)
                  if (!showData) {
                    return <span className="text-foreground-subtle">•••</span>
                  }
                  return <span className="font-semibold text-foreground tabular-nums">${tld.min_registration_price.toFixed(2)}</span>
                },
              },
              {
                key: 'renew_price',
                header: 'Renew (1y)',
                align: 'right',
                width: '120px',
                render: (tld, idx) => {
                  const showData = isAuthenticated || (page === 0 && idx === 0)
                  if (!showData) {
                    return <span className="text-foreground-subtle blur-[3px]">$XX.XX</span>
                  }
                  return (
                    <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, idx) => {
                  const showData = isAuthenticated || (page === 0 && idx === 0)
                  if (!showData) {
                    return <span className="text-foreground-subtle blur-[3px]">+X%</span>
                  }
                  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, idx) => {
                  const showData = isAuthenticated || (page === 0 && idx === 0)
                  if (!showData) {
                    return <span className="text-foreground-subtle blur-[3px]">+X%</span>
                  }
                  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, idx) => {
                  const showData = isAuthenticated || (page === 0 && idx === 0)
                  if (!showData) {
                    return (
                      <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-foreground/5 blur-[3px]">
                        <span className="w-2.5 h-2.5 rounded-full bg-foreground-subtle" />
                        <span className="hidden sm:inline ml-1">Hidden</span>
                      </span>
                    )
                  }
                  return 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 */}
          {!loading && pagination.total > pagination.limit && (
            <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 {currentPage} of {totalPages}
              </span>
              <button
                onClick={() => setPage(page + 1)}
                disabled={!pagination.has_more}
                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>
          )}

          {/* Stats */}
          {!loading && (
            <div className="mt-6 flex justify-center">
              <p className="text-ui-sm text-foreground-subtle">
                {searchQuery 
                  ? `Found ${pagination.total} TLDs matching "${searchQuery}"`
                  : `${pagination.total} TLDs available`
                }
              </p>
            </div>
          )}
        </div>
      </main>

      <Footer />
    </div>
  )
}
