<script lang='ts' setup>
import { toastController } from "@ionic/vue";
import { eyeOffOutline, eyeOutline, keyOutline } from "ionicons/icons";
import zod from "zod";
import { client, safeClient } from "@/api";

const router = useRouter();

const formData = ref({
  currentPassword: "",
  newPassword: "",
  confirmPassword: "",
});

const showCurrentPassword = ref(false);
const showNewPassword = ref(false);
const showConfirmPassword = ref(false);
const isSubmitting = ref(false);

// 表单验证 Schema
const ChangePaymentPasswordSchema = zod.object({
  currentPassword: zod
    .string()
    .min(1, "请输入当前交易密码"),

  newPassword: zod
    .string()
    .min(6, "新密码至少6位")
    .max(20, "新密码最多20位")
    .regex(/^\d+$/, "交易密码只能包含数字")
    .refine(val => val.length === 6, "交易密码必须为6位数字"),

  confirmPassword: zod
    .string()
    .min(1, "请确认新密码"),
}).refine(data => data.newPassword === data.confirmPassword, {
  message: "两次输入的密码不一致",
  path: ["confirmPassword"],
}).refine(data => data.currentPassword !== data.newPassword, {
  message: "新密码不能与当前密码相同",
  path: ["newPassword"],
});

async function showToast(message: string, color: "success" | "danger" | "warning" = "danger") {
  const toast = await toastController.create({
    message,
    duration: 2000,
    position: "top",
    color,
  });
  await toast.present();
}

async function handleSubmit() {
  const result = ChangePaymentPasswordSchema.safeParse(formData.value);
  if (!result.success) {
    const first = result.error.issues[0];
    await showToast(first.message);
    return;
  }

  isSubmitting.value = true;
  try {
    await safeClient(client.api.user.security["transaction-password"].put({
      newPassword: formData.value.newPassword,
      oldPassword: formData.value.currentPassword,
    }));

    await showToast("交易密码修改成功", "success");
    router.back();
  }
  catch (error) {
    await showToast("密码修改失败，请检查当前密码是否正确", "danger");
  }
  finally {
    isSubmitting.value = false;
  }
}
</script>

