'use client'

import { useState } from 'react'
import { Search, Check, X, Loader2, Calendar, Building2, Server, Plus, AlertTriangle, Clock } 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
}

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)

  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">
        {/* Glow effect container - always visible, stronger on focus */}
        <div className={clsx(
          "absolute -inset-1 rounded-2xl transition-opacity duration-500",
          isFocused ? "opacity-100" : "opacity-60"
        )}>
          <div className="absolute inset-0 bg-gradient-to-r from-accent/30 via-accent/20 to-accent/30 rounded-2xl blur-xl" />
        </div>
        
        {/* Input container */}
        <div className={clsx(
          "relative bg-background-secondary rounded-2xl transition-all duration-300 shadow-2xl shadow-accent/10",
          isFocused ? "ring-2 ring-accent/50" : "ring-1 ring-accent/30"
        )}>
          <input
            type="text"
            value={domain}
            onChange={(e) => setDomain(e.target.value)}
            onFocus={() => setIsFocused(true)}
            onBlur={() => setIsFocused(false)}
            placeholder="Hunt any domain..."
            className="w-full px-5 sm:px-7 py-5 sm:py-6 pr-32 sm:pr-40 bg-transparent rounded-2xl
                       text-base sm:text-lg text-foreground placeholder:text-foreground-subtle
                       focus:outline-none transition-colors"
          />
          <button
            type="submit"
            disabled={loading || !domain.trim()}
            className="absolute right-2.5 sm:right-3 top-1/2 -translate-y-1/2
                       px-5 sm:px-7 py-3 sm:py-3.5 bg-accent text-background text-sm sm:text-base font-semibold rounded-xl
                       hover:bg-accent-hover active:scale-[0.98] shadow-lg shadow-accent/25
                       disabled:opacity-40 disabled:cursor-not-allowed
                       transition-all duration-300 flex items-center gap-2"
          >
            {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>
        
        <p className="mt-3 sm:mt-4 text-center text-xs sm:text-sm text-foreground-subtle">
          Try <span className="text-accent/70">dream.com</span>, <span className="text-accent/70">startup.io</span>, or <span className="text-accent/70">next.ai</span>
        </p>
      </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="rounded-xl sm:rounded-2xl border border-accent/30 overflow-hidden text-left">
              {/* Header */}
              <div className="p-5 sm:p-6 bg-gradient-to-br from-accent/10 via-accent/5 to-transparent">
                <div className="flex items-center gap-4">
                  <div className="w-11 h-11 rounded-xl bg-accent/15 border border-accent/20 flex items-center justify-center shrink-0">
                    <Check className="w-5 h-5 text-accent" strokeWidth={2.5} />
                  </div>
                  <div className="flex-1 min-w-0 text-left">
                    <p className="font-mono text-body sm:text-body-lg font-medium text-foreground text-left">
                      {result.domain}
                    </p>
                    <p className="text-body-sm text-accent text-left">
                      It&apos;s yours for the taking.
                    </p>
                  </div>
                  <span className="px-3 py-1.5 bg-accent text-background text-ui-sm font-medium rounded-lg shrink-0">
                    Available
                  </span>
                </div>
              </div>
              
              {/* CTA */}
              <div className="p-4 sm:p-5 bg-background-secondary border-t border-accent/20">
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4">
                  <p className="text-body-sm text-foreground-muted text-left">
                    Grab it now or track it in your watchlist.
                  </p>
                  <Link
                    href={isAuthenticated ? '/terminal/radar' : '/register'}
                    className="shrink-0 flex items-center justify-center sm:justify-start gap-2 px-5 py-2.5
                               bg-accent text-background text-ui font-medium rounded-lg
                               hover:bg-accent-hover transition-all duration-300"
                  >
                    <Plus className="w-4 h-4" />
                    <span>Track This</span>
                  </Link>
                </div>
              </div>
            </div>
          ) : (
            /* ========== TAKEN DOMAIN ========== */
            <div className="rounded-xl sm:rounded-2xl border border-border overflow-hidden bg-background-secondary text-left">
              {/* Header */}
              <div className="p-5 sm:p-6 border-b border-border">
                <div className="flex items-center gap-4">
                  <div className="w-11 h-11 rounded-xl bg-danger-muted border border-danger/20 flex items-center justify-center shrink-0">
                    <X className="w-5 h-5 text-danger" strokeWidth={2} />
                  </div>
                  <div className="flex-1 min-w-0 text-left">
                    <p className="font-mono text-body sm:text-body-lg font-medium text-foreground text-left">
                      {result.domain}
                    </p>
                    <p className="text-body-sm text-foreground-muted text-left">
                      Someone got there first. For now.
                    </p>
                  </div>
                  <span className="px-3 py-1.5 bg-background-tertiary text-foreground-muted text-ui-sm font-medium rounded-lg border border-border shrink-0">
                    Taken
                  </span>
                </div>
              </div>

              {/* Domain Info */}
              {(result.registrar || result.expiration_date) && (
                <div className="p-5 sm:p-6 border-b border-border bg-background-tertiary/30">
                  <div className="grid sm:grid-cols-2 gap-5">
                    {result.registrar && (
                      <div className="flex items-start gap-3 text-left">
                        <div className="w-9 h-9 bg-background-tertiary rounded-lg flex items-center justify-center shrink-0">
                          <Building2 className="w-4 h-4 text-foreground-subtle" />
                        </div>
                        <div className="min-w-0 text-left">
                          <p className="text-ui-sm text-foreground-subtle uppercase tracking-wider mb-0.5 text-left">Registrar</p>
                          <p className="text-body-sm text-foreground truncate text-left">{result.registrar}</p>
                        </div>
                      </div>
                    )}
                    
                    {result.expiration_date && (
                      <div className="flex items-start gap-3 text-left">
                        <div className={clsx(
                          "w-9 h-9 rounded-lg flex items-center justify-center shrink-0",
                          getDaysUntilExpiration(result.expiration_date) !== null && 
                          getDaysUntilExpiration(result.expiration_date)! <= 90
                            ? "bg-warning-muted"
                            : "bg-background-tertiary"
                        )}>
                          <Calendar className={clsx(
                            "w-4 h-4",
                            getDaysUntilExpiration(result.expiration_date) !== null && 
                            getDaysUntilExpiration(result.expiration_date)! <= 90
                              ? "text-warning"
                              : "text-foreground-subtle"
                          )} />
                        </div>
                        <div className="min-w-0 text-left">
                          <p className="text-ui-sm text-foreground-subtle uppercase tracking-wider mb-0.5 text-left">Expires</p>
                          <p className="text-body-sm text-foreground text-left">
                            {formatDate(result.expiration_date)}
                            {getDaysUntilExpiration(result.expiration_date) !== null && (
                              <span className={clsx(
                                "ml-2 text-ui-sm",
                                getDaysUntilExpiration(result.expiration_date)! <= 30
                                  ? "text-danger"
                                  : getDaysUntilExpiration(result.expiration_date)! <= 90
                                    ? "text-warning"
                                    : "text-foreground-subtle"
                              )}>
                                ({getDaysUntilExpiration(result.expiration_date)} days)
                              </span>
                            )}
                          </p>
                        </div>
                      </div>
                    )}

                    {result.name_servers && result.name_servers.length > 0 && (
                      <div className="flex items-start gap-3 sm:col-span-2 text-left">
                        <div className="w-9 h-9 bg-background-tertiary rounded-lg flex items-center justify-center shrink-0">
                          <Server className="w-4 h-4 text-foreground-subtle" />
                        </div>
                        <div className="min-w-0 text-left">
                          <p className="text-ui-sm text-foreground-subtle uppercase tracking-wider mb-0.5 text-left">Name Servers</p>
                          <p className="text-body-sm font-mono text-foreground-muted truncate text-left">
                            {result.name_servers.slice(0, 2).join(' · ')}
                            {result.name_servers.length > 2 && (
                              <span className="text-foreground-subtle"> +{result.name_servers.length - 2}</span>
                            )}
                          </p>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )}
              
              {/* Watchlist CTA */}
              <div className="p-4 sm:p-5">
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4">
                  <div className="flex items-center gap-2 text-body-sm text-foreground-muted text-left">
                    <Clock className="w-4 h-4 text-foreground-subtle shrink-0" />
                    <span className="text-left">We&apos;ll alert you the moment it drops.</span>
                  </div>
                  <Link
                    href={isAuthenticated ? '/terminal/radar' : '/register'}
                    className="shrink-0 flex items-center justify-center sm:justify-start gap-2 px-4 py-2.5
                               bg-background-tertiary text-foreground text-ui font-medium rounded-lg 
                               border border-border hover:border-border-hover transition-all duration-300"
                  >
                    <Plus className="w-4 h-4" />
                    <span>Track This</span>
                  </Link>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  )
}
