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

const router = useRouter()

const form = ref({
  username: '',
  phone: '',
  email: '',
  password: '',
  confirmPassword: '',
})
const submitting = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

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

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

  const username = form.value.username.trim()
  const phone = form.value.phone.trim()
  const email = form.value.email.trim()
  const password = form.value.password

  if (!username || !phone || !email || !password) {
    errorMessage.value = '请完整填写用户名、手机号、邮箱和密码'
    return
  }

  if (!/^\d{11}$/.test(phone)) {
    errorMessage.value = '手机号格式不正确，请输入11位数字'
    return
  }

  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    errorMessage.value = '邮箱格式不正确'
    return
  }

  if (password.length < 6) {
    errorMessage.value = '密码至少 6 位'
    return
  }

  if (password !== form.value.confirmPassword) {
    errorMessage.value = '两次输入密码不一致'
    return
  }

  submitting.value = true
  try {
    await register({ username, phone, email, password })
    successMessage.value = '注册成功，正在前往登录页'
    await router.replace({ path: '/login', query: { loginId: phone } })
  } 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" type="button" @click="router.push('/login')">登录</button>
        <button class="tab-btn active" type="button">注册</button>
      </div>

      <form class="form" @submit.prevent="handleSubmit">
        <label class="field">
          <span>用户名</span>
          <input v-model.trim="form.username" type="text" placeholder="3-20位用户名" minlength="3" maxlength="20" />
        </label>
        <label class="field">
          <span>手机号</span>
          <input
            v-model.trim="form.phone"
            type="tel"
            inputmode="numeric"
            placeholder="请输入11位手机号"
            maxlength="11"
          />
        </label>
        <label class="field">
          <span>邮箱</span>
          <input v-model.trim="form.email" type="email" placeholder="请输入邮箱地址" />
        </label>
        <label class="field">
          <span>密码</span>
          <input v-model="form.password" type="password" placeholder="至少6位密码" minlength="6" />
        </label>
        <label class="field">
          <span>确认密码</span>
          <input v-model="form.confirmPassword" type="password" placeholder="再次输入密码" minlength="6" />
        </label>
        <button class="primary-btn" type="submit" :disabled="submitting">
          {{ submitting ? '注册中...' : '注册' }}
        </button>
      </form>

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