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

export function AuthCallback() {
  const [searchParams] = useSearchParams()
  const navigate = useNavigate()
  const { login } = useAuth()
  const [error, setError] = useState('')

  useEffect(() => {
    const code = searchParams.get('code')
    if (!code) {
      setError('缺少授权码')
      setTimeout(() => navigate('/login'), 3000)
      return
    }

    fetch('/api/oauth/exchange-code', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ code }),
    })
      .then(r => r.json())
      .then(result => {
        if (result.code === '000000') {
          login(result.data.token, result.data.refresh_token, result.data.user)
          navigate('/')
        } else {
          setError(result.message || '登录失败')
          setTimeout(() => navigate('/login'), 3000)
        }
      })
      .catch(() => {
        setError('网络错误，请重试')
        setTimeout(() => navigate('/login'), 3000)
      })
  }, [searchParams, login, navigate])

  if (error) {
    return (
      <div style={{ padding: 40, textAlign: 'center', background: '#f0fdfa', minHeight: '100vh', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', color: '#134e4a' }}>
        <h2>登录失败</h2>
        <p style={{ color: '#f43f5e' }}>{error}</p>
        <p style={{ color: '#94a3b8', fontSize: 14 }}>3秒后跳转到登录页...</p>
      </div>
    )
  }

  return (
    <div style={{ padding: 40, textAlign: 'center', background: '#f0fdfa', minHeight: '100vh', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', color: '#134e4a' }}>
      <h2>正在登录，请稍候...</h2>
    </div>
  )
}
