'use client'

import { useEffect, useState, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import Link from 'next/link'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import { api } from '@/lib/api'
import { CheckCircle, XCircle, Loader2, Mail, ArrowRight } from 'lucide-react'

function VerifyEmailContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const token = searchParams.get('token')
  
  const [status, setStatus] = useState<'loading' | 'success' | 'error' | 'no-token'>('loading')
  const [message, setMessage] = useState('')
  const [email, setEmail] = useState('')
  const [resending, setResending] = useState(false)
  const [resendSuccess, setResendSuccess] = useState(false)

  useEffect(() => {
    if (!token) {
      setStatus('no-token')
      return
    }

    verifyEmail()
  }, [token])

  const verifyEmail = async () => {
    try {
      const response = await api.verifyEmail(token!)
      setStatus('success')
      setMessage(response.message)
      
      // Redirect to login after 3 seconds
      setTimeout(() => {
        router.push('/login?verified=true')
      }, 3000)
    } catch (err: any) {
      setStatus('error')
      setMessage(err.message || 'Verification failed. The link may be expired.')
    }
  }

  const handleResend = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!email) return

    setResending(true)
    try {
      await api.resendVerification(email)
      setResendSuccess(true)
    } catch (err) {
      // Always show success for security
      setResendSuccess(true)
    } finally {
      setResending(false)
    }
  }

  return (
    <div className="min-h-screen bg-[#020202] text-white relative overflow-x-hidden selection:bg-accent/30 selection:text-white">
      {/* Living Background Atmosphere */}
      <div className="fixed inset-0 pointer-events-none overflow-hidden">
        <div className="absolute inset-0 bg-[url('/noise.png')] opacity-[0.04] mix-blend-overlay z-10" />
        
        {/* Animated Orbs */}
        <div className="absolute top-[20%] left-[50%] -translate-x-1/2 w-[60vw] h-[60vw] bg-accent/5 rounded-full blur-[150px] animate-pulse-slow mix-blend-screen" />
        <div className="absolute bottom-[-20%] right-[-10%] w-[50vw] h-[50vw] bg-purple-500/5 rounded-full blur-[120px] animate-blob mix-blend-screen" />
        
        {/* Grid Overlay */}
        <div 
          className="absolute inset-0 opacity-[0.03] z-0"
          style={{
            backgroundImage: `linear-gradient(rgba(255,255,255,0.3) 0.5px, transparent 0.5px), linear-gradient(90deg, rgba(255,255,255,0.3) 0.5px, transparent 0.5px)`,
            backgroundSize: '40px 40px',
          }}
        />
      </div>

      <Header />

      <main className="min-h-screen flex items-center justify-center px-4 sm:px-6 py-20 relative z-10">
        <div className="w-full max-w-[450px] animate-fade-in">
          
          <div className="bg-[#050505] border border-white/10 relative p-8 sm:p-10 shadow-2xl">
             {/* Tech Corners */}
             <div className="absolute -top-px -left-px w-4 h-4 border-t border-l border-white/40" />
             <div className="absolute -top-px -right-px w-4 h-4 border-t border-r border-white/40" />
             <div className="absolute -bottom-px -left-px w-4 h-4 border-b border-l border-white/40" />
             <div className="absolute -bottom-px -right-px w-4 h-4 border-b border-r border-white/40" />

            {status === 'loading' && (
              <div className="text-center py-8">
                <Loader2 className="w-12 h-12 text-accent animate-spin mx-auto mb-6" />
                <h2 className="font-display text-2xl text-white mb-2">Verifying Credentials</h2>
                <p className="text-xs font-mono text-white/40">Secure handshake in progress...</p>
              </div>
            )}

            {status === 'success' && (
              <div className="text-center py-8">
                <div className="w-16 h-16 bg-accent/10 border border-accent/20 flex items-center justify-center mx-auto mb-6 rounded-none">
                  <CheckCircle className="w-8 h-8 text-accent" />
                </div>
                <h2 className="font-display text-2xl text-white mb-2">Access Granted</h2>
                <p className="text-sm font-mono text-white/50 mb-6">{message}</p>
                <div className="inline-flex items-center gap-2 px-4 py-2 bg-white/5 border border-white/10 text-xs font-mono text-white/60">
                   <Loader2 className="w-3 h-3 animate-spin" /> Redirecting to Terminal...
                </div>
              </div>
            )}

            {status === 'error' && (
              <div className="text-center py-8">
                <div className="w-16 h-16 bg-red-500/10 border border-red-500/20 flex items-center justify-center mx-auto mb-6 rounded-none">
                  <XCircle className="w-8 h-8 text-red-500" />
                </div>
                <h2 className="font-display text-2xl text-white mb-2">Verification Failed</h2>
                <p className="text-sm font-mono text-white/50 mb-8">{message}</p>
                
                {!resendSuccess ? (
                  <form onSubmit={handleResend} className="mt-6">
                    <p className="text-[10px] font-mono text-white/40 uppercase tracking-widest mb-4">
                      Request New Link
                    </p>
                    <div className="flex gap-2">
                      <input
                        type="email"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        placeholder="EMAIL ADDRESS"
                        className="flex-1 bg-[#0A0A0A] border border-white/10 px-4 py-3 text-white font-mono text-sm placeholder:text-white/20 focus:outline-none focus:border-accent transition-all rounded-none"
                        required
                      />
                      <button
                        type="submit"
                        disabled={resending}
                        className="px-4 py-3 bg-white text-black text-xs font-bold uppercase tracking-wider hover:bg-accent transition-all disabled:opacity-50"
                      >
                        {resending ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Send'}
                      </button>
                    </div>
                  </form>
                ) : (
                  <div className="mt-6 p-4 bg-accent/5 border border-accent/20">
                    <p className="text-xs font-mono text-accent">
                      New verification link dispatched.
                    </p>
                  </div>
                )}
              </div>
            )}

            {status === 'no-token' && (
              <div className="text-center py-8">
                <div className="w-16 h-16 bg-white/5 border border-white/10 flex items-center justify-center mx-auto mb-6 rounded-none">
                  <Mail className="w-8 h-8 text-white/40" />
                </div>
                <h2 className="font-display text-2xl text-white mb-2">Verify Identity</h2>
                <p className="text-sm font-mono text-white/50 mb-8">
                  Check your inbox for the verification link.
                </p>
                
                {!resendSuccess ? (
                  <form onSubmit={handleResend} className="mt-6">
                    <div className="flex gap-2">
                      <input
                        type="email"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        placeholder="EMAIL ADDRESS"
                        className="flex-1 bg-[#0A0A0A] border border-white/10 px-4 py-3 text-white font-mono text-sm placeholder:text-white/20 focus:outline-none focus:border-accent transition-all rounded-none"
                        required
                      />
                      <button
                        type="submit"
                        disabled={resending}
                        className="px-4 py-3 bg-white text-black text-xs font-bold uppercase tracking-wider hover:bg-accent transition-all disabled:opacity-50"
                      >
                        {resending ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Send'}
                      </button>
                    </div>
                  </form>
                ) : (
                  <div className="mt-6 p-4 bg-accent/5 border border-accent/20">
                    <p className="text-xs font-mono text-accent">
                      Link dispatched. Check inbox.
                    </p>
                  </div>
                )}
              </div>
            )}

            <div className="mt-8 pt-8 border-t border-white/10 text-center">
              <Link 
                href="/login" 
                className="inline-flex items-center gap-2 text-xs font-mono text-white/40 hover:text-white transition-colors uppercase tracking-wider"
              >
                <ArrowRight className="w-3 h-3 rotate-180" />
                Return to Login
              </Link>
            </div>
          </div>
        </div>
      </main>

      <Footer />
    </div>
  )
}

export default function VerifyEmailPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex items-center justify-center bg-[#020202]">
        <div className="w-8 h-8 border-2 border-white/10 border-t-accent rounded-full animate-spin" />
      </div>
    }>
      <VerifyEmailContent />
    </Suspense>
  )
}
