<script setup lang="ts">
import Brand from '@/components/Brand.vue'
import { UserOutlined, LockOutlined, MailOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user'
import { api } from '@/utils/request'
import { ApiError } from '@/types/api'
import type { UserInfo } from '@/stores/user'

const formState = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
})

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

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

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    const data = await api.post<{
      access_token?: string
      refresh_token?: string
      user?: UserInfo
    }>('/api/v1/register', {
      username: formState.username,
      email: formState.email,
      password: formState.password,
    })

    // 注册成功后自动设置 token（如果后端返回）
    if (data?.access_token) {
      userStore.setToken(data.access_token, data.refresh_token!)
      if (data.user) {
        userStore.setUser(data.user)
      }
    }

    message.success('注册成功！即将跳转到登录页...')
    setTimeout(() => {
      router.push('/login')
    }, 1500)
  } catch (error: unknown) {
    if (error && typeof error === 'object' && 'errorFields' in error) {
      return
    }
    if (error instanceof ApiError) {
      message.error(error.message)
      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>
