<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { RouterLink, useRoute, useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'

import { fetchAuthCaptcha, type AuthCaptcha } from '@/features/auth/api/auth'
import { useSessionStore } from '@/stores/session'
import { useSmsCountdown } from '@/shared/composables/useSmsCountdown'
import { readError } from '@/shared/utils/error'

const router = useRouter()
const route = useRoute()
const session = useSessionStore()
const loading = ref(false)
const agreed = ref(false)
const captchaLoading = ref(false)
const captcha = ref<AuthCaptcha | null>(null)
const loginMode = ref<'sms' | 'password'>('password')
const form = reactive({
  phone: '',
  captchaCode: '',
  code: '',
  password: '',
})

const { countDown, sending, handleSendCode } = useSmsCountdown()

onMounted(loadCaptcha)

function switchToPassword() {
  loginMode.value = 'password'
  form.captchaCode = ''
  form.code = ''
}

function switchToSms() {
  loginMode.value = 'sms'
  form.password = ''
}

async function loadCaptcha() {
  captchaLoading.value = true
  try {
    captcha.value = await fetchAuthCaptcha()
    form.captchaCode = ''
  } catch (error) {
    showToast({ message: readError(error, '图形验证码加载失败'), icon: 'cross' })
  } finally {
    captchaLoading.value = false
  }
}

async function sendCode() {
  const sent = await handleSendCode(form.phone, {
    captchaId: captcha.value?.captcha_id || '',
    captchaCode: form.captchaCode,
  })
  if (!sent && form.captchaCode.trim()) {
    await loadCaptcha()
  }
}

async function handleLogin() {
  if (!agreed.value) {
    showDialog({
      title: '提示',
      message: '请先阅读并同意用户协议和隐私政策',
    })
    return
  }

  loading.value = true
  try {
    await session.login(form.phone, form.code)
    const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : '/m/profile'
    await router.replace(redirect)
  } catch {
    showToast({ message: '登录失败，请检查手机号和验证码', icon: 'cross' })
  } finally {
    loading.value = false
  }
}

async function handlePasswordLogin() {
  if (!agreed.value) {
    showDialog({
      title: '提示',
      message: '请先阅读并同意用户协议和隐私政策',
    })
    return
  }
  if (!form.password) {
    showToast({ message: '请输入密码', icon: 'warning-o' })
    return
  }
  loading.value = true
  try {
    await session.loginByPassword(form.phone, form.password)
    const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : '/m/profile'
    await router.replace(redirect)
  } catch (error) {
    showToast({ message: readError(error, '登录失败，请检查手机号和密码'), icon: 'cross' })
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <main class="mobile-login-shell">
    <header class="page-header">
      <button class="back-btn" type="button" @click="router.back()">
        <van-icon name="arrow-left" :size="20" />
      </button>
    </header>

    <section class="auth-body">
      <div class="brand-lockup">
        <div class="brand-logo">锤</div>
        <strong>大锤商行</strong>
      </div>

      <div class="form-section">
        <h1>{{ loginMode === 'sms' ? '登录' : '密码登录' }}</h1>

        <label class="auth-input-row">
          <input v-model="form.phone" type="tel" maxlength="11" placeholder="手机号" />
        </label>

        <!-- 短信登录 -->
        <template v-if="loginMode === 'sms'">
          <label class="auth-input-row captcha-row">
            <input
              v-model="form.captchaCode"
              type="text"
              maxlength="4"
              autocomplete="off"
              placeholder="图形验证码"
            />
            <button
              class="captcha-image-button"
              type="button"
              :disabled="captchaLoading"
              @click="loadCaptcha"
            >
              <img v-if="captcha" :src="captcha.image" alt="图形验证码" />
              <span v-else>刷新</span>
            </button>
          </label>

          <label class="auth-input-row code-row">
            <input
              v-model="form.code"
              type="text"
              inputmode="numeric"
              maxlength="6"
              placeholder="验证码"
            />
            <span class="code-action">
              <van-button
                size="small"
                plain
                :disabled="sending || countDown > 0"
                :loading="sending"
                class="code-btn"
                @click="sendCode"
              >
                {{ countDown > 0 ? `${countDown}s` : sending ? '发送中' : '发送验证码' }}
              </van-button>
            </span>
          </label>
        </template>

        <!-- 密码登录 -->
        <template v-if="loginMode === 'password'">
          <label class="auth-input-row">
            <input
              v-model="form.password"
              type="password"
              maxlength="20"
              placeholder="密码"
            />
          </label>
        </template>

        <div class="assist-row">
          <span v-if="loginMode === 'sms'">验证码登录</span>
          <span v-else>密码登录</span>
          <button v-if="loginMode === 'sms'" class="link-btn" type="button" @click="switchToPassword">密码登录</button>
          <button v-else class="link-btn" type="button" @click="switchToSms">短信验证码登录</button>
          <RouterLink v-if="loginMode === 'sms'" to="/m/register">没有账号？<b>立即注册</b></RouterLink>
        </div>

        <div class="agreement-row">
          <van-checkbox v-model="agreed" shape="square" icon-size="16px">
            我已阅读并同意《<b>用户协议</b>》和《<b>隐私政策</b>》
          </van-checkbox>
        </div>

        <van-button
          v-if="loginMode === 'sms'"
          type="primary"
          block
          class="primary-button"
          :loading="loading"
          loading-text="登录中..."
          @click="handleLogin"
        >
          登录
        </van-button>
        <van-button
          v-else
          type="primary"
          block
          class="primary-button"
          :loading="loading"
          loading-text="登录中..."
          @click="handlePasswordLogin"
        >
          登录
        </van-button>

        <RouterLink to="/m/register" class="secondary-entry">还没有账号，创建一个</RouterLink>
      </div>
    </section>
  </main>
</template>

<style scoped>
.mobile-login-shell {
  min-height: 100dvh;
  background:
    radial-gradient(circle at 50% 12%, rgba(255, 106, 0, 0.12), transparent 34%),
    linear-gradient(180deg, #fff7ed 0%, #ffffff 68%, #fffaf4 100%);
  color: #111827;
}

.page-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  height: 48px;
  margin: 0;
  padding: 0 18px;
  background: transparent;
}

.back-btn {
  display: grid;
  width: 34px;
  height: 34px;
  place-items: center;
  border: none;
  border-radius: 999px;
  background: none;
  color: #111827;
}

.auth-body {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100px 24px 48px;
  min-height: 100dvh;
}

.brand-lockup {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 36px;
}

.brand-logo {
  display: grid;
  width: 44px;
  height: 44px;
  place-items: center;
  border-radius: 12px;
  background: linear-gradient(135deg, #ff6a00, #ff914d);
  box-shadow: 0 10px 28px rgba(255, 106, 0, 0.24);
  color: #fff;
  font-size: 18px;
  font-weight: 900;
}

.brand-lockup strong {
  color: #0f172a;
  font-size: 20px;
  font-weight: 800;
}

.form-section {
  width: 100%;
  max-width: 400px;
}

.form-section h1 {
  margin: 0 0 28px;
  color: #0f172a;
  font-size: 26px;
  font-weight: 800;
}

.auth-input-row {
  display: flex;
  align-items: center;
  margin-bottom: 14px;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  background: #ffffff;
  overflow: hidden;
}

.auth-input-row input {
  flex: 1 1 0%;
  width: 0;
  min-width: 0;
  border: none;
  padding: 14px 16px;
  color: #0f172a;
  font-size: 16px;
  background: transparent;
  outline: none;
}

.auth-input-row input::placeholder {
  color: #94a3b8;
}

.captcha-row {
  padding-right: 4px;
}

.captcha-image-button {
  display: grid;
  place-items: center;
  flex: 0 0 78px;
  width: 78px;
  height: 38px;
  margin: 2px 6px 2px 0;
  border: none;
  border-radius: 8px;
  background: #fff7ed;
  color: #ff6a00;
  cursor: pointer;
  font-size: 13px;
  font-weight: 700;
  padding: 0;
  overflow: hidden;
}

.captcha-image-button:disabled {
  cursor: wait;
  opacity: 0.7;
}

.captcha-image-button img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.code-row {
  padding-right: 4px;
}

.code-action {
  flex: 0 0 auto;
  min-width: 92px;
  padding: 4px;
}

.code-btn {
  width: 100%;
  font-size: 11px !important;
}

.assist-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin: 8px 0 12px;
  font-size: 13px;
  color: #64748b;
  flex-wrap: wrap;
}

.assist-row a,
.link-btn {
  color: #ff6a00;
  text-decoration: none;
  font-size: 13px;
  font-weight: 700;
  background: none;
  border: none;
  padding: 0;
  cursor: pointer;
}

.agreement-row {
  margin: 16px 0 20px;
  font-size: 13px;
  color: #475569;
}

.agreement-row b {
  color: #ff6a00;
}

.primary-button {
  height: 50px;
  border-radius: 12px;
  font-size: 17px;
  font-weight: 700;
  background: linear-gradient(135deg, #ff6a00, #ff8a1f);
  border: none;
  box-shadow: 0 10px 28px rgba(255, 106, 0, 0.24);
}

.secondary-entry {
  display: block;
  margin-top: 18px;
  text-align: center;
  color: #94a3b8;
  font-size: 14px;
  text-decoration: none;
}
</style>
