<template>
  <div class="page">
    <el-card shadow="never">
      <template #header><span class="title">{{ $t('password.title') }}</span></template>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        style="max-width: 480px"
      >
        <el-form-item :label="$t('password.oldPassword')" prop="oldPassword">
          <el-input v-model="form.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item :label="$t('password.newPassword')" prop="newPassword">
          <el-input v-model="form.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item :label="$t('password.confirmPassword')" prop="confirmPassword">
          <el-input v-model="form.confirmPassword" type="password" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="submitting" @click="submit">{{ $t('password.submit') }}</el-button>
          <el-button @click="onCancel">{{ $t('password.cancel') }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const router = useRouter();
const formRef = ref();
const submitting = ref(false);
const form = reactive({ oldPassword: "", newPassword: "", confirmPassword: "" });

const rules = {
  oldPassword: [{ required: true, message: () => t('password.pleaseInputOld'), trigger: "blur" }],
  newPassword: [
    { required: true, message: () => t('password.pleaseInputNew'), trigger: "blur" },
    { min: 6, message: () => t('password.passwordTooShort'), trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: () => t('password.pleaseInputConfirm'), trigger: "blur" },
    {
      validator: (_, val, cb) => (val === form.newPassword ? cb() : cb(new Error(t('password.passwordMismatch')))),
      trigger: "blur",
    },
  ],
};

const submit = async () => {
  await formRef.value.validate((valid) => {
    if (!valid) return;
    submitting.value = true;
    setTimeout(() => {
      submitting.value = false;
      ElMessage.success(t('password.success'));
      router.back();
    }, 600);
  });
};

const onCancel = () => router.back();
</script>

<style scoped>
.title {
  font-size: 16px;
  font-weight: 600;
}
</style>
