import { useState, useEffect, useRef } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import api from '../api/client'

const TURNSTILE_SITE_KEY = window.__APP_CONFIG__?.TURNSTILE_SITE_KEY || ''

function TurnstileWidget({ onVerify }) {
  const ref = useRef(null)
  const widgetId = useRef(null)
  useEffect(() => {
    if (!TURNSTILE_SITE_KEY) return
    if (!document.getElementById('cf-turnstile-script')) {
      const s = document.createElement('script')
      s.id = 'cf-turnstile-script'
      s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js'
      s.async = true
      document.head.appendChild(s)
    }
    let timer
    const tryRender = () => {
      if (!window.turnstile || !ref.current) { timer = setTimeout(tryRender, 200); return }
      widgetId.current = window.turnstile.render(ref.current, { sitekey: TURNSTILE_SITE_KEY, callback: onVerify })
    }
    tryRender()
    return () => { clearTimeout(timer); if (widgetId.current != null) try { window.turnstile.remove(widgetId.current) } catch {} }
  }, [])
  if (!TURNSTILE_SITE_KEY) return null
  return <div ref={ref} style={{ margin: '8px 0' }} />
}

export default function LoginPage() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)
  const [unverified, setUnverified] = useState(false)
  const [resendSent, setResendSent] = useState(false)
  const [resending, setResending] = useState(false)
  const [turnstileToken, setTurnstileToken] = useState('')
  const [ssoConfig, setSsoConfig] = useState(null)
  const { login } = useAuth()
  const navigate = useNavigate()
  const searchParams = new URLSearchParams(window.location.search)
  const ssoError = searchParams.get('error')

  useEffect(() => {
    api.get('/auth/sso/config').then(r => setSsoConfig(r.data)).catch(() => {})
  }, [])

  const handleSubmit = async (e) => {
    e.preventDefault()
    setError('')
    setUnverified(false)
    setLoading(true)
    try {
      await login(email, password, turnstileToken)
      navigate('/')
    } catch (err) {
      if (err.response?.status === 403) {
        setUnverified(true)
      } else {
        const detail = err.response?.data?.detail
        if (typeof detail === 'string') setError(detail)
        else if (Array.isArray(detail)) setError(detail.some(e => e.loc?.includes('email')) ? 'Invalid email address.' : 'Please check your input and try again.')
        else setError('Login failed')
      }
    } finally {
      setLoading(false)
    }
  }

  const resendVerification = async () => {
    setResending(true)
    try {
      await api.post('/auth/resend-verification', { email })
      setResendSent(true)
    } catch {
      setResendSent(true) // always show success to avoid enumeration
    } finally {
      setResending(false)
    }
  }

  return (
    <div className="auth-page">
      <div className="auth-card">
        <h1>Sign In</h1>

        {unverified && !resendSent && (
          <div style={{ background: '#fffbeb', border: '1px solid #fcd34d', borderRadius: 8, padding: '14px 16px', marginBottom: 16 }}>
            <p style={{ margin: '0 0 10px', fontSize: '0.875rem', color: '#92400e', fontWeight: 500 }}>
              Your email is not verified. Please check your inbox.
            </p>
            <button className="btn btn-sm btn-primary" onClick={resendVerification} disabled={resending}>
              {resending ? 'Sending…' : 'Resend verification email'}
            </button>
          </div>
        )}

        {resendSent && (
          <div className="alert alert-success">
            Verification email sent — check your inbox and spam folder.
          </div>
        )}

        {error && <div className="alert alert-error">{error}</div>}
        {ssoError && <div className="alert alert-error">SSO login failed. Please try again.</div>}

        {ssoConfig?.sso_enabled && (
          <>
            <a href="/api/auth/sso/login" className="btn btn-secondary" style={{ width: '100%', display: 'block', textAlign: 'center', textDecoration: 'none', marginBottom: 16 }}>
              Sign in with {ssoConfig.provider_name}
            </a>
            {!ssoConfig.sso_only && <div style={{ textAlign: 'center', color: 'var(--text-muted)', fontSize: '0.82rem', margin: '12px 0' }}>or sign in with email</div>}
          </>
        )}

        {!ssoConfig?.sso_only && (
          <>
            <form onSubmit={handleSubmit}>
              <div className="form-group">
                <label>Email</label>
                <input type="email" value={email} onChange={e => setEmail(e.target.value)} required />
              </div>
              <div className="form-group">
                <label>Password</label>
                <input type="password" value={password} onChange={e => setPassword(e.target.value)} required />
              </div>
              <TurnstileWidget onVerify={setTurnstileToken} />
              <button className="btn btn-primary" style={{ width: '100%' }} disabled={loading || (TURNSTILE_SITE_KEY && !turnstileToken)}>
                {loading ? 'Signing in...' : 'Sign In'}
              </button>
            </form>
            <div className="auth-link">
              <Link to="/forgot-password" style={{ color: '#64748b', fontSize: '0.85rem' }}>Forgot password?</Link>
            </div>
            <div className="auth-link">
              Don't have an account? <Link to="/register">Sign up</Link>
            </div>
          </>
        )}
      </div>
    </div>
  )
}
