import { useEffect, useState } from 'react'
import { useSearchParams, Link } from 'react-router-dom'
import { CheckCircle2, XCircle, Loader2 } from 'lucide-react'
import { authApi } from '@/api/auth'
import { cn } from '@/lib/utils'

export function VerifyEmailPage() {
  const [searchParams] = useSearchParams()
  const token = searchParams.get('token')
  const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading')
  const [errorMessage, setErrorMessage] = useState('')

  useEffect(() => {
    if (!token) {
      setStatus('error')
      setErrorMessage('No verification token provided')
      return
    }

    authApi.verifyEmail(token)
      .then(() => setStatus('success'))
      .catch((err) => {
        setStatus('error')
        const detail = (err as { response?: { data?: { detail?: string } } }).response?.data?.detail
        setErrorMessage(detail ?? 'Verification failed')
      })
  }, [token])

  return (
    <div className="flex min-h-screen items-center justify-center bg-background p-4">
      <div className="glass-card-static w-full max-w-md p-8 text-center">
        {status === 'loading' && (
          <>
            <Loader2 className="mx-auto h-12 w-12 animate-spin text-primary" />
            <p className="mt-4 text-foreground">Verifying your email...</p>
          </>
        )}
        {status === 'success' && (
          <>
            <CheckCircle2 className="mx-auto h-12 w-12 text-emerald-400" />
            <h1 className="mt-4 text-xl font-bold font-heading text-foreground">Email Verified</h1>
            <p className="mt-2 text-muted-foreground">Your email has been successfully verified.</p>
            <Link
              to="/"
              className={cn(
                'mt-6 inline-flex items-center rounded-[10px] bg-gradient-brand px-6 py-2 text-sm font-semibold text-[#101114]',
                'shadow-lg shadow-primary/20 hover:opacity-90'
              )}
            >
              Go to Dashboard
            </Link>
          </>
        )}
        {status === 'error' && (
          <>
            <XCircle className="mx-auto h-12 w-12 text-rose-500" />
            <h1 className="mt-4 text-xl font-bold font-heading text-foreground">Verification Failed</h1>
            <p className="mt-2 text-muted-foreground">{errorMessage}</p>
            <Link
              to="/"
              className={cn(
                'mt-6 inline-flex items-center rounded-[10px] bg-[rgba(255,255,255,0.04)] border border-[rgba(255,255,255,0.06)] px-6 py-2 text-sm font-medium text-foreground',
                'hover:border-[rgba(255,255,255,0.12)]'
              )}
            >
              Go to Dashboard
            </Link>
          </>
        )}
      </div>
    </div>
  )
}

export default VerifyEmailPage
