"use client"

import React, { useEffect, useState, Suspense } from 'react'
import { useSearchParams } from 'next/navigation'
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Loader2, CheckCircle2, XCircle, AlertCircle } from 'lucide-react'
import Link from 'next/link'

const VerifyEmailContent = () => {
    const searchParams = useSearchParams()
    const token = searchParams.get('token')
    const [status, setStatus] = useState<'loading' | 'success' | 'error' | 'invalid'>(token ? 'loading' : 'invalid')
    const [message, setMessage] = useState('')

    useEffect(() => {
        if (!token) {
            return
        }

        const verifyEmail = async () => {
            try {
                const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080'
                const response = await fetch(`${apiUrl}/api/v1/auth/verify-email?token=${token}`, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json'
                    }
                })

                // Backend responses might modify status
                const data = await response.json().catch(() => ({}))

                if (response.ok) {
                    setStatus('success')
                    setMessage(data.message || 'E-posta adresiniz başarıyla doğrulandı.')
                } else {
                    setStatus('error')
                    setMessage(data.error || data.message || 'Doğrulama işlemi başarısız oldu. Link süresi dolmuş veya geçersiz olabilir.')
                }
            } catch {
                setStatus('error')
                setMessage('Sunucu ile iletişim kurulurken bir hata oluştu.')
            }
        }

        verifyEmail()
    }, [token])

    return (
        <Card className="w-full max-w-md shadow-xl">
            <CardHeader className="space-y-1">
                <CardTitle className="text-2xl font-bold text-center">E-posta Doğrulama</CardTitle>
                <CardDescription className="text-center">
                    Hesap aktivasyon durumu
                </CardDescription>
            </CardHeader>
            <CardContent className="flex flex-col items-center justify-center py-6 space-y-4">
                {status === 'loading' && (
                    <>
                        <Loader2 className="h-16 w-16 animate-spin text-blue-500" />
                        <p className="text-gray-500">Doğrulanıyor, lütfen bekleyin...</p>
                    </>
                )}

                {status === 'success' && (
                    <>
                        <CheckCircle2 className="h-16 w-16 text-green-500" />
                        <div className="text-center space-y-2">
                            <h3 className="text-xl font-semibold text-green-600">Başarılı!</h3>
                            <p className="text-gray-600">{message}</p>
                        </div>
                    </>
                )}

                {status === 'error' && (
                    <>
                        <XCircle className="h-16 w-16 text-red-500" />
                        <div className="text-center space-y-2">
                            <h3 className="text-xl font-semibold text-red-600">Hata!</h3>
                            <p className="text-gray-600">{message}</p>
                        </div>
                    </>
                )}

                {status === 'invalid' && (
                    <>
                        <AlertCircle className="h-16 w-16 text-amber-500" />
                        <div className="text-center space-y-2">
                            <h3 className="text-xl font-semibold text-amber-600">Geçersiz Bağlantı</h3>
                            <p className="text-gray-600">Doğrulama bağlantısı geçersiz veya eksik.</p>
                        </div>
                    </>
                )}
            </CardContent>
            <CardFooter className="justify-center">
                {status === 'loading' ? (
                    <Button disabled variant="outline" className="w-full">İşlem Sürüyor</Button>
                ) : (
                    <Link href="/auth/login" className="w-full">
                        <Button className="w-full">
                            {status === 'success' ? 'Giriş Yap' : 'Giriş Sayfasına Dön'}
                        </Button>
                    </Link>
                )}
            </CardFooter>
        </Card>
    )
}

const VerifyEmailPage = () => {
    return (
        <div className="flex min-h-screen items-center justify-center bg-gray-100 p-4 dark:bg-gray-900">
            <Suspense fallback={
                <div className="flex items-center space-x-2">
                    <Loader2 className="h-6 w-6 animate-spin" />
                    <span>Yükleniyor...</span>
                </div>
            }>
                <VerifyEmailContent />
            </Suspense>
        </div>
    )
}

export default VerifyEmailPage
