<script setup>
import Brand from '@/components/Brand.vue'

// 表单数据
const formState = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
})

// 表单规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为 3-20 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value !== formState.password) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur',
    },
  ],
}

const formRef = ref()
const loading = ref(false)
const router = useRouter()

// 提交注册
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

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

    const data = await response.json()

    if (data.code === 0) {
      message.success('注册成功！即将跳转到登录页...')
      setTimeout(() => {
        router.push('/login')
      }, 1500)
    } else {
      message.error(data.message || '注册失败，请重试')
    }
  } catch (error) {
    if (error.errorFields) {
      // 表单验证错误
      return
    }
    console.error('注册错误：', error)
    message.error('注册失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}
</script>

<template>
  <div class="flex flex-col lg:flex-row min-h-screen">
    <!-- 左侧图片区域 -->
    <div
      class="w-full lg:w-1/2 relative overflow-hidden bg-linear-to-br from-[#4da30d] to-[#377508] min-h-[200px] lg:min-h-screen"
    >
      <img
        src="@/assets/images/bg.jpeg"
        alt="Background"
        class="absolute inset-0 w-full h-full object-cover"
      />
      <div class="absolute inset-0 bg-black/20"></div>
    </div>

    <!-- 右侧表单区域 -->
    <div class="w-full lg:w-1/2 flex items-center justify-begain bg-white p-6 md:p-8 lg:p-12">
      <div class="w-full max-w-md p-4 border border-gray-300 rounded-md overflow-hidden shadow-md">
        <!-- Brand Logo -->
        <div class="mb-8">
          <Brand class="justify-center" size="large" :show-app-name="false" />
        </div>

        <!-- 表单标题 -->
        <div class="mb-8 text-center">
          <h1 class="text-3xl font-bold text-gray-800 mb-2">用户注册</h1>
          <p class="text-gray-600">创建您的账户</p>
        </div>

        <!-- 注册表单 -->
        <a-form
          ref="formRef"
          :model="formState"
          :rules="rules"
          layout="vertical"
          @finish="handleSubmit"
        >
          <a-form-item label="用户名" name="username">
            <a-input
              v-model:value="formState.username"
              size="large"
              placeholder="请输入用户名"
              :maxlength="20"
            >
              <template #prefix>
                <UserOutlined class="text-gray-400" />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item label="邮箱" name="email">
            <a-input
              v-model:value="formState.email"
              size="large"
              type="email"
              placeholder="请输入邮箱地址"
            >
              <template #prefix>
                <MailOutlined class="text-gray-400" />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item label="密码" name="password">
            <a-input-password
              v-model:value="formState.password"
              size="large"
              placeholder="请输入密码（至少6位）"
              :maxlength="50"
            >
              <template #prefix>
                <LockOutlined class="text-gray-400" />
              </template>
            </a-input-password>
          </a-form-item>

          <a-form-item label="确认密码" name="confirmPassword">
            <a-input-password
              v-model:value="formState.confirmPassword"
              size="large"
              placeholder="请再次输入密码"
              :maxlength="50"
            >
              <template #prefix>
                <LockOutlined class="text-gray-400" />
              </template>
            </a-input-password>
          </a-form-item>

          <a-form-item class="mt-6">
            <a-button
              type="primary"
              html-type="submit"
              size="large"
              :loading="loading"
              block
              class="h-12 text-base font-medium bg-[#4da30d] hover:bg-[#5fc910] border-none"
            >
              注册
            </a-button>
          </a-form-item>

          <div class="text-center mt-4">
            <span class="text-gray-600 text-sm">已有账户？</span>
            <a-button type="link" class="text-[#4da30d] hover:text-[#5fc910]" @click="goToLogin">
              立即登录
            </a-button>
          </div>
        </a-form>
      </div>
    </div>
  </div>
</template>
