'use client'

import { useState, useEffect } from 'react'
import { Search, Check, X, Loader2, Calendar, Building2, Server, Plus, AlertTriangle, Clock, Lock, Crosshair, ArrowRight, Sparkles } from 'lucide-react'
import { api } from '@/lib/api'
import { useStore } from '@/lib/store'
import Link from 'next/link'
import clsx from 'clsx'

interface CheckResult {
  domain: string
  status: string
  is_available: boolean
  registrar: string | null
  expiration_date: string | null
  name_servers: string[] | null
  error_message: string | null
}

const PLACEHOLDERS = [
  'crypto.ai',
  'hotel.zurich',
  'startup.io',
  'finance.xyz',
  'meta.com',
  'shop.app'
]

export function DomainChecker() {
  const [domain, setDomain] = useState('')
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<CheckResult | null>(null)
  const [error, setError] = useState<string | null>(null)
  const { isAuthenticated } = useStore()
  const [isFocused, setIsFocused] = useState(false)
  
  // Typing effect state
  const [placeholder, setPlaceholder] = useState('')
  const [placeholderIndex, setPlaceholderIndex] = useState(0)
  const [charIndex, setCharIndex] = useState(0)
  const [isDeleting, setIsDeleting] = useState(false)
  const [isPaused, setIsPaused] = useState(false)

  // Typing effect logic
  useEffect(() => {
    if (isFocused || domain) return // Stop animation when user interacts

    const currentWord = PLACEHOLDERS[placeholderIndex]
    const typeSpeed = isDeleting ? 50 : 100
    const pauseTime = 2000

    if (isPaused) {
      const timeout = setTimeout(() => {
        setIsPaused(false)
        setIsDeleting(true)
      }, pauseTime)
      return () => clearTimeout(timeout)
    }

    const timeout = setTimeout(() => {
      if (!isDeleting) {
        // Typing
        if (charIndex < currentWord.length) {
          setPlaceholder(currentWord.substring(0, charIndex + 1))
          setCharIndex(prev => prev + 1)
        } else {
          // Finished typing, pause before deleting
          setIsPaused(true)
        }
      } else {
        // Deleting
        if (charIndex > 0) {
          setPlaceholder(currentWord.substring(0, charIndex - 1))
          setCharIndex(prev => prev - 1)
        } else {
          // Finished deleting, move to next word
          setIsDeleting(false)
          setPlaceholderIndex((prev) => (prev + 1) % PLACEHOLDERS.length)
        }
      }
    }, typeSpeed)

    return () => clearTimeout(timeout)
  }, [charIndex, isDeleting, isPaused, placeholderIndex, isFocused, domain])

  const handleCheck = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!domain.trim()) return

    setLoading(true)
    setError(null)
    setResult(null)

    try {
      const res = await api.checkDomain(domain)
      setResult(res)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unable to check domain')
    } finally {
      setLoading(false)
    }
  }

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return null
    return new Date(dateStr).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    })
  }

  const getDaysUntilExpiration = (dateStr: string | null) => {
    if (!dateStr) return null
    const expDate = new Date(dateStr)
    const now = new Date()
    const diffTime = expDate.getTime() - now.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    return diffDays
  }

  return (
    <div className="w-full max-w-2xl mx-auto">
      {/* Search Form */}
      <form onSubmit={handleCheck} className="relative group">
        {/* Glow effect container - always visible, stronger on focus */}
        <div className={clsx(
          "absolute -inset-1 transition-opacity duration-500",
          isFocused ? "opacity-100" : "opacity-40 group-hover:opacity-60"
        )}>
          <div className="absolute inset-0 bg-gradient-to-r from-accent/30 via-accent/10 to-accent/30 blur-xl" />
        </div>
        
        {/* Input container */}
        <div className={clsx(
          "relative bg-[#050505] transition-all duration-300 shadow-2xl shadow-black/50 border border-white/20",
          isFocused ? "border-accent shadow-[0_0_30px_rgba(16,185,129,0.1)]" : "group-hover:border-white/40"
        )}>
          {/* Tech Corners */}
          <div className="absolute -top-px -left-px w-2 h-2 border-t border-l border-accent opacity-50" />
          <div className="absolute -top-px -right-px w-2 h-2 border-t border-r border-accent opacity-50" />
          <div className="absolute -bottom-px -left-px w-2 h-2 border-b border-l border-accent opacity-50" />
          <div className="absolute -bottom-px -right-px w-2 h-2 border-b border-r border-accent opacity-50" />

          <input
            type="text"
            value={domain}
            onChange={(e) => setDomain(e.target.value)}
            onFocus={() => setIsFocused(true)}
            onBlur={() => setIsFocused(false)}
            placeholder={isFocused ? "Enter domain..." : `Search ${placeholder}|`}
            className="w-full px-5 sm:px-7 py-5 sm:py-6 pr-32 sm:pr-40 bg-transparent rounded-none
                       text-base sm:text-lg text-white placeholder:text-white/40
                       focus:outline-none transition-colors font-mono tracking-tight"
          />
          <button
            type="submit"
            disabled={loading || !domain.trim()}
            className="absolute right-2 top-2 bottom-2
                       px-5 sm:px-7 bg-accent text-background text-sm sm:text-base font-bold uppercase tracking-wider
                       hover:bg-accent-hover active:scale-[0.98]
                       disabled:opacity-40 disabled:cursor-not-allowed
                       transition-all duration-300 flex items-center gap-2 clip-path-slant"
            style={{ clipPath: 'polygon(10% 0, 100% 0, 100% 100%, 0 100%)' }}
          >
            {loading ? (
              <Loader2 className="w-4 h-4 sm:w-5 sm:h-5 animate-spin" />
            ) : (
              <Search className="w-4 h-4 sm:w-5 sm:h-5" />
            )}
            <span>Hunt</span>
          </button>
        </div>
      </form>

      {/* Error State */}
      {error && (
        <div className="mt-8 sm:mt-10 p-4 sm:p-5 bg-danger-muted border border-danger/20 rounded-xl sm:rounded-2xl animate-fade-in">
          <p className="text-danger text-body-xs sm:text-body-sm text-center">{error}</p>
        </div>
      )}

      {/* Result Card */}
      {result && (
        <div className="mt-8 sm:mt-10 animate-scale-in">
          {result.is_available ? (
            /* ========== AVAILABLE DOMAIN ========== */
            <div className="relative group">
                <div className="absolute -inset-0.5 bg-gradient-to-r from-emerald-500/50 to-emerald-900/20 opacity-50 blur-sm transition-opacity group-hover:opacity-100" />
                <div className="relative bg-[#050505] border border-emerald-500/30 p-1 shadow-2xl">
                    {/* Inner Content */}
                    <div className="bg-[#080a08] relative overflow-hidden">
                        <div className="absolute top-0 right-0 p-4 opacity-10">
                            <Sparkles className="w-24 h-24 text-emerald-500" />
                        </div>
                        
                        <div className="p-6 flex items-start justify-between relative z-10">
                            <div>
                                <div className="flex items-center gap-3 mb-2">
                                    <div className="flex items-center gap-1.5 px-2 py-0.5 bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-[10px] font-bold uppercase tracking-widest">
                                        <div className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
                                        Available
                                    </div>
                                    <span className="text-emerald-500/40 text-[10px] font-mono">// IMMEDIATE_DEPLOY</span>
                  </div>
                                <h3 className="text-3xl sm:text-4xl font-display text-white tracking-tight mb-1">{result.domain}</h3>
                                <p className="text-emerald-400/60 font-mono text-xs">Ready for immediate acquisition.</p>
                  </div>
                            <div className="w-12 h-12 bg-emerald-500/10 border border-emerald-500/30 flex items-center justify-center text-emerald-400">
                                <Check className="w-6 h-6" strokeWidth={3} />
                </div>
              </div>
              
                        <div className="h-px w-full bg-gradient-to-r from-emerald-500/20 via-emerald-500/10 to-transparent" />

                        <div className="p-5 flex items-center justify-between bg-emerald-950/[0.05]">
                            <div className="flex flex-col">
                                <span className="text-[10px] text-white/30 uppercase tracking-widest font-mono mb-1">Status</span>
                                <span className="text-sm font-mono text-emerald-100/80">Market Open</span>
                            </div>
                  <Link
                    href={isAuthenticated ? '/terminal/hunt' : '/register'}
                                className="group relative px-6 py-3 bg-emerald-500 hover:bg-emerald-400 transition-colors text-black font-bold uppercase tracking-wider text-xs flex items-center gap-2"
                                style={{ clipPath: 'polygon(12px 0, 100% 0, 100% 100%, 0 100%, 0 12px)' }}
                  >
                                <span>Acquire Asset</span>
                                <ArrowRight className="w-3.5 h-3.5 group-hover:translate-x-1 transition-transform" />
                  </Link>
                        </div>
                </div>
              </div>
            </div>
          ) : (
            /* ========== TAKEN DOMAIN ========== */
            <div className="relative group">
                 <div className="absolute -inset-0.5 bg-gradient-to-r from-rose-500/40 to-rose-900/10 opacity-30 blur-sm transition-opacity group-hover:opacity-60" />
                 <div className="relative bg-[#050505] border border-rose-500/20 p-1 shadow-2xl">
                    <div className="bg-[#0a0505] relative overflow-hidden">
                         <div className="p-6 flex items-start justify-between relative z-10">
                            <div>
                                <div className="flex items-center gap-3 mb-2">
                                    <div className="flex items-center gap-1.5 px-2 py-0.5 bg-rose-500/10 border border-rose-500/20 text-rose-400 text-[10px] font-bold uppercase tracking-widest">
                                        <div className="w-1.5 h-1.5 rounded-full bg-rose-500" />
                                        Locked
                </div>
              </div>
                                <h3 className="text-3xl sm:text-4xl font-display text-white/40 tracking-tight mb-1 line-through decoration-rose-500/30">{result.domain}</h3>
                            </div>
                            <div className="w-12 h-12 bg-rose-500/5 border border-rose-500/10 flex items-center justify-center text-rose-500/50">
                                <Lock className="w-6 h-6" />
                        </div>
                        </div>

                        {/* Details Grid */}
                         <div className="grid grid-cols-2 border-t border-rose-500/10 divide-x divide-rose-500/10">
                            <div className="p-4 bg-rose-950/[0.02]">
                                <span className="text-[10px] text-rose-200/30 uppercase tracking-widest font-mono block mb-1">Registrar</span>
                                <span className="text-sm text-rose-100/60 font-mono truncate block">{result.registrar || 'Unknown'}</span>
                        </div>
                            <div className="p-4 bg-rose-950/[0.02]">
                                <span className="text-[10px] text-rose-200/30 uppercase tracking-widest font-mono block mb-1">Expires</span>
                                <span className={clsx("text-sm font-mono block", 
                                    getDaysUntilExpiration(result.expiration_date) !== null && getDaysUntilExpiration(result.expiration_date)! < 90 ? "text-rose-400 font-bold" : "text-rose-100/60"
                              )}>
                                    {formatDate(result.expiration_date) || 'Unknown'}
                              </span>
                  </div>
                </div>

                         <div className="p-4 bg-rose-950/[0.05] border-t border-rose-500/10 flex items-center justify-between">
                            <span className="text-xs text-rose-500/50 font-mono">Target this asset?</span>
                  <Link
                    href={isAuthenticated ? '/terminal/hunt' : '/register'}
                                className="group relative px-6 py-3 bg-rose-500 hover:bg-rose-400 transition-colors text-black font-bold uppercase tracking-wider text-xs flex items-center gap-2"
                                style={{ clipPath: 'polygon(12px 0, 100% 0, 100% 100%, 0 100%, 0 12px)' }}
                  >
                                <span>Monitor Status</span>
                                <Crosshair className="w-3.5 h-3.5 group-hover:translate-x-1 transition-transform" />
                  </Link>
                         </div>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  )
}