<template>
  <ion-page>
    <ion-header class="ion-no-border">
      <ion-toolbar class="ion-toolbar">
        <ion-buttons slot="start">
          <back-button />
        </ion-buttons>
        <ion-title>更改交易密码</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content class="ion-padding">
      <div class="space-y-5">
        <!-- 提示信息 -->
        <div class="info-card">
          <ion-icon :icon="keyOutline" class="text-2xl text-[#c41e3a]" />
          <div class="text-sm text-[#666] leading-relaxed">
            交易密码用于提现、转账等资金操作，为了保障您的资金安全，请妥善保管交易密码。
          </div>
        </div>

        <!-- 表单卡片 -->
        <div class="form-card">
          <div class="space-y-4">
            <!-- 当前交易密码 -->
            <div class="form-item">
              <div class="flex items-center gap-2 mb-2">
                <ion-icon :icon="keyOutline" class="text-lg text-primary" />
                <label class="form-label">当前交易密码</label>
              </div>
              <ion-item lines="none" class="input-item">
                <ion-input
                  v-model="formData.currentPassword"
                  :type="showCurrentPassword ? 'text' : 'password'"
                  placeholder="请输入当前交易密码"
                  class="custom-input"
                  inputmode="numeric"
                  :maxlength="6"
                />
                <ion-icon
                  slot="end"
                  :icon="showCurrentPassword ? eyeOutline : eyeOffOutline"
                  class="password-toggle"
                  @click="showCurrentPassword = !showCurrentPassword"
                />
              </ion-item>
            </div>

            <!-- 新交易密码 -->
            <div class="form-item">
              <div class="flex items-center gap-2 mb-2">
                <ion-icon :icon="keyOutline" class="text-lg text-primary" />
                <label class="form-label">新交易密码</label>
              </div>
              <ion-item lines="none" class="input-item">
                <ion-input
                  v-model="formData.newPassword"
                  :type="showNewPassword ? 'text' : 'password'"
                  placeholder="请输入6位数字密码"
                  class="custom-input"
                  inputmode="numeric"
                  :maxlength="6"
                />
                <ion-icon
                  slot="end"
                  :icon="showNewPassword ? eyeOutline : eyeOffOutline"
                  class="password-toggle"
                  @click="showNewPassword = !showNewPassword"
                />
              </ion-item>
              <div class="text-xs text-[#999] mt-1 ml-1">
                交易密码为6位纯数字
              </div>
            </div>

            <!-- 确认新交易密码 -->
            <div class="form-item">
              <div class="flex items-center gap-2 mb-2">
                <ion-icon :icon="keyOutline" class="text-lg text-primary" />
                <label class="form-label">确认新密码</label>
              </div>
              <ion-item lines="none" class="input-item">
                <ion-input
                  v-model="formData.confirmPassword"
                  :type="showConfirmPassword ? 'text' : 'password'"
                  placeholder="请再次输入新密码"
                  class="custom-input"
                  inputmode="numeric"
                  :maxlength="6"
                />
                <ion-icon
                  slot="end"
                  :icon="showConfirmPassword ? eyeOutline : eyeOffOutline"
                  class="password-toggle"
                  @click="showConfirmPassword = !showConfirmPassword"
                />
              </ion-item>
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <ion-button
          expand="block"
          class="submit-button"
          :disabled="isSubmitting"
          @click="handleSubmit"
        >
          <ion-spinner v-if="isSubmitting" name="crescent" />
          <span v-else>确认修改</span>
        </ion-button>

        <!-- 注意事项 -->
        <div class="notice-card">
          <div class="text-sm font-semibold text-[#333] mb-2">
            注意事项：
          </div>
          <ul class="text-xs text-[#666] space-y-1 pl-4">
            <li>• 交易密码为6位纯数字，便于快速输入</li>
            <li>• 新密码不能与当前密码相同</li>
            <li>• 建议不要使用简单数字组合（如123456）</li>
            <li>• 交易密码与登录密码应设置不同</li>
            <li>• 请勿将交易密码告知他人</li>
            <li>• 如忘记密码，请联系客服找回</li>
          </ul>
        </div>
      </div>
    </ion-content>
  </ion-page>
</template>

<style lang='css' scoped>
.info-card {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  background: linear-gradient(135deg, #fff5f5 0%, #ffffff 100%);
  border-radius: 12px;
  border: 1px solid #ffe0e0;
}

.form-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.form-item {
  margin-bottom: 20px;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  font-size: 15px;
  font-weight: 600;
  color: #333;
}

.input-item {
  --background: #f7f8fa;
  --border-radius: 12px;
  --padding-start: 16px;
  --padding-end: 16px;
  --min-height: 48px;
}

.custom-input {
  --placeholder-color: #999;
  --placeholder-opacity: 1;
  font-size: 15px;
}

.password-toggle {
  font-size: 20px;
  color: #999;
  cursor: pointer;
  padding: 8px;
}

.password-toggle:hover {
  color: #666;
}

.submit-button {
  --background: linear-gradient(135deg, #c41e3a 0%, #8b1a2e 100%);
  --background-activated: linear-gradient(135deg, #8b1a2e 0%, #c41e3a 100%);
  --border-radius: 12px;
  --padding-top: 14px;
  --padding-bottom: 14px;
  font-weight: 600;
  font-size: 16px;
  margin-top: 8px;
  text-transform: none;
  letter-spacing: 0.5px;
}

.notice-card {
  background: #f9fafb;
  border-radius: 12px;
  padding: 16px;
  border: 1px solid #e5e7eb;
}

.notice-card ul li {
  line-height: 1.8;
}
</style>
