'use client'

import { useState, useCallback, useEffect, useRef } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { useAnalyzePanelStore } from '@/lib/analyze-store'
import {
  Search,
  X,
  Loader2,
  CheckCircle2,
  XCircle,
  Eye,
  ArrowRight,
  Shield,
  Globe,
  Calendar,
  Building,
  Clock,
  RefreshCw,
  Sparkles,
  ExternalLink,
  History,
} from 'lucide-react'
import clsx from 'clsx'

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

interface SearchResult {
  domain: string
  status: string
  is_available: boolean | null
  registrar: string | null
  expiration_date: string | null
  loading: boolean
}

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

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

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

  const [searchQuery, setSearchQuery] = useState('')
  const [searchResult, setSearchResult] = useState<SearchResult | null>(null)
  const [addingToWatchlist, setAddingToWatchlist] = useState(false)
  const [searchFocused, setSearchFocused] = useState(false)
  const [recentSearches, setRecentSearches] = useState<string[]>([])
  const searchInputRef = useRef<HTMLInputElement>(null)

  // Load recent searches from localStorage
  useEffect(() => {
    const stored = localStorage.getItem('pounce_recent_searches')
    if (stored) {
      try {
        setRecentSearches(JSON.parse(stored).slice(0, 8))
      } catch {
        // Ignore invalid JSON
      }
    }
  }, [])

  // Save to recent searches
  const saveToRecent = useCallback((domain: string) => {
    setRecentSearches((prev) => {
      const filtered = prev.filter((d) => d !== domain)
      const updated = [domain, ...filtered].slice(0, 8)
      localStorage.setItem('pounce_recent_searches', JSON.stringify(updated))
      return updated
    })
  }, [])

  // Search Handler
  const handleSearch = useCallback(async (domainInput: string) => {
    if (!domainInput.trim()) {
      setSearchResult(null)
      return
    }
    const cleanDomain = domainInput.trim().toLowerCase()
    setSearchResult({ domain: cleanDomain, status: 'checking', is_available: null, registrar: null, expiration_date: null, loading: true })

    try {
      const whoisResult = await api.checkDomain(cleanDomain).catch(() => null)
      setSearchResult({
        domain: whoisResult?.domain || cleanDomain,
        status: whoisResult?.status || 'unknown',
        is_available: whoisResult?.is_available ?? null,
        registrar: whoisResult?.registrar || null,
        expiration_date: whoisResult?.expiration_date || null,
        loading: false,
      })
      saveToRecent(cleanDomain)
    } catch {
      setSearchResult({ domain: cleanDomain, status: 'error', is_available: null, registrar: null, expiration_date: null, loading: false })
    }
  }, [saveToRecent])

  const handleAddToWatchlist = useCallback(async () => {
    if (!searchQuery.trim()) return
    setAddingToWatchlist(true)
    try {
      await addDomain(searchQuery.trim())
      showToast(`Added: ${searchQuery.trim()}`, 'success')
    } catch (err: any) {
      showToast(err.message || 'Failed', 'error')
    } finally {
      setAddingToWatchlist(false)
    }
  }, [searchQuery, addDomain, showToast])

  // Debounced search
  useEffect(() => {
    const timer = setTimeout(() => {
      if (searchQuery.length > 3) handleSearch(searchQuery)
      else setSearchResult(null)
    }, 500)
    return () => clearTimeout(timer)
  }, [searchQuery, handleSearch])

  // Focus input on mount
  useEffect(() => {
    searchInputRef.current?.focus()
  }, [])

  return (
    <div className="space-y-4">
      {/* Search Input */}
      <div className={clsx(
        "relative border-2 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-5 h-5 ml-4 transition-colors", searchFocused ? "text-accent" : "text-white/30")} />
          <input
            ref={searchInputRef}
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            onFocus={() => setSearchFocused(true)}
            onBlur={() => setSearchFocused(false)}
            onKeyDown={(e) => e.key === 'Enter' && handleSearch(searchQuery)}
            placeholder="example.com"
            className="flex-1 bg-transparent px-3 py-4 text-base lg:text-lg text-white placeholder:text-white/20 outline-none font-mono"
          />
          {searchQuery && (
            <button
              onClick={() => { setSearchQuery(''); setSearchResult(null) }}
              className="p-4 text-white/30 hover:text-white transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          )}
          <button
            onClick={() => handleSearch(searchQuery)}
            disabled={!searchQuery.trim()}
            className={clsx(
              "h-full px-4 py-4 text-sm font-bold uppercase tracking-wider transition-all",
              searchQuery.trim() ? "bg-accent text-black hover:bg-white" : "bg-white/5 text-white/20"
            )}
          >
            Check
          </button>
        </div>
      </div>

      {/* Stats Bar */}
      <div className="flex items-center justify-between text-[10px] font-mono text-white/40">
        <span>Enter a domain to check availability via RDAP/WHOIS</span>
        <span className="flex items-center gap-1">
          <Sparkles className="w-3 h-3" />
          Instant check
        </span>
      </div>

      {/* Search Result */}
      {searchResult && (
        <div className="animate-in fade-in slide-in-from-bottom-2 duration-200">
          {searchResult.loading ? (
            <div className="flex items-center justify-center gap-3 py-12 border border-white/[0.08] bg-white/[0.02]">
              <Loader2 className="w-6 h-6 animate-spin text-accent" />
              <span className="text-sm text-white/50 font-mono">Checking availability...</span>
            </div>
          ) : (
            <div className={clsx(
              "border-2 overflow-hidden bg-[#020202]",
              searchResult.is_available ? "border-accent/40" : "border-white/[0.08]"
            )}>
              {/* Result Row */}
              <div className="p-4">
                <div className="flex items-center justify-between gap-4">
                  <div className="flex items-center gap-4 min-w-0 flex-1">
                    {/* Status Icon */}
                    <div className={clsx(
                      "w-12 h-12 flex items-center justify-center border shrink-0",
                      searchResult.is_available ? "bg-accent/10 border-accent/30" : "bg-white/[0.02] border-white/[0.08]"
                    )}>
                      {searchResult.is_available ? (
                        <CheckCircle2 className="w-6 h-6 text-accent" />
                      ) : (
                        <XCircle className="w-6 h-6 text-white/30" />
                      )}
                    </div>

                    {/* Domain Info */}
                    <div className="min-w-0 flex-1">
                      <div className="text-lg font-bold text-white font-mono truncate">{searchResult.domain}</div>
                      <div className="flex items-center gap-3 text-[10px] font-mono text-white/40 mt-1">
                        <span className={clsx(
                          "px-2 py-0.5 uppercase font-bold",
                          searchResult.is_available ? "bg-accent/20 text-accent" : "bg-white/10 text-white/50"
                        )}>
                          {searchResult.is_available ? 'Available' : 'Taken'}
                        </span>
                        {searchResult.registrar && (
                          <>
                            <span className="text-white/10">|</span>
                            <span className="flex items-center gap-1">
                              <Building className="w-3 h-3" />
                              {searchResult.registrar}
                            </span>
                          </>
                        )}
                        {searchResult.expiration_date && (
                          <>
                            <span className="text-white/10">|</span>
                            <span className="flex items-center gap-1">
                              <Calendar className="w-3 h-3" />
                              Expires {new Date(searchResult.expiration_date).toLocaleDateString()}
                            </span>
                          </>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* Actions */}
                  <div className="flex items-center gap-2 shrink-0">
                    <button
                      onClick={() => openAnalyze(searchResult.domain)}
                      className="w-9 h-9 flex items-center justify-center border border-white/10 text-white/30 hover:text-accent hover:border-accent/20 hover:bg-accent/10 transition-colors"
                      title="Deep Analysis"
                    >
                      <Shield className="w-4 h-4" />
                    </button>

                    <button
                      onClick={handleAddToWatchlist}
                      disabled={addingToWatchlist}
                      className={clsx(
                        "w-9 h-9 flex items-center justify-center border transition-colors",
                        searchResult.is_available 
                          ? "border-white/10 text-white/30 hover:text-white hover:bg-white/5"
                          : "border-accent/30 text-accent hover:bg-accent/10"
                      )}
                      title={searchResult.is_available ? "Track" : "Monitor for drops"}
                    >
                      {addingToWatchlist ? <Loader2 className="w-4 h-4 animate-spin" /> : <Eye className="w-4 h-4" />}
                    </button>

                    {searchResult.is_available ? (
                      <a
                        href={`https://www.namecheap.com/domains/registration/results/?domain=${searchResult.domain}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="h-9 px-4 bg-accent text-black text-xs font-bold uppercase tracking-wider flex items-center gap-2 hover:bg-white transition-colors"
                      >
                        Register
                        <ArrowRight className="w-3.5 h-3.5" />
                      </a>
                    ) : (
                      <a
                        href={`https://www.expireddomains.net/domain-name-search/?q=${searchResult.domain.split('.')[0]}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="h-9 px-4 bg-white/10 text-white text-xs font-bold uppercase tracking-wider flex items-center gap-2 hover:bg-white/20 transition-colors"
                      >
                        Find Similar
                        <ExternalLink className="w-3.5 h-3.5" />
                      </a>
                    )}
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Recent Searches */}
      {!searchResult && recentSearches.length > 0 && (
        <div className="border border-white/[0.08] bg-white/[0.02]">
          <div className="px-4 py-3 border-b border-white/[0.08] flex items-center justify-between">
            <div className="flex items-center gap-2">
              <History className="w-4 h-4 text-white/30" />
              <span className="text-[10px] font-mono text-white/40 uppercase tracking-wider">Recent Searches</span>
            </div>
            <button
              onClick={() => {
                setRecentSearches([])
                localStorage.removeItem('pounce_recent_searches')
              }}
              className="text-[10px] font-mono text-white/30 hover:text-white transition-colors"
            >
              Clear
            </button>
          </div>
          <div className="p-3">
            <div className="flex flex-wrap gap-2">
              {recentSearches.map((domain) => (
                <button
                  key={domain}
                  onClick={() => {
                    setSearchQuery(domain)
                    handleSearch(domain)
                  }}
                  className="group px-3 py-2 border border-white/[0.08] bg-[#020202] hover:border-accent/30 hover:bg-accent/[0.03] transition-all"
                >
                  <span className="text-xs font-mono text-white/60 group-hover:text-accent transition-colors">{domain}</span>
                </button>
              ))}
            </div>
          </div>
        </div>
      )}

    </div>
  )
}
