/**
 * 注册页面组件
 * 用户注册界面，展示如何调用后端注册API
 * 
 * 【重要说明】：
 * 1. 使用Ant Design表单组件构建专业注册界面
 * 2. 通过AuthContext调用后端注册API
 * 3. 表单验证和错误处理
 * 4. 注册成功后跳转到登录页面
 */

import React, { useState } from 'react';
import { Form, Input, Button, Card, Typography, Divider, message } from 'antd';
import { UserOutlined, LockOutlined, UserAddOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';

const { Title, Text } = Typography;

/**
 * 注册页面组件
 */
const RegisterPage = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const { register } = useAuth();

  /**
   * 处理注册表单提交
   * 【API调用标注】这里调用后端注册接口
   */
  const handleRegister = async (values) => {
    try {
      setLoading(true);
      
      // 【API调用标注】调用后端注册接口
      // 后端接口: POST /auth/register
      // 对应后端文件: backend/api/auth_api.py -> register()
      const result = await register({
        username: values.username,
        password: values.password,
        is_admin: false, // 默认注册普通用户
      });

      if (result.success) {
        message.success('注册成功！请登录');
        navigate('/login');
      } else {
        message.error(result.error || '注册失败');
      }
    } catch (error) {
      console.error('注册失败:', error);
      message.error('注册失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      padding: '20px'
    }}>
      <Card
        style={{
          width: '100%',
          maxWidth: 450,
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)',
          borderRadius: 12,
        }}
      >
        {/* 标题 */}
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <Title level={2} style={{ margin: 0, color: '#1890ff' }}>
            创建新账户
          </Title>
          <Text type="secondary">加入AI换脸换装系统</Text>
        </div>

        {/* 注册表单 */}
        <Form
          name="register"
          onFinish={handleRegister}
          autoComplete="off"
          size="large"
        >
          {/* 用户名输入框 */}
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名！' },
              { min: 3, message: '用户名至少3个字符！' },
              { max: 20, message: '用户名最多20个字符！' },
              {
                pattern: /^[a-zA-Z0-9_]+$/,
                message: '用户名只能包含字母、数字和下划线！',
              },
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
              autoComplete="username"
            />
          </Form.Item>

          {/* 密码输入框 */}
          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码！' },
              { min: 6, message: '密码至少6个字符！' },
              { max: 50, message: '密码最多50个字符！' },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              autoComplete="new-password"
            />
          </Form.Item>

          {/* 确认密码输入框 */}
          <Form.Item
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码！' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致！'));
                },
              }),
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="确认密码"
              autoComplete="new-password"
            />
          </Form.Item>

          {/* 注册按钮 */}
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              icon={<UserAddOutlined />}
              style={{
                width: '100%',
                height: 48,
                fontSize: 16,
                borderRadius: 8,
              }}
            >
              {loading ? '注册中...' : '注册'}
            </Button>
          </Form.Item>
        </Form>

        {/* 分割线 */}
        <Divider>
          <Text type="secondary">已有账户？</Text>
        </Divider>

        {/* 登录链接 */}
        <div style={{ textAlign: 'center' }}>
          <Link to="/login">
            <Button type="link" size="large">
              立即登录
            </Button>
          </Link>
        </div>

        {/* 用户协议 */}
        <div style={{ 
          textAlign: 'center', 
          marginTop: 24,
          padding: 16,
          background: '#f5f5f5',
          borderRadius: 8
        }}>
          <Text type="secondary" style={{ fontSize: 12 }}>
            注册即表示同意我们的服务条款和隐私政策
          </Text>
        </div>
      </Card>
    </div>
  );
};

export default RegisterPage; 