import { useState } from 'react'
import { Link } from 'react-router-dom'

export default function RegisterPage() {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [loading, setLoading] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    setSuccess('')

    if (password !== confirmPassword) {
      setError('两次密码不一致')
      return
    }

    setLoading(true)

    try {
      const res = await fetch('/api/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
      })

      const data = await res.json()

      if (res.ok) {
        setSuccess('注册成功，请登录')
        setTimeout(() => {
          window.location.href = '/login'
        }, 1500)
      } else {
        setError(data.error || '注册失败')
      }
    } catch {
      setError('网络错误，请重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="container-sm">
      <div className="text-center mb-6" style={{ paddingTop: '80px' }}>
        <div className="logo" style={{ width: '48px', height: '48px', fontSize: '20px', margin: '0 auto 16px' }}>
          AC
        </div>
        <h1 className="page-title">AntiCaptcha</h1>
        <p className="text-secondary">验证码识别服务平台</p>
      </div>

      <div className="card fade-in">
        <h2 className="text-lg mb-4 text-center">注册</h2>
        
        <form onSubmit={handleSubmit}>
          <div className="form-group">
            <label className="label">用户名</label>
            <input
              type="text"
              className="input"
              value={username}
              onChange={e => setUsername(e.target.value)}
              placeholder="请输入用户名"
              required
            />
          </div>

          <div className="form-group">
            <label className="label">密码</label>
            <input
              type="password"
              className="input"
              value={password}
              onChange={e => setPassword(e.target.value)}
              placeholder="请输入密码"
              required
            />
          </div>

          <div className="form-group">
            <label className="label">确认密码</label>
            <input
              type="password"
              className="input"
              value={confirmPassword}
              onChange={e => setConfirmPassword(e.target.value)}
              placeholder="请再次输入密码"
              required
            />
          </div>

          {error && <div className="error mb-4">{error}</div>}
          {success && <div className="success mb-4">{success}</div>}

          <button type="submit" className="button button-block button-lg" disabled={loading}>
            {loading ? '注册中...' : '注册'}
          </button>
        </form>

        <div className="text-center mt-4">
          <span className="text-secondary">已有账号？</span>{' '}
          <Link to="/login">立即登录</Link>
        </div>
      </div>
    </div>
  )
}