<script setup lang="ts">
import { ref } from "vue";

import { api } from "../api/client";
import { useUiStore } from "../stores/ui";

const ui = useUiStore();
const currentPassword = ref("");
const newPassword = ref("");
const confirmation = ref("");
const saving = ref(false);
const errorMessage = ref("");

async function submit(): Promise<void> {
  saving.value = true;
  errorMessage.value = "";
  try {
    await api.patch("/account/password", {
      current_password: currentPassword.value,
      new_password: newPassword.value,
      confirmation: confirmation.value,
    });
    currentPassword.value = "";
    newPassword.value = "";
    confirmation.value = "";
    ui.closeDialog();
    ui.showToast("密码已修改");
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : "密码修改失败。";
  } finally {
    saving.value = false;
  }
}
</script>

<template>
  <form class="form-grid" @submit.prevent="submit">
    <div class="field"><label for="current-password">当前密码</label><input id="current-password" v-model="currentPassword" class="input" type="password" autocomplete="current-password" required /></div>
    <div class="field"><label for="new-password">新密码</label><input id="new-password" v-model="newPassword" class="input" type="password" autocomplete="new-password" required /></div>
    <div class="field"><label for="password-confirmation">确认新密码</label><input id="password-confirmation" v-model="confirmation" class="input" type="password" autocomplete="new-password" required /></div>
    <p class="faint password-hint">密码长度8至128位，至少包含字母、数字、符号中的两类。</p>
    <p v-if="errorMessage" class="field-error" role="alert">{{ errorMessage }}</p>
    <div class="form-actions"><button class="btn btn-primary" type="submit" :disabled="saving">{{ saving ? "保存中" : "修改密码" }}</button></div>
  </form>
</template>
