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

function LoginPage() {
  const { onLogin } = useAuth()
  const [credentials, setCredentials] = useState({
    username: '',
    password: ''
  })
  const [error, setError] = useState(null)
  const [loading, setLoading] = useState(false)

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

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

    try {
      const response = await authAPI.login(credentials)
      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)
      }
    } catch (err) {
      setError(err.message || '登录失败，请检查您的用户名和密码')
      console.error('Login 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>}
        <form onSubmit={handleSubmit} className="auth-form">
          <div className="form-group">
            <label htmlFor="username">用户名</label>
            <input
              type="text"
              id="username"
              name="username"
              value={credentials.username}
              onChange={handleChange}
              required
            />
          </div>
          <div className="form-group">
            <label htmlFor="password">密码</label>
            <input
              type="password"
              id="password"
              name="password"
              value={credentials.password}
              onChange={handleChange}
              required
            />
          </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({}, '', '/register')
              const event = new PopStateEvent('popstate')
              window.dispatchEvent(event)
            }}>
              立即注册
            </a>
          </p>
        </div>
      </div>
    </div>
  )
}

export default LoginPage