import React, { useState } from 'react'
import { useAuth } from '../context/AuthContext'
import { authAPI } from '../services/api'

function RegisterPage() {
  const { onLogin } = useAuth()
  const [userData, setUserData] = useState({
    username: '',
    email: '',
    password: ''
  })
  const [error, setError] = useState(null)
  const [loading, setLoading] = useState(false)
  const [success, setSuccess] = useState(false)

  // 处理表单输入变化
  const handleChange = (e) => {
    const { name, value } = e.target
    setUserData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  // 处理表单提交
  const handleSubmit = async (e) => {
    e.preventDefault()
    setLoading(true)
    setError(null)
    setSuccess(false)

    try {
      const response = await authAPI.register(userData)
      if (response.token) {
        // 存储用户信息
        localStorage.setItem('user', JSON.stringify(response.user))
        
        // 更新认证状态
        onLogin(response.user, response.token)
        
        // 导航到首页
        window.history.pushState({}, '', '/')
        const event = new PopStateEvent('popstate')
        window.dispatchEvent(event)
      } else {
        setSuccess(true)
        // 注册成功但不自动登录
        setUserData({
          username: '',
          email: '',
          password: ''
        })
      }
    } catch (err) {
      setError(err.message || '注册失败，请稍后再试')
      console.error('Registration error:', err)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="main-content auth-page">
      <div className="auth-container">
        <h1>注册</h1>
        {error && <div className="error-message">{error}</div>}
        {success && <div className="success-message">注册成功！请登录。</div>}
        
        <form onSubmit={handleSubmit} className="auth-form">
          <div className="form-group">
            <label htmlFor="username">用户名</label>
            <input
              type="text"
              id="username"
              name="username"
              value={userData.username}
              onChange={handleChange}
              required
            />
          </div>
          <div className="form-group">
            <label htmlFor="email">邮箱</label>
            <input
              type="email"
              id="email"
              name="email"
              value={userData.email}
              onChange={handleChange}
              required
            />
          </div>
          <div className="form-group">
            <label htmlFor="password">密码</label>
            <input
              type="password"
              id="password"
              name="password"
              value={userData.password}
              onChange={handleChange}
              required
              minLength="6"
            />
          </div>
          <button 
            type="submit" 
            className="btn btn-primary btn-block"
            disabled={loading}
          >
            {loading ? '注册中...' : '注册'}
          </button>
        </form>
        <div className="auth-links">
          <p>已有账号？ 
            <a href="#" onClick={(e) => {
              e.preventDefault()
              window.history.pushState({}, '', '/login')
              const event = new PopStateEvent('popstate')
              window.dispatchEvent(event)
            }}>
              立即登录
            </a>
          </p>
        </div>
      </div>
    </div>
  )
}

export default RegisterPage