<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationStyle: 'custom',
  },
}
</route>

<script lang="ts" setup>
import { getCode, register } from '@/api/login'
import { goBack, toPage } from '@/utils/page'
import { toast } from '@/utils/toast'

defineOptions({
  name: 'Register', // 注册
})

// 获取屏幕边界到安全区域距离
const systemInfo = uni.getSystemInfoSync()
const safeAreaInsets = systemInfo.safeAreaInsets

// 表单数据
const formData = ref({
  name: '',
  phone: '',
  verifyCode: '',
  pwd: '',
  code: '',
})

// 验证码倒计时
const countdown = ref(0)
const countdownTimer = ref<any>(null)

// 获取验证码
async function getVerificationCode() {
  // 验证手机号
  if (!formData.value.phone.trim()) {
    toast.error('Please enter phone number first')
    return
  }

  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(formData.value.phone)) {
    toast.error('Please enter valid phone number')
    return
  }

  // 防止重复点击
  if (countdown.value > 0) {
    return
  }

  try {
    // 显示加载状态
    uni.showLoading({
      title: 'Sending...',
      mask: true,
    })

    // 调用获取验证码接口
    await getCode(formData.value.phone)

    uni.hideLoading()
    toast.success('Verification code sent successfully')

    // 开始倒计时
    countdown.value = 60
    countdownTimer.value = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownTimer.value!)
        countdownTimer.value = null
      }
    }, 1000)
  }
  catch (error) {
    uni.hideLoading()
    toast.error(error.message || 'Failed to send verification code')
  }
}

// 注册处理
async function handleRegister() {
  try {
    // 表单验证
    const isValid = await validateForm()
    if (!isValid)
      return

    // 显示加载状态
    uni.showLoading({
      title: 'Registering...',
      mask: true,
    })

    // 调用注册接口
    const registerData = {
      name: formData.value.name,
      phone: formData.value.phone,
      verifyCode: formData.value.verifyCode,
      pwd: formData.value.pwd,
      code: formData.value.code,
    }

    await register(registerData)

    uni.hideLoading()
    // 注册成功
    toast.success('Registration successful!')
    setTimeout(() => {
      toPage('/pages/login/login', {}, true)
    }, 1500)
  }
  catch (error) {
    uni.hideLoading()
    toast.error(error.message || 'Registration failed')
  }
}

// 表单验证
function validateForm() {
  return new Promise((resolve) => {
    // 验证必填字段
    if (!formData.value.name.trim()) {
      toast.error('Please enter name')
      resolve(false)
      return
    }

    if (!formData.value.phone.trim()) {
      toast.error('Please enter phone number')
      resolve(false)
      return
    }

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(formData.value.phone)) {
      toast.error('Please enter valid phone number')
      resolve(false)
      return
    }

    if (!formData.value.verifyCode.trim()) {
      toast.error('Please enter verification code')
      resolve(false)
      return
    }

    if (!formData.value.pwd.trim()) {
      toast.error('Please enter password')
      resolve(false)
      return
    }

    // 验证密码长度
    if (formData.value.pwd.length < 6 || formData.value.pwd.length > 20) {
      toast.error('Password should be 6-20 characters')
      resolve(false)
      return
    }

    resolve(true)
  })
}

// 页面卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
})
</script>

<template>
  <view class="register-page min-h-screen bg-white">
    <!-- 背景图片区域 -->
    <view class="auth-bg-section relative">
      <!-- 自定义导航栏 -->
      <view :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
        <view class="h-88rpx flex items-center px-24rpx">
          <wd-icon name="thin-arrow-left" size="32rpx" @click="goBack" />
        </view>
      </view>

      <!-- Logo和标语 -->
      <view class="pb-40rpx pt-60rpx text-center">
        <view class="mb-20rpx flex items-center justify-center">
          <image src="/static/logo.png" class="mr-16rpx h-60rpx w-60rpx" />
        </view>
      </view>
    </view>

    <!-- 表单内容区域 -->
    <view class="flex flex-col px-20rpx">
      <view class="mb-40rpx" />

      <!-- 注册表单 -->
      <wd-form ref="form" :model="formData">
        <view class="mb-40rpx space-y-32rpx">
          <wd-input
            v-model="formData.name"
            prop="name"
            placeholder="Username"
            no-border
            custom-class="bandhu-auth-input-field"
          />
          <wd-input
            v-model="formData.phone"
            prop="phone"
            placeholder="+88 Mobile number"
            no-border
            custom-class="bandhu-auth-input-field"
          />
          <view class="flex items-center gap-20rpx">
            <wd-input
              v-model="formData.verifyCode"
              prop="verifyCode"
              placeholder="Verification Code"
              no-border
              custom-class="flex-1 bandhu-auth-input-field"
            />
            <wd-button
              type="error"
              plain
              :disabled="countdown > 0"
              custom-class="bandhu-auth-secondary-btn"
              @click="getVerificationCode"
            >
              {{ countdown > 0 ? `${countdown}s` : 'Get Code' }}
            </wd-button>
          </view>
          <wd-input
            v-model="formData.pwd"
            prop="pwd"
            placeholder="Password 6-20 characters"
            no-border
            show-password
            custom-class="bandhu-auth-input-field"
          />
          <wd-input
            v-model="formData.code"
            placeholder="Referrer Code"
            no-border
            custom-class="bandhu-auth-input-field"
          />
        </view>

        <!-- 注册按钮 -->
        <wd-button
          type="error"
          size="large"
          custom-class="mb-200rpx w-full bandhu-auth-primary-btn"
          @click="handleRegister"
        >
          Register
        </wd-button>
      </wd-form>

      <!-- 登录提示 -->
      <view class="text-center">
        <text class="text-28rpx text-#666">
          Already have account?
        </text>
        <text class="ml-10rpx text-28rpx text-[var(--wot-color-theme)]" @click="toPage('/pages/login/login')">
          Login Now
        </text>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
// 注册页面特有样式（如果有的话）
</style>
