'use client'

import { Suspense, useEffect, useState } from 'react'
import { useSearchParams, useRouter } from 'next/navigation'
import { motion } from 'framer-motion'

function VerifyContent() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const token = searchParams.get('token')

  const [status, setStatus] = useState<'verifying' | 'success' | 'error'>('verifying')
  const [errorMsg, setErrorMsg] = useState('')

  useEffect(() => {
    if (!token) {
      setStatus('error')
      setErrorMsg('No access token provided.')
      return
    }

    async function verify() {
      try {
        // If the investor already has a valid session, skip token verification
        const sessionCheck = await fetch('/api/auth/me')
        if (sessionCheck.ok) {
          router.push('/')
          return
        }

        const res = await fetch('/api/auth/verify', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ token }),
        })

        if (res.ok) {
          setStatus('success')
          setTimeout(() => router.push('/'), 1000)
        } else {
          const data = await res.json()
          setStatus('error')
          setErrorMsg(data.error || 'Verification failed.')
        }
      } catch {
        setStatus('error')
        setErrorMsg('Network error. Please try again.')
      }
    }

    verify()
  }, [token, router])

  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.95 }}
      animate={{ opacity: 1, scale: 1 }}
      transition={{ duration: 0.4 }}
      className="relative z-10 text-center max-w-md mx-auto px-6"
    >
      <div className="bg-white/[0.03] border border-white/[0.06] rounded-2xl p-8 backdrop-blur-sm">
        {status === 'verifying' && (
          <>
            <div className="w-12 h-12 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin mx-auto mb-4" />
            <p className="text-white/60">Verifying your access link...</p>
          </>
        )}

        {status === 'success' && (
          <>
            <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-green-500/10 flex items-center justify-center">
              <svg className="w-8 h-8 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <p className="text-white/80 font-medium">Access verified!</p>
            <p className="text-white/40 text-sm mt-2">Redirecting to pitch deck...</p>
          </>
        )}

        {status === 'error' && (
          <>
            <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-red-500/10 flex items-center justify-center">
              <svg className="w-8 h-8 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </div>
            <p className="text-white/80 font-medium mb-2">Access Denied</p>
            <p className="text-white/50 text-sm">{errorMsg}</p>
            <a
              href="/auth"
              className="inline-block mt-6 text-indigo-400 text-sm hover:text-indigo-300 transition-colors"
            >
              Back to login
            </a>
          </>
        )}
      </div>
    </motion.div>
  )
}

export default function VerifyPage() {
  return (
    <div className="h-screen flex items-center justify-center bg-[#0a0a1a] relative overflow-hidden">
      <div className="absolute inset-0 bg-gradient-to-br from-indigo-950/30 via-transparent to-purple-950/20" />
      <Suspense
        fallback={
          <div className="relative z-10 text-center">
            <div className="w-12 h-12 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin mx-auto mb-4" />
            <p className="text-white/60">Loading...</p>
          </div>
        }
      >
        <VerifyContent />
      </Suspense>
    </div>
  )
}
