<template>
  <div class="login-page">
    <van-nav-bar title="登录" left-text="返回" left-arrow @click-left="$router.back()" />

    <div class="login-content">
      <div class="login-hero">
        <h2>欢迎来到许愿树 ✨</h2>
        <p>登录后记录你的每一个心愿</p>
      </div>

      <van-form @submit="handleLogin">
        <van-cell-group inset>
          <van-field
            v-model="phone"
            name="phone"
            label="手机号"
            placeholder="请输入手机号"
            type="tel"
            maxlength="11"
            :rules="[{ required: true, pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }]"
          />
          <van-field
            v-model="code"
            name="code"
            label="验证码"
            placeholder="请输入验证码"
            maxlength="6"
            :rules="[{ required: true, message: '请输入验证码' }]"
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                plain
                :disabled="countdown > 0"
                @click="sendCode"
              >
                {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
              </van-button>
            </template>
          </van-field>
          <van-field
            v-model="captchaText"
            name="captcha"
            label="图形验证"
            placeholder="请输入图片中的字符"
            maxlength="4"
            :rules="[{ required: true, message: '请输入图形验证码' }]"
          >
            <template #button>
              <img
                v-if="captchaImg"
                :src="captchaImg"
                class="captcha-img"
                @click="refreshCaptcha"
              />
            </template>
          </van-field>
        </van-cell-group>

        <div class="submit-wrap">
          <van-button type="primary" block round native-type="submit" :loading="logging">
            登录
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showSuccessToast, showToast } from 'vant'
import { useUserStore } from '@/stores/user'
import { sendSms, login as loginApi, getCaptcha as getCaptchaApi } from '@/api/auth'

const router = useRouter()
const userStore = useUserStore()

const phone = ref('')
const code = ref('')
const captchaText = ref('')
const captchaImg = ref('')
const captchaKey = ref('')
const countdown = ref(0)
const logging = ref(false)

async function refreshCaptcha() {
  try {
    const captcha = await getCaptchaApi()
    captchaKey.value = captcha.key
    captchaImg.value = captcha.value
  } catch {
    // ignore
  }
}

function sendCode() {
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    showToast('请输入正确的手机号')
    return
  }
  sendSms(phone.value)
  showToast('验证码已发送')
  countdown.value = 60
  const t = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) clearInterval(t)
  }, 1000)
}

async function handleLogin() {
  logging.value = true
  try {
    const userData = await loginApi(phone.value, code.value, captchaText.value, captchaKey.value)
    userStore.login(userData)
    showSuccessToast('登录成功')
    router.replace('/')
  } catch (err: any) {
    showToast(err?.message || '登录失败')
    refreshCaptcha()
  } finally {
    logging.value = false
  }
}

onMounted(() => {
  refreshCaptcha()
})
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background: #f7f8fa;
}
.login-content {
  padding: 16px;
}
.login-hero {
  text-align: center;
  padding: 30px 0;
}
.login-hero h2 {
  font-size: 22px;
  margin-bottom: 6px;
}
.login-hero p {
  font-size: 14px;
  color: #999;
}
.submit-wrap {
  padding: 24px 16px;
}
.captcha-img {
  height: 36px;
  cursor: pointer;
  border-radius: 4px;
}
</style>
