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 { PageMeta } from '@/components/common/PageMeta'
import { cn } from '@/lib/utils'

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

  useEffect(() => {
    if (!token) 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 (
    <>
    <PageMeta title="Verify Email" description="Verify your ResolutionFlow email address" />
    <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-brand-dark',
                '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-white/[0.04] border border-brand-border px-6 py-2 text-sm font-medium text-foreground',
                'hover:border-white/[0.12]'
              )}
            >
              Go to Dashboard
            </Link>
          </>
        )}
      </div>
    </div>
    </>
  )
}

export default VerifyEmailPage
