<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { login } from '../api/auth'
import { readStoredAuth, saveAuth } from '../utils/auth-storage'

const router = useRouter()
const route = useRoute()

const form = ref({
  loginId: '',
  password: '',
})
const submitting = ref(false)
const errorMessage = ref('')

watch(
  () => route.query.loginId,
  (value) => {
    if (typeof value === 'string' && value && !form.value.loginId) {
      form.value.loginId = value
    }
  },
  { immediate: true },
)

onMounted(() => {
  if (readStoredAuth()) {
    void router.replace('/hall')
  }
})

async function handleSubmit(): Promise<void> {
  errorMessage.value = ''

  if (!form.value.loginId.trim() || !form.value.password) {
    errorMessage.value = '请输入登录ID和密码'
    return
  }

  submitting.value = true
  try {
    const result = await login({
      loginId: form.value.loginId.trim(),
      password: form.value.password,
    })
    saveAuth(result)

    const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : '/hall'
    await router.replace(redirect)
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : '登录失败，请稍后重试'
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <section class="auth-page">
    <div class="auth-card">
      <h1>麻将</h1>
      <p class="sub-title">先完成账号登录，后续进入大厅创建/加入房间</p>

      <div class="mode-tabs">
        <button class="tab-btn active" type="button">登录</button>
        <button class="tab-btn" type="button" @click="router.push('/register')">注册</button>
      </div>

      <form class="form" @submit.prevent="handleSubmit">
        <label class="field">
          <span>登录ID</span>
          <input v-model.trim="form.loginId" type="text" placeholder="请输入手机号或账号" />
        </label>
        <label class="field">
          <span>密码</span>
          <input v-model="form.password" type="password" placeholder="请输入密码" />
        </label>
        <button class="primary-btn" type="submit" :disabled="submitting">
          {{ submitting ? '登录中...' : '登录' }}
        </button>
      </form>

      <p v-if="errorMessage" class="message error">{{ errorMessage }}</p>
    </div>
  </section>
</template>
