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

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

defineOptions({
  name: 'ForgotPassword', // 忘记密码
})

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

// 步骤控制：1-输入手机号，2-重置密码
const step = ref(1)

// 表单数据
const formData = ref({
  phone: '',
  verifyCode: '',
  newPwd: '',
  confirmPwd: '',
})

// 验证码倒计时
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')
  }
}

// 第一步：验证手机号
function handleStep1() {
  // 验证手机号
  if (!formData.value.phone.trim()) {
    toast.error('Please enter phone number')
    return
  }

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

  // 跳转到第二步
  step.value = 2
}

// 第二步：重置密码
async function handleResetPassword() {
  try {
    // 表单验证
    const isValid = await validateResetForm()
    if (!isValid)
      return

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

    // 调用重置密码接口
    const resetData = {
      phoneNo: formData.value.phone,
      newPwd: formData.value.newPwd,
      verifyCode: formData.value.verifyCode,
    }

    await updateUserPassword(resetData)

    uni.hideLoading()
    toast.success('Password reset successfully')

    // 跳转到登录页
    setTimeout(() => {
      toPage('/pages/login/login', {}, true)
    }, 1500)
  }
  catch (error) {
    uni.hideLoading()
    toast.error(error.message || 'Failed to reset password')
  }
}

// 重置密码表单验证
function validateResetForm() {
  return new Promise((resolve) => {
    // 验证验证码
    if (!formData.value.verifyCode.trim()) {
      toast.error('Please enter verification code')
      resolve(false)
      return
    }

    // 验证新密码
    if (!formData.value.newPwd.trim()) {
      toast.error('Please enter new password')
      resolve(false)
      return
    }

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

    // 验证确认密码
    if (!formData.value.confirmPwd.trim()) {
      toast.error('Please confirm your password')
      resolve(false)
      return
    }

    // 验证两次密码是否一致
    if (formData.value.newPwd !== formData.value.confirmPwd) {
      toast.error('Passwords do not match')
      resolve(false)
      return
    }

    resolve(true)
  })
}

// 返回上一页
function goBack() {
  if (step.value === 2) {
    step.value = 1
  }
  else {
    goBackUtil()
  }
}

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

<template>
  <view class="forgot-password-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-60rpx 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" />

      <!-- 第一步：输入手机号 -->
      <view v-if="step === 1">
        <wd-form ref="form" :model="formData">
          <view class="mb-60rpx">
            <wd-input
              v-model="formData.phone"
              prop="phone"
              placeholder="+88 Mobile number"
              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="handleStep1"
          >
            Reset Password
          </wd-button>
        </wd-form>
      </view>

      <!-- 第二步：重置密码 -->
      <view v-else>
        <wd-form ref="form" :model="formData">
          <view class="mb-40rpx space-y-32rpx">
            <wd-input
              v-model="formData.phone"
              prop="phone"
              no-border
              readonly
              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.newPwd"
              prop="newPwd"

              placeholder="New Password 6-20 characters"
              no-border show-password
              custom-class="bandhu-auth-input-field"
            />
            <wd-input
              v-model="formData.confirmPwd"
              prop="confirmPwd"
              show-password
              placeholder="Confirm password"
              no-border
              custom-class="bandhu-auth-input-field"
            />
          </view>

          <!-- 密码提示 -->
          <view class="mb-60rpx text-center text-24rpx text-#666">
            Your password must be different from previous used password
          </view>

          <!-- 重置密码按钮 -->
          <wd-button
            type="error"
            size="large"
            custom-class="mb-200rpx w-full bandhu-auth-primary-btn"
            @click="handleResetPassword"
          >
            Reset Password
          </wd-button>
        </wd-form>
      </view>

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

<style lang="scss" scoped>
// 忘记密码页面特有样式（如果有的话）
</style>
