'use client'

import { useState, useEffect, useCallback, useMemo } from 'react'
import { api } from '@/lib/api'
import { useAnalyzePanelStore } from '@/lib/analyze-store'
import { useStore } from '@/lib/store'
import { 
  Clock, 
  Globe, 
  Loader2, 
  Search, 
  ChevronRight, 
  ChevronLeft,
  ChevronUp,
  ChevronDown,
  RefreshCw,
  X,
  Eye,
  Shield,
  ExternalLink,
  Zap,
  Filter,
  Ban,
  Hash,
} from 'lucide-react'
import clsx from 'clsx'

// ============================================================================
// TYPES
// ============================================================================

interface DroppedDomain {
  domain: string
  tld: string
  dropped_date: string
  length: number
  is_numeric: boolean
  has_hyphen: boolean
}

interface ZoneStats {
  ch: { domain_count: number; last_sync: string | null }
  li: { domain_count: number; last_sync: string | null }
  daily_drops: number
}

// All supported TLDs
type SupportedTld = 'ch' | 'li' | 'xyz' | 'org' | 'online' | 'info' | 'dev' | 'app'

const ALL_TLDS: { tld: SupportedTld; flag: string }[] = [
  { tld: 'ch', flag: '🇨🇭' },
  { tld: 'li', flag: '🇱🇮' },
  { tld: 'xyz', flag: '🌐' },
  { tld: 'org', flag: '🏛️' },
  { tld: 'online', flag: '💻' },
  { tld: 'info', flag: 'ℹ️' },
  { tld: 'dev', flag: '👨‍💻' },
  { tld: 'app', flag: '📱' },
]

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

interface DropsTabProps {
  showToast: (message: string, type?: 'success' | 'error' | 'info') => void
}

