'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-background relative overflow-hidden">
      {/* Background Effects */}
      <div className="fixed inset-0 pointer-events-none">
        <div className="absolute top-[-20%] left-1/2 -translate-x-1/2 w-[1200px] h-[800px] bg-accent/[0.03] rounded-full blur-[120px]" />
        <div className="absolute bottom-[-10%] right-[-10%] w-[600px] h-[600px] bg-accent/[0.02] rounded-full blur-[100px]" />
        <div 
          className="absolute inset-0 opacity-[0.015]"
          style={{
            backgroundImage: `linear-gradient(rgba(255,255,255,.1) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.1) 1px, transparent 1px)`,
            backgroundSize: '64px 64px',
          }}
        />
      </div>

      <Header />

      <main className="relative flex-1 pt-32 sm:pt-40 pb-20 sm:pb-28 px-4 sm:px-6">
        <div className="max-w-md mx-auto">
          <div className="text-center mb-8">
            <div className="inline-flex items-center gap-2 px-4 py-2 bg-accent/10 border border-accent/20 rounded-full mb-6">
              <Mail className="w-4 h-4 text-accent" />
              <span className="text-sm font-medium text-accent">Email Verification</span>
            </div>
          </div>

          <div className="bg-background-secondary/50 border border-border rounded-2xl p-8 backdrop-blur-sm">
            {status === 'loading' && (
              <div className="text-center py-8">
                <Loader2 className="w-12 h-12 text-accent animate-spin mx-auto mb-4" />
                <p className="text-lg text-foreground">Verifying your email...</p>
                <p className="text-sm text-foreground-muted mt-2">This will only take a moment</p>
              </div>
            )}

            {status === 'success' && (
              <div className="text-center py-8">
                <div className="w-16 h-16 bg-accent/10 rounded-full flex items-center justify-center mx-auto mb-4">
                  <CheckCircle className="w-8 h-8 text-accent" />
                </div>
                <h2 className="text-2xl font-display text-foreground mb-2">Email Verified!</h2>
                <p className="text-foreground-muted mb-6">{message}</p>
                <p className="text-sm text-foreground-subtle">Redirecting to login...</p>
              </div>
            )}

            {status === 'error' && (
              <div className="text-center py-8">
                <div className="w-16 h-16 bg-red-500/10 rounded-full flex items-center justify-center mx-auto mb-4">
                  <XCircle className="w-8 h-8 text-red-500" />
                </div>
                <h2 className="text-2xl font-display text-foreground mb-2">Verification Failed</h2>
                <p className="text-foreground-muted mb-6">{message}</p>
                
                {!resendSuccess ? (
                  <form onSubmit={handleResend} className="mt-6">
                    <p className="text-sm text-foreground-muted mb-4">
                      Need a new verification link?
                    </p>
                    <div className="flex gap-2">
                      <input
                        type="email"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        placeholder="Enter your email"
                        className="flex-1 px-4 py-3 bg-background border border-border rounded-xl text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50"
                        required
                      />
                      <button
                        type="submit"
                        disabled={resending}
                        className="px-4 py-3 bg-accent text-background rounded-xl font-medium hover:bg-accent-hover transition-all disabled:opacity-50"
                      >
                        {resending ? <Loader2 className="w-5 h-5 animate-spin" /> : 'Resend'}
                      </button>
                    </div>
                  </form>
                ) : (
                  <div className="mt-6 p-4 bg-accent/10 border border-accent/20 rounded-xl">
                    <p className="text-sm text-accent">
                      If an unverified account exists, a new verification link has been sent.
                    </p>
                  </div>
                )}
              </div>
            )}

            {status === 'no-token' && (
              <div className="text-center py-8">
                <div className="w-16 h-16 bg-foreground/5 rounded-full flex items-center justify-center mx-auto mb-4">
                  <Mail className="w-8 h-8 text-foreground-muted" />
                </div>
                <h2 className="text-2xl font-display text-foreground mb-2">Verify Your Email</h2>
                <p className="text-foreground-muted mb-6">
                  Check your inbox for a verification link, or request a new one below.
                </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="Enter your email"
                        className="flex-1 px-4 py-3 bg-background border border-border rounded-xl text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50"
                        required
                      />
                      <button
                        type="submit"
                        disabled={resending}
                        className="px-4 py-3 bg-accent text-background rounded-xl font-medium hover:bg-accent-hover transition-all disabled:opacity-50"
                      >
                        {resending ? <Loader2 className="w-5 h-5 animate-spin" /> : 'Send'}
                      </button>
                    </div>
                  </form>
                ) : (
                  <div className="mt-6 p-4 bg-accent/10 border border-accent/20 rounded-xl">
                    <p className="text-sm text-accent">
                      If an unverified account exists, a verification link has been sent.
                    </p>
                  </div>
                )}
              </div>
            )}

            <div className="mt-8 pt-6 border-t border-border text-center">
              <Link 
                href="/login" 
                className="inline-flex items-center gap-2 text-sm text-foreground-muted hover:text-accent transition-colors"
              >
                Back to Login
                <ArrowRight className="w-4 h-4" />
              </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-background">
        <Loader2 className="w-6 h-6 animate-spin text-accent" />
      </div>
    }>
      <VerifyEmailContent />
    </Suspense>
  )
}
