<script setup lang="ts">
import { reactive, shallowRef } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { register } from '@/api/auth'

const route = useRoute()
const router = useRouter()
const loading = shallowRef(false)
const form = reactive({
  name: '',
  email: '',
  password: '',
  password_confirmation: '',
  invite_code: String(route.query.invite_code ?? route.query.code ?? route.query.invite ?? ''),
})

async function submit() {
  loading.value = true
  try {
    await register(form)
    ElMessage.success('注册成功，请登录')
    await router.push('/login')
  } catch (error: any) {
    const errors = error.response?.data?.errors
    const firstError = errors ? Object.values(errors).flat().find(Boolean) : null
    ElMessage.error(String(firstError ?? error.response?.data?.message ?? '注册失败，请检查填写信息'))
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <main class="register-page">
    <section class="register-panel">
      <h1>邀请码注册</h1>
      <ElForm :model="form" label-position="top">
        <ElFormItem label="姓名"><ElInput v-model="form.name" /></ElFormItem>
        <ElFormItem label="邮箱"><ElInput v-model="form.email" /></ElFormItem>
        <ElFormItem label="密码"><ElInput v-model="form.password" type="password" show-password /></ElFormItem>
        <ElFormItem label="确认密码"><ElInput v-model="form.password_confirmation" type="password" show-password /></ElFormItem>
        <ElFormItem label="邀请码"><ElInput v-model="form.invite_code" /></ElFormItem>
        <ElButton class="w-full" type="primary" :loading="loading" @click="submit">注册</ElButton>
      </ElForm>
    </section>
  </main>
</template>

<style scoped>
.register-page {
  min-height: 100vh;
  display: grid;
  place-items: center;
  padding: 20px;
}

.register-panel {
  width: min(520px, 100%);
  padding: 28px;
  border: 1px solid var(--qq-line);
  border-radius: 8px;
  background: white;
}
</style>