export function DropsTab({ showToast }: DropsTabProps) {
  const openAnalyze = useAnalyzePanelStore((s) => s.open)
  const addDomain = useStore((s) => s.addDomain)

  // Data State
  const [items, setItems] = useState<DroppedDomain[]>([])
  const [stats, setStats] = useState<ZoneStats | null>(null)
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const [total, setTotal] = useState(0)

  // Filter State  
  const [selectedTld, setSelectedTld] = useState<SupportedTld | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [searchFocused, setSearchFocused] = useState(false)
  const [minLength, setMinLength] = useState<number | undefined>(undefined)
  const [maxLength, setMaxLength] = useState<number | undefined>(undefined)
  const [excludeNumeric, setExcludeNumeric] = useState(true)
  const [excludeHyphen, setExcludeHyphen] = useState(true)
  const [filtersOpen, setFiltersOpen] = useState(false)

  // Pagination
  const [page, setPage] = useState(1)
  const ITEMS_PER_PAGE = 50

  // Sorting
  const [sortField, setSortField] = useState<'domain' | 'length' | 'date'>('length')
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')

  // Tracking
  const [tracking, setTracking] = useState<string | null>(null)

  // Load Stats
  const loadStats = useCallback(async () => {
    try {
      const result = await api.getDropsStats()
      setStats(result)
    } catch (error) {
      console.error('Failed to load zone stats:', error)
    }
  }, [])

  // Load Drops (only last 24h)
  const loadDrops = useCallback(async (currentPage = 1, isRefresh = false) => {
    if (isRefresh) setRefreshing(true)
    else setLoading(true)

    try {
      const result = await api.getDrops({
        tld: selectedTld || undefined,
        hours: 24, // Only last 24h - fresh drops only!
        min_length: minLength,
        max_length: maxLength,
        exclude_numeric: excludeNumeric,
        exclude_hyphen: excludeHyphen,
        keyword: searchQuery || undefined,
        limit: ITEMS_PER_PAGE,
        offset: (currentPage - 1) * ITEMS_PER_PAGE,
      })
      setItems(result.items)
      setTotal(result.total)
    } catch (error: any) {
      console.error('Failed to load drops:', error)
      if (error.message?.includes('401') || error.message?.includes('auth')) {
        showToast('Login required to view drops', 'info')
      }
      setItems([])
      setTotal(0)
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }, [selectedTld, minLength, maxLength, excludeNumeric, excludeHyphen, searchQuery, showToast])

  // Initial Load
  useEffect(() => {
    loadStats()
  }, [loadStats])

  useEffect(() => {
    setPage(1)
    loadDrops(1)
  }, [loadDrops])

  const handlePageChange = useCallback((newPage: number) => {
    setPage(newPage)
    loadDrops(newPage)
  }, [loadDrops])

  const handleRefresh = useCallback(async () => {
    await loadDrops(page, true)
    await loadStats()
  }, [loadDrops, loadStats, page])

  const track = useCallback(async (domain: string) => {
    if (tracking) return
    setTracking(domain)
    try {
      await addDomain(domain)
      showToast(`Tracking ${domain}`, 'success')
    } catch (e) {
      showToast(e instanceof Error ? e.message : 'Failed', 'error')
    } finally {
      setTracking(null)
    }
  }, [addDomain, showToast, tracking])

  // Sorted Items
  const sortedItems = useMemo(() => {
    const mult = sortDirection === 'asc' ? 1 : -1
    return [...items].sort((a, b) => {
      switch (sortField) {
        case 'domain':
          return mult * a.domain.localeCompare(b.domain)
        case 'length':
          return mult * (a.length - b.length)
        case 'date':
          return mult * (new Date(a.dropped_date).getTime() - new Date(b.dropped_date).getTime())
        default:
          return 0
      }
    })
  }, [items, sortField, sortDirection])

  const handleSort = useCallback((field: typeof sortField) => {
    if (sortField === field) {
      setSortDirection((d) => (d === 'asc' ? 'desc' : 'asc'))
    } else {
      setSortField(field)
      setSortDirection(field === 'length' ? 'asc' : 'desc')
    }
  }, [sortField])

  const totalPages = Math.ceil(total / ITEMS_PER_PAGE)
  const activeFiltersCount = [
    selectedTld !== null,
    minLength !== undefined,
    maxLength !== undefined,
    excludeNumeric,
    excludeHyphen,
  ].filter(Boolean).length

  const formatTime = (iso: string) => {
    const d = new Date(iso)
    const now = new Date()
    const diffH = Math.floor((now.getTime() - d.getTime()) / (1000 * 60 * 60))
    if (diffH < 1) return 'Just now'
    if (diffH === 1) return '1h ago'
    return `${diffH}h ago`
  }

  if (loading && items.length === 0) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-6 h-6 text-accent animate-spin" />
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* Header Stats */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 bg-accent/10 border border-accent/20 flex items-center justify-center">
            <Zap className="w-5 h-5 text-accent" />
          </div>
          <div>
            <div className="text-xl font-bold text-white font-mono">
              {stats?.daily_drops?.toLocaleString() || total.toLocaleString()}
            </div>
            <div className="text-[10px] font-mono text-white/40 uppercase">Fresh drops (24h)</div>
          </div>
        </div>
        <button
          onClick={handleRefresh}
          disabled={refreshing}
          className="p-2 border border-white/10 text-white/30 hover:text-white hover:bg-white/5 transition-colors"
        >
          <RefreshCw className={clsx("w-4 h-4", refreshing && "animate-spin")} />
        </button>
      </div>

      {/* Search */}
      <div className={clsx(
        "relative border transition-all duration-200",
        searchFocused ? "border-accent/50 bg-accent/[0.02]" : "border-white/[0.08] bg-white/[0.02]"
      )}>
        <div className="flex items-center">
          <Search className={clsx("w-4 h-4 ml-3 transition-colors", searchFocused ? "text-accent" : "text-white/30")} />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            onFocus={() => setSearchFocused(true)}
            onBlur={() => setSearchFocused(false)}
            placeholder="Search drops..."
            className="flex-1 bg-transparent px-3 py-3 text-sm text-white placeholder:text-white/20 outline-none font-mono"
          />
          {searchQuery && (
            <button onClick={() => setSearchQuery('')} className="p-3 text-white/30 hover:text-white transition-colors">
              <X className="w-4 h-4" />
            </button>
          )}
        </div>
      </div>

      {/* TLD Quick Filter */}
      <div className="flex gap-1.5 flex-wrap">
        <button
          onClick={() => setSelectedTld(null)}
          className={clsx(
            "px-2.5 py-1.5 text-[10px] font-mono uppercase border transition-colors",
            selectedTld === null ? "border-accent bg-accent/10 text-accent" : "border-white/[0.08] text-white/40"
          )}
        >
          All
        </button>
        {ALL_TLDS.map(({ tld, flag }) => (
          <button
            key={tld}
            onClick={() => setSelectedTld(tld)}
            className={clsx(
              "px-2.5 py-1.5 text-[10px] font-mono uppercase border transition-colors flex items-center gap-1",
              selectedTld === tld ? "border-accent bg-accent/10 text-accent" : "border-white/[0.08] text-white/40"
            )}
          >
            <span className="text-xs">{flag}</span>.{tld}
          </button>
        ))}
      </div>

      {/* Filter Toggle */}
      <button
        onClick={() => setFiltersOpen(!filtersOpen)}
        className={clsx(
          "flex items-center justify-between w-full py-2 px-3 border transition-colors",
          filtersOpen ? "border-accent/30 bg-accent/[0.05]" : "border-white/[0.08] bg-white/[0.02]"
        )}
      >
        <div className="flex items-center gap-2">
          <Filter className="w-4 h-4 text-white/40" />
          <span className="text-xs font-mono text-white/60">Filters</span>
          {activeFiltersCount > 0 && (
            <span className="px-1.5 py-0.5 text-[9px] font-bold bg-accent text-black">{activeFiltersCount}</span>
          )}
        </div>
        <ChevronRight className={clsx("w-4 h-4 text-white/30 transition-transform", filtersOpen && "rotate-90")} />
      </button>

      {/* Filters Panel */}
      {filtersOpen && (
        <div className="p-3 border border-white/[0.08] bg-white/[0.02] space-y-3 animate-in fade-in slide-in-from-top-2 duration-200">
          {/* Length Filter */}
          <div>
            <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider mb-2">Length</div>
            <div className="flex gap-2 items-center">
              <input
                type="number"
                value={minLength || ''}
                onChange={(e) => setMinLength(e.target.value ? Number(e.target.value) : undefined)}
                placeholder="Min"
                className="w-16 bg-white/[0.02] border border-white/10 px-2 py-1.5 text-xs text-white placeholder:text-white/25 outline-none font-mono"
                min={1}
                max={63}
              />
              <span className="text-white/20">–</span>
              <input
                type="number"
                value={maxLength || ''}
                onChange={(e) => setMaxLength(e.target.value ? Number(e.target.value) : undefined)}
                placeholder="Max"
                className="w-16 bg-white/[0.02] border border-white/10 px-2 py-1.5 text-xs text-white placeholder:text-white/25 outline-none font-mono"
                min={1}
                max={63}
              />
            </div>
          </div>

          {/* Quality Filters */}
          <div className="flex gap-2">
            <button
              onClick={() => setExcludeNumeric(!excludeNumeric)}
              className={clsx(
                "flex-1 flex items-center justify-between py-2 px-3 border transition-colors",
                excludeNumeric ? "border-white/20 bg-white/[0.05]" : "border-white/[0.08]"
              )}
            >
              <div className="flex items-center gap-2">
                <Hash className="w-3.5 h-3.5 text-white/40" />
                <span className="text-[10px] font-mono text-white/60">No numbers</span>
              </div>
              <div className={clsx("w-3.5 h-3.5 border flex items-center justify-center", excludeNumeric ? "border-accent bg-accent" : "border-white/30")}>
                {excludeNumeric && <span className="text-black text-[8px] font-bold">✓</span>}
              </div>
            </button>

            <button
              onClick={() => setExcludeHyphen(!excludeHyphen)}
              className={clsx(
                "flex-1 flex items-center justify-between py-2 px-3 border transition-colors",
                excludeHyphen ? "border-white/20 bg-white/[0.05]" : "border-white/[0.08]"
              )}
            >
              <div className="flex items-center gap-2">
                <Ban className="w-3.5 h-3.5 text-white/40" />
                <span className="text-[10px] font-mono text-white/60">No hyphens</span>
              </div>
              <div className={clsx("w-3.5 h-3.5 border flex items-center justify-center", excludeHyphen ? "border-accent bg-accent" : "border-white/30")}>
                {excludeHyphen && <span className="text-black text-[8px] font-bold">✓</span>}
              </div>
            </button>
          </div>
        </div>
      )}

      {/* Stats Bar */}
      <div className="flex items-center justify-between text-[10px] font-mono text-white/40">
        <span>{total.toLocaleString()} fresh drops</span>
        {totalPages > 1 && <span>Page {page}/{totalPages}</span>}
      </div>

      {/* Results */}
      {sortedItems.length === 0 ? (
        <div className="text-center py-16 border border-dashed border-white/[0.08]">
          <Globe className="w-8 h-8 text-white/10 mx-auto mb-3" />
          <p className="text-white/40 text-sm font-mono">No fresh drops</p>
          <p className="text-white/25 text-xs font-mono mt-1">Check back after the next sync</p>
        </div>
      ) : (
        <>
          <div className="space-y-px bg-white/[0.04] border border-white/[0.08]">
            {/* Desktop Table Header */}
            <div className="hidden lg:grid grid-cols-[1fr_60px_80px_100px] gap-4 px-3 py-2 text-[10px] font-mono text-white/40 uppercase tracking-wider border-b border-white/[0.08]">
              <button onClick={() => handleSort('domain')} className="flex items-center gap-1 hover:text-white/60 text-left">
                Domain
                {sortField === 'domain' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
              </button>
              <button onClick={() => handleSort('length')} className="flex items-center gap-1 justify-center hover:text-white/60">
                Len
                {sortField === 'length' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
              </button>
              <button onClick={() => handleSort('date')} className="flex items-center gap-1 justify-center hover:text-white/60">
                When
                {sortField === 'date' && (sortDirection === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
              </button>
              <div className="text-right">Actions</div>
            </div>

            {sortedItems.map((item) => (
              <div key={item.domain} className="bg-[#020202] hover:bg-white/[0.02] transition-all">
                {/* Mobile Row */}
                <div className="lg:hidden p-3">
                  <div className="flex items-center justify-between gap-3 mb-2">
                    <div className="flex items-center gap-2 min-w-0 flex-1">
                      <span className="text-sm shrink-0">{ALL_TLDS.find(t => t.tld === item.tld)?.flag || '🌐'}</span>
                      <button onClick={() => openAnalyze(item.domain)} className="text-sm font-bold text-white font-mono truncate text-left">
                        {item.domain}
                      </button>
                    </div>
                    <div className="flex items-center gap-2 shrink-0">
                      <span className={clsx(
                        "text-[10px] font-mono font-bold px-1.5 py-0.5",
                        item.length <= 5 ? "text-accent bg-accent/10" : "text-white/40 bg-white/5"
                      )}>
                        {item.length}
                      </span>
                      <span className="text-[10px] font-mono text-white/30">{formatTime(item.dropped_date)}</span>
                    </div>
                  </div>

                  <div className="flex gap-2">
                    <button
                      onClick={() => track(item.domain)}
                      disabled={tracking === item.domain}
                      className="flex-1 py-2 text-[10px] font-bold uppercase tracking-wider border border-white/[0.08] text-white/40 flex items-center justify-center gap-1.5"
                    >
                      {tracking === item.domain ? <Loader2 className="w-3 h-3 animate-spin" /> : <Eye className="w-3 h-3" />}
                      Track
                    </button>
                    <button onClick={() => openAnalyze(item.domain)} className="w-10 py-2 border border-white/[0.08] text-white/50 flex items-center justify-center">
                      <Shield className="w-3.5 h-3.5" />
                    </button>
                    <a
                      href={`https://www.namecheap.com/domains/registration/results/?domain=${item.domain}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex-1 py-2 bg-accent text-black text-[10px] font-bold uppercase flex items-center justify-center gap-1"
                    >
                      Get <ExternalLink className="w-3 h-3" />
                    </a>
                  </div>
                </div>

                {/* Desktop Row */}
                <div className="hidden lg:grid grid-cols-[1fr_60px_80px_100px] gap-4 items-center p-3 group">
                  <div className="flex items-center gap-2 min-w-0 flex-1">
                    <span className="text-sm shrink-0">{ALL_TLDS.find(t => t.tld === item.tld)?.flag || '🌐'}</span>
                    <button
                      onClick={() => openAnalyze(item.domain)}
                      className="text-sm font-bold text-white font-mono truncate group-hover:text-accent transition-colors text-left"
                    >
                      {item.domain}
                    </button>
                  </div>

                  <div className="text-center">
                    <span className={clsx(
                      "text-[10px] font-mono font-bold px-1.5 py-0.5",
                      item.length <= 5 ? "text-accent bg-accent/10" : item.length <= 8 ? "text-amber-400 bg-amber-400/10" : "text-white/40 bg-white/5"
                    )}>
                      {item.length}
                    </span>
                  </div>

                  <div className="text-center">
                    <span className="text-[10px] font-mono text-white/50">{formatTime(item.dropped_date)}</span>
                  </div>

                  <div className="flex items-center justify-end gap-1.5 opacity-50 group-hover:opacity-100 transition-opacity">
                    <button
                      onClick={() => track(item.domain)}
                      disabled={tracking === item.domain}
                      className="w-6 h-6 flex items-center justify-center border border-white/10 text-white/30 hover:text-white hover:bg-white/5"
                    >
                      {tracking === item.domain ? <Loader2 className="w-3 h-3 animate-spin" /> : <Eye className="w-3 h-3" />}
                    </button>
                    <button
                      onClick={() => openAnalyze(item.domain)}
                      className="w-6 h-6 flex items-center justify-center border border-white/10 text-white/30 hover:text-accent hover:border-accent/20 hover:bg-accent/10"
                    >
                      <Shield className="w-3 h-3" />
                    </button>
                    <a
                      href={`https://www.namecheap.com/domains/registration/results/?domain=${item.domain}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="h-6 px-2 bg-accent text-black text-[10px] font-bold flex items-center gap-1 hover:bg-white"
                    >
                      Get
                    </a>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-center gap-1 pt-2">
              <button
                onClick={() => handlePageChange(page - 1)}
                disabled={page === 1}
                className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/50 hover:text-white hover:bg-white/5 disabled:opacity-30 disabled:cursor-not-allowed"
              >
                <ChevronLeft className="w-4 h-4" />
              </button>
              <span className="text-xs text-white/50 font-mono px-3">{page}/{totalPages}</span>
              <button
                onClick={() => handlePageChange(page + 1)}
                disabled={page === totalPages}
                className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/50 hover:text-white hover:bg-white/5 disabled:opacity-30 disabled:cursor-not-allowed"
              >
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          )}
        </>
      )}
    </div>
  )
}
