<template>
  <div class="flex w-full h-screen">
    <LoginLeftView />

    <div class="relative flex-1">
      <AuthTopBar />

      <div class="auth-right-wrap">
        <div class="form">
          <h3 class="title">{{ $t('resetPassword.title') }}</h3>
          <p class="sub-title">{{ $t('resetPassword.subTitle') }}</p>

          <ElAlert
            v-if="!token"
            :title="$t('resetPassword.invalidToken')"
            type="error"
            :closable="false"
            show-icon
            class="mt-4"
          />

          <ElForm
            v-else
            ref="formRef"
            :model="formModel"
            :rules="rules"
            class="mt-5"
            label-position="top"
          >
            <ElFormItem :label="$t('resetPassword.newPassword')" prop="newPassword">
              <ElInput
                v-model="formModel.newPassword"
                class="custom-height"
                type="password"
                show-password
                :placeholder="$t('resetPassword.newPasswordPlaceholder')"
              />
            </ElFormItem>

            <ElFormItem :label="$t('resetPassword.confirmPassword')" prop="confirmPassword">
              <ElInput
                v-model="formModel.confirmPassword"
                class="custom-height"
                type="password"
                show-password
                :placeholder="$t('resetPassword.confirmPasswordPlaceholder')"
              />
            </ElFormItem>

            <div style="margin-top: 10px">
              <ElButton
                class="w-full custom-height"
                type="primary"
                @click="handleSubmit"
                :loading="loading"
                v-ripple
              >
                {{ $t('resetPassword.submitBtnText') }}
              </ElButton>
            </div>

            <div style="margin-top: 15px">
              <ElButton class="w-full custom-height" plain @click="toLogin">
                {{ $t('resetPassword.backBtnText') }}
              </ElButton>
            </div>
          </ElForm>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { computed, reactive, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { useI18n } from 'vue-i18n'
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
  import { fetchResetAdminPassword } from '@/api/auth'

  defineOptions({ name: 'ResetPassword' })

  const router = useRouter()
  const route = useRoute()
  const { t } = useI18n()

  const token = computed(() => String(route.query.token || '').trim())
  const loading = ref(false)
  const formRef = ref<FormInstance>()

  const formModel = reactive({
    newPassword: '',
    confirmPassword: ''
  })

  const rules = computed<FormRules>(() => ({
    newPassword: [
      { required: true, message: t('resetPassword.rules.newPasswordRequired'), trigger: 'blur' },
      { min: 6, max: 32, message: t('resetPassword.rules.passwordLength'), trigger: 'blur' }
    ],
    confirmPassword: [
      {
        required: true,
        message: t('resetPassword.rules.confirmPasswordRequired'),
        trigger: 'blur'
      },
      {
        validator: (_rule, value, callback) => {
          if (value !== formModel.newPassword) {
            callback(new Error(t('resetPassword.rules.passwordNotMatch')))
            return
          }
          callback()
        },
        trigger: 'blur'
      }
    ]
  }))

  const handleSubmit = async () => {
    if (!formRef.value || !token.value) return

    // 1. 校验表单
    await formRef.value.validate(async (valid) => {
      if (!valid) return

      loading.value = true
      try {
        // 2. 重置密码
        await fetchResetAdminPassword({
          token: token.value,
          newPassword: formModel.newPassword
        })

        // 3. 提示并跳转登录
        ElMessage.success(t('resetPassword.success'))
        await router.push({ name: 'Login' })
      } catch (error) {
        console.error(error)
      } finally {
        loading.value = false
      }
    })
  }

  const toLogin = () => {
    router.push({ name: 'Login' })
  }
</script>

<style scoped>
  @import '../login/style.css';
</style>
