import { useState, useEffect } from 'react'
import { useSearchParams, useNavigate } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import { api } from '../utils/api'

export default function Verify() {
  const [searchParams] = useSearchParams()
  const token = searchParams.get('token')
  const navigate = useNavigate()
  const { setAuthFromToken } = useAuth()

  const [status, setStatus] = useState('loading') // loading | success | error | expired | already_verified
  const [error, setError] = useState(null)
  const [email, setEmail] = useState('')
  const [resending, setResending] = useState(false)
  const [resendSuccess, setResendSuccess] = useState(false)
  const [hasVerified, setHasVerified] = useState(false)

  useEffect(() => {
    if (hasVerified) return // Prevent React StrictMode double execution
    if (!token) {
      setStatus('error')
      setError('Kein Verifikations-Token gefunden')
      return
    }
    setHasVerified(true)
    const verify = async () => {
      try {
        const result = await api.verifyEmail(token)

        // Auto-login with returned token
        if (result.token && result.profile) {
          setAuthFromToken(result.token, result.profile)
          setStatus('success')

          // Redirect to dashboard after 1.5 seconds
          setTimeout(() => {
            window.location.href = '/'
          }, 1500)
        } else {
          setStatus('error')
          setError('Verifizierung erfolgreich, aber Login fehlgeschlagen')
        }
      } catch (err) {
        let errorMsg = err.message || 'Verifizierung fehlgeschlagen'

        // Try to parse JSON error response
        try {
          const parsed = JSON.parse(errorMsg)
          if (parsed.detail) errorMsg = parsed.detail
        } catch (e) {
          // Not JSON, use as-is
        }

        // Check if already verified or already used
        if (errorMsg.includes('bereits bestätigt') || errorMsg.includes('already verified') ||
            errorMsg.includes('bereits verwendet') || errorMsg.includes('already used')) {
          setStatus('already_verified')
          setError(errorMsg) // Show the actual message
          // Auto-redirect to dashboard after 3 seconds (let App.jsx decide login vs dashboard)
          setTimeout(() => { window.location.href = '/' }, 3000)
        }
        // Check if token expired
        else if (errorMsg.includes('abgelaufen') || errorMsg.includes('expired')) {
          setStatus('expired')
          setError(errorMsg)
        } else {
          setStatus('error')
          setError(errorMsg)
        }
      }
    }

    verify()
  }, [token, setAuthFromToken, navigate])

  const handleResend = async () => {
    if (!email.trim()) {
      setError('Bitte E-Mail-Adresse eingeben')
      return
    }

    setResending(true)
    setError(null)

    try {
      await api.resendVerification(email.trim().toLowerCase())
      setResendSuccess(true)
    } catch (err) {
      setError(err.message || 'E-Mail konnte nicht versendet werden')
    } finally {
      setResending(false)
    }
  }

  if (status === 'loading') {
    return (
      <div style={{
        maxWidth:420, margin:'0 auto', padding:'60px 20px',
        textAlign:'center'
      }}>
        <div className="spinner" style={{width:48, height:48, margin:'0 auto 24px'}}/>
        <h2>E-Mail wird bestätigt...</h2>
        <p style={{color:'var(--text2)'}}>Einen Moment bitte</p>
      </div>
    )
  }

  if (status === 'expired') {
    return (
      <div style={{
        maxWidth:420, margin:'0 auto', padding:'60px 20px',
        textAlign:'center'
      }}>
        <div style={{
          background:'#FFF4E6',
          border:'2px solid #F59E0B',
          borderRadius:16, padding:'40px 24px', marginBottom:24
        }}>
          <div style={{fontSize:48, marginBottom:16}}>⏰</div>
          <h2 style={{marginBottom:12, color:'#D97706'}}>
            Verifikations-Link abgelaufen
          </h2>
          <p style={{color:'var(--text2)', lineHeight:1.6, marginBottom:24}}>
            Dieser Link ist leider nicht mehr gültig. Bitte fordere eine neue Bestätigungs-E-Mail an.
          </p>

          {resendSuccess ? (
            <div style={{
              background:'var(--accent-light)',
              border:'1px solid var(--accent)',
              borderRadius:8, padding:'16px', marginBottom:16
            }}>
              <div style={{fontSize:32, marginBottom:8}}>✓</div>
              <div style={{fontWeight:600, color:'var(--accent-dark)', marginBottom:4}}>
                E-Mail versendet!
              </div>
              <p style={{fontSize:13, color:'var(--text2)', margin:0}}>
                Bitte prüfe dein Postfach.
              </p>
            </div>
          ) : (
            <>
              <input
                type="email"
                className="form-input"
                placeholder="deine@email.de"
                value={email}
                onChange={e => setEmail(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && handleResend()}
                style={{width:'100%', boxSizing:'border-box', marginBottom:12}}
                autoFocus
              />

              {error && (
                <div style={{
                  background:'rgba(216,90,48,0.1)',
                  color:'#D85A30',
                  fontSize:13,
                  padding:'10px 14px',
                  borderRadius:8,
                  marginBottom:12,
                  border:'1px solid rgba(216,90,48,0.2)'
                }}>
                  {error}
                </div>
              )}

              <button
                onClick={handleResend}
                disabled={resending || !email.trim()}
                className="btn btn-primary btn-full"
                style={{marginBottom:12}}
              >
                {resending ? (
                  <><div className="spinner" style={{width:14,height:14}}/> Sende...</>
                ) : (
                  'Neue Bestätigungs-E-Mail senden'
                )}
              </button>
            </>
          )}
        </div>

        <button
          onClick={() => navigate('/login')}
          style={{
            background:'none', border:'none', cursor:'pointer',
            fontSize:13, color:'var(--text3)', textDecoration:'underline'
          }}
        >
          Zurück zum Login
        </button>
      </div>
    )
  }

  if (status === 'already_verified') {
    return (
      <div style={{
        maxWidth:420, margin:'0 auto', padding:'60px 20px',
        textAlign:'center'
      }}>
        <div style={{
          background:'var(--accent-light)',
          border:'2px solid var(--accent)',
          borderRadius:16, padding:'40px 24px', marginBottom:24
        }}>
          <div style={{fontSize:48, marginBottom:16}}>✓</div>
          <h2 style={{marginBottom:12, color:'var(--accent-dark)'}}>
            E-Mail bereits bestätigt
          </h2>
          <p style={{color:'var(--text2)', lineHeight:1.6, marginBottom:error?12:24}}>
            {error || 'Deine E-Mail-Adresse wurde bereits verifiziert. Du kannst dich jetzt anmelden.'}
          </p>
          {!error && (
            <p style={{fontSize:13, color:'var(--text3)'}}>
              Du wirst gleich zum Login weitergeleitet...
            </p>
          )}
          {error && (
            <p style={{fontSize:13, color:'var(--text3)', marginTop:16}}>
              Du wirst gleich zum Login weitergeleitet...
            </p>
          )}
        </div>

        <button
          onClick={() => { window.location.href = '/' }}
          className="btn btn-primary btn-full"
        >
          Weiter zum Dashboard
        </button>
      </div>
    )
  }

  if (status === 'error') {
    return (
      <div style={{
        maxWidth:420, margin:'0 auto', padding:'60px 20px',
        textAlign:'center'
      }}>
        <div style={{
          background:'#FCEBEB',
          border:'2px solid #D85A30',
          borderRadius:16, padding:'40px 24px', marginBottom:24
        }}>
          <div style={{fontSize:48, marginBottom:16}}>✗</div>
          <h2 style={{marginBottom:12, color:'#D85A30'}}>
            Verifizierung fehlgeschlagen
          </h2>
          <p style={{color:'var(--text2)', lineHeight:1.6}}>
            {error}
          </p>
        </div>

        <button
          onClick={() => navigate('/register')}
          className="btn btn-primary btn-full"
          style={{marginBottom:12}}
        >
          Zur Registrierung
        </button>

        <button
          onClick={() => navigate('/login')}
          style={{
            background:'none', border:'none', cursor:'pointer',
            fontSize:13, color:'var(--text3)', textDecoration:'underline',
            width:'100%'
          }}
        >
          Zum Login
        </button>
      </div>
    )
  }

  // Success
  return (
    <div style={{
      maxWidth:420, margin:'0 auto', padding:'60px 20px',
      textAlign:'center'
    }}>
      <div style={{
        background:'var(--accent-light)',
        border:'2px solid var(--accent)',
        borderRadius:16, padding:'40px 24px', marginBottom:24
      }}>
        <div style={{fontSize:48, marginBottom:16}}>✓</div>
        <h2 style={{marginBottom:12, color:'var(--accent-dark)'}}>
          E-Mail bestätigt!
        </h2>
        <p style={{color:'var(--text2)', lineHeight:1.6}}>
          Dein Account wurde erfolgreich aktiviert.
          Du wirst gleich zum Dashboard weitergeleitet...
        </p>
      </div>

      <div className="spinner" style={{width:32, height:32, margin:'0 auto'}}/>
    </div>
  )
}
