import { useState, useEffect } from 'react'
import { Link, useSearchParams, useNavigate } from 'react-router-dom'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { auth } from '@/lib/appwrite'
import { Mail, Loader2, CheckCircle, XCircle, RefreshCw } from 'lucide-react'

export function VerifyEmail() {
  const [searchParams] = useSearchParams()
  const navigate = useNavigate()
  
  const userId = searchParams.get('userId')
  const secret = searchParams.get('secret')

  const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading')
  const [error, setError] = useState('')

  useEffect(() => {
    verifyEmail()
  }, [userId, secret])

  const verifyEmail = async () => {
    if (!userId || !secret) {
      setStatus('error')
      setError('Ungültiger Verifizierungslink')
      return
    }

    try {
      await auth.verifyEmail(userId, secret)
      setStatus('success')
    } catch (err: unknown) {
      setStatus('error')
      setError(err instanceof Error ? err.message : 'Fehler bei der Verifizierung')
    }
  }

  const handleResendVerification = async () => {
    setStatus('loading')
    setError('')

    try {
      await auth.sendVerification()
      setError('')
      alert('Neue Verifizierungs-E-Mail wurde gesendet!')
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Fehler beim Senden')
    } finally {
      setStatus('error')
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Logo */}
        <Link to="/" className="flex items-center justify-center mb-8 leading-none">
          <img 
            src="/logo.png" 
            alt="MailFlow Logo" 
            className="w-24 h-24 rounded-xl object-contain pr-[5px] block"
            style={{ display: 'block', margin: 0, padding: 0 }}
          />
          <span className="text-xl font-bold text-slate-900 dark:text-slate-100 ml-[5px]">
            Mail<span className="text-primary-600 dark:text-primary-400">Flow</span>
          </span>
        </Link>

        <Card className="shadow-xl border-0 dark:bg-slate-800 dark:border-slate-700">
          <CardHeader className="text-center pb-2">
            <CardTitle className="text-2xl dark:text-slate-100">
              {status === 'loading' && 'E-Mail wird verifiziert...'}
              {status === 'success' && 'E-Mail verifiziert!'}
              {status === 'error' && 'Verifizierung fehlgeschlagen'}
            </CardTitle>
            <CardDescription className="dark:text-slate-400">
              {status === 'loading' && 'Bitte warte einen Moment.'}
              {status === 'success' && 'Deine E-Mail-Adresse wurde erfolgreich bestätigt.'}
              {status === 'error' && error}
            </CardDescription>
          </CardHeader>
          <CardContent>
            {status === 'loading' && (
              <div className="flex flex-col items-center py-12">
                <Loader2 className="w-12 h-12 animate-spin text-primary-500 dark:text-primary-400 mb-4" />
                <p className="text-slate-500 dark:text-slate-400">Verifizierung läuft...</p>
              </div>
            )}

            {status === 'success' && (
              <div className="text-center py-8">
                <div className="w-20 h-20 mx-auto mb-6 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
                  <CheckCircle className="w-10 h-10 text-green-600 dark:text-green-400" />
                </div>
                
                <div className="space-y-4">
                  <div className="p-4 bg-green-50 dark:bg-green-900/30 border border-green-100 dark:border-green-800 rounded-xl">
                    <p className="text-green-700 dark:text-green-300 font-medium">
                      Dein Account ist jetzt vollständig aktiviert!
                    </p>
                  </div>

                  <p className="text-slate-600 dark:text-slate-400">
                    Du kannst jetzt alle Features von MailFlow nutzen.
                  </p>

                  <Button onClick={() => navigate('/dashboard')} className="w-full">
                    Zum Dashboard
                  </Button>
                </div>
              </div>
            )}

            {status === 'error' && (
              <div className="text-center py-8">
                <div className="w-20 h-20 mx-auto mb-6 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
                  <XCircle className="w-10 h-10 text-red-600 dark:text-red-400" />
                </div>

                <div className="space-y-4">
                  <div className="p-4 bg-red-50 dark:bg-red-900/30 border border-red-100 dark:border-red-800 rounded-xl">
                    <p className="text-red-700 dark:text-red-300">
                      {error || 'Der Verifizierungslink ist ungültig oder abgelaufen.'}
                    </p>
                  </div>

                  <p className="text-slate-600 dark:text-slate-400 text-sm">
                    Falls dein Link abgelaufen ist, kannst du eine neue Verifizierungs-E-Mail anfordern.
                  </p>

                  <div className="space-y-3">
                    <Button onClick={handleResendVerification} variant="outline" className="w-full">
                      <RefreshCw className="w-4 h-4 mr-2" />
                      Neue E-Mail senden
                    </Button>
                    
                    <Button onClick={() => navigate('/login')} variant="ghost" className="w-full">
                      Zurück zum Login
                    </Button>
                  </div>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Help text */}
        <p className="text-center text-sm text-slate-500 dark:text-slate-400 mt-6">
          Probleme? Kontaktiere uns unter{' '}
          <a href="mailto:support@mailflow.de" className="text-primary-600 dark:text-primary-400 hover:underline">
            support@mailflow.de
          </a>
        </p>
      </div>
    </div>
  )
}
