import { useState, useEffect } from 'react'
import { useSearchParams, Link } from 'react-router-dom'
import api from '../api/client'

export default function VerifyEmailPage() {
  const [searchParams] = useSearchParams()
  const token = searchParams.get('token')
  const [status, setStatus] = useState('verifying') // verifying | success | error
  const [message, setMessage] = useState('')

  useEffect(() => {
    if (!token) { setStatus('error'); setMessage('No verification token provided.'); return }
    api.get(`/auth/verify-email?token=${token}`)
      .then(res => { setStatus('success'); setMessage(res.data.message) })
      .catch(err => { setStatus('error'); setMessage(err.response?.data?.detail || 'Verification failed.') })
  }, [token])

  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f1f5f9' }}>
      <div className="card" style={{ maxWidth: 420, width: '100%', textAlign: 'center' }}>
        {status === 'verifying' && (
          <><div className="spinner" style={{ margin: '0 auto 16px' }}></div><p>Verifying your email...</p></>
        )}
        {status === 'success' && (
          <>
            <div style={{ fontSize: '3rem', marginBottom: 12 }}>✅</div>
            <h2 style={{ color: '#166534', marginBottom: 8 }}>Email Verified!</h2>
            <p style={{ color: '#64748b', marginBottom: 24 }}>{message}</p>
            <Link to="/login" className="btn btn-primary">Log In</Link>
          </>
        )}
        {status === 'error' && (
          <>
            <div style={{ fontSize: '3rem', marginBottom: 12 }}>❌</div>
            <h2 style={{ color: '#dc2626', marginBottom: 8 }}>Verification Failed</h2>
            <p style={{ color: '#64748b', marginBottom: 24 }}>{message}</p>
            <Link to="/login" className="btn btn-secondary">Back to Login</Link>
          </>
        )}
      </div>
    </div>
  )
}
