<script lang='ts' setup>
import { alertController, toastController } from "@ionic/vue";
import { checkmarkCircleOutline, chevronForwardOutline, closeCircleOutline, keyOutline, lockClosedOutline, shieldCheckmarkOutline } from "ionicons/icons";
import { client, safeClient } from "@/api";

const router = useRouter();
const { data: status, execute } = await safeClient(() => client.api.user.security["transaction-password"].status.get());
const hasPaymentPassword = computed(() => status.value?.enabled ?? false);
const toggleInst = ref<HTMLIonToggleElement | null>(null);

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

function handleChangePassword() {
  router.push("/security/change_password");
}

function handleChangePaymentPassword() {
  router.push("/security/change_payment_password");
}

async function handleTogglePaymentPassword() {
  if (status.value?.enabled) {
    // 禁用交易密码需要验证当前交易密码
    const alert = await alertController.create({
      header: "禁用交易密码",
      message: "请输入当前交易密码以确认操作",
      inputs: [
        {
          name: "oldPassword",
          type: "password",
          placeholder: "请输入当前交易密码",
          attributes: {
            maxlength: 20,
            inputmode: "numeric",
          },
        },
      ],
      buttons: [
        {
          text: "取消",
          role: "cancel",
        },
        {
          text: "确认",
          role: "confirm",
          handler: async (data) => {
            if (!data.oldPassword) {
              await showToast("请输入交易密码", "danger");
              return false;
            }
            if (data.oldPassword.length < 6) {
              await showToast("交易密码至少6位", "danger");
              return false;
            }

            const { error } = await safeClient(client.api.user.security["transaction-password"].delete({
              oldPassword: data.oldPassword,
            }));

            if (!error.value) {
              await showToast("交易密码功能已关闭", "warning");
              await execute();
              return true;
            }
            return false;
          },
        },
      ],
    });
    await alert.present();
  }
  else {
    // 启用交易密码需要设置新密码
    const alert = await alertController.create({
      header: "设置交易密码",
      message: "交易密码用于提现、转账等资金操作，请设置6-20位数字密码",
      inputs: [
        {
          name: "password",
          type: "password",
          placeholder: "请输入新交易密码",
          attributes: {
            maxlength: 20,
            inputmode: "numeric",
          },
        },
        {
          name: "confirmPassword",
          type: "password",
          placeholder: "请再次输入交易密码",
          attributes: {
            maxlength: 20,
            inputmode: "numeric",
          },
        },
      ],
      buttons: [
        {
          text: "取消",
          role: "cancel",
        },
        {
          text: "确认",
          handler: async (data) => {
            if (!data.password || !data.confirmPassword) {
              await showToast("请输入交易密码", "danger");
              return false;
            }
            if (data.password.length < 6) {
              await showToast("交易密码至少6位", "danger");
              return false;
            }
            if (data.password !== data.confirmPassword) {
              await showToast("两次输入的密码不一致", "danger");
              return false;
            }
            if (!/^\d+$/.test(data.password)) {
              await showToast("交易密码只能包含数字", "danger");
              return false;
            }

            const { error } = await safeClient(client.api.user.security["transaction-password"].post({
              password: data.password,
            }));

            if (!error.value) {
              await showToast("交易密码设置成功");
              await execute();
              return true;
            }
            return false;
          },
        },
      ],
    });
    await alert.present();
  }
}
</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="shieldCheckmarkOutline" class="text-2xl text-[#c41e3a]" />
          <div class="text-sm text-[#666] leading-relaxed">
            为了保障您的账户安全，建议定期更新密码，并启用交易密码保护。
          </div>
        </div>

        <!-- 安全设置列表 -->
        <div class="security-card">
          <div class="card-title">
            <ion-icon :icon="lockClosedOutline" class="text-xl text-primary" />
            <span>密码管理</span>
          </div>

          <div class="security-list">
            <!-- 交易密码状态 -->
            <div class="security-item">
              <div class="item-left">
                <ion-icon :icon="keyOutline" class="item-icon text-primary" />
                <div class="item-content">
                  <div class="item-title">
                    交易密码
                  </div>
                  <div class="item-desc">
                    用于提现、转账等资金操作
                  </div>
                </div>
              </div>
              <div class="item-right">
                <div class="flex items-center gap-2">
                  <div class="status-badge" :class="status?.enabled ? 'enabled' : 'disabled'">
                    <ion-icon
                      :icon="status?.enabled ? checkmarkCircleOutline : closeCircleOutline"
                      class="text-sm"
                    />
                    <span>{{ status?.enabled ? '已启用' : '未启用' }}</span>
                  </div>
                  <ion-toggle
                    ref="toggleInst"
                    :checked="status?.enabled"
                    color="danger"
                    @ion-change="handleTogglePaymentPassword"
                  />
                </div>
              </div>
            </div>

            <!-- 添加谷歌验证 -->
            <!-- <div class="security-item">
              <div class="item-left">
                <ion-icon :icon="shieldCheckmarkOutline" class="item-icon text-primary" />
                <div class="item-content">
                  <div class="item-title">
                    谷歌验证
                  </div>
                  <div class="item-desc">
                    用于提现、转账等资金操作
                  </div>
                </div>
              </div>
              <div class="item-right">
                <div class="flex items-center gap-2">
                  <div class="status-badge" :class="status?.enabled ? 'enabled' : 'disabled'">
                    <ion-icon
                      :icon="status?.enabled ? checkmarkCircleOutline : closeCircleOutline"
                      class="text-sm"
                    />
                    <span>{{ status?.enabled ? '已启用' : '未启用' }}</span>
                  </div>
                  <ion-toggle
                    ref="toggleInst"
                    :checked="status?.enabled"
                    color="danger"
                    @ion-change="handleTogglePaymentPassword"
                  />
                </div>
              </div>
            </div> -->

            <!-- 更改登录密码 -->
            <div class="security-item clickable" @click="handleChangePassword">
              <div class="item-left">
                <ion-icon :icon="lockClosedOutline" class="item-icon text-primary" />
                <div class="item-content">
                  <div class="item-title">
                    更改登录密码
                  </div>
                  <div class="item-desc">
                    定期更改密码，保护账户安全
                  </div>
                </div>
              </div>
              <div class="item-right">
                <ion-icon :icon="chevronForwardOutline" class="text-[#999]" />
              </div>
            </div>

            <!-- 更改交易密码 -->
            <div
              class="security-item clickable"
              :class="{ disabled: !hasPaymentPassword }"
              @click="hasPaymentPassword && handleChangePaymentPassword()"
            >
              <div class="item-left">
                <ion-icon :icon="keyOutline" class="item-icon text-primary" />
                <div class="item-content">
                  <div class="item-title">
                    更改交易密码
                  </div>
                  <div class="item-desc">
                    修改交易密码，提升资金安全
                  </div>
                </div>
              </div>
              <div class="item-right">
                <ion-icon :icon="chevronForwardOutline" class="text-[#999]" />
              </div>
            </div>
          </div>
        </div>

        <!-- 安全建议 -->
        <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>• 密码长度建议8位以上，包含字母和数字</li>
            <li>• 不要使用生日、电话等易被猜测的密码</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;
}

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

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
}

.security-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f7f8fa;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.security-item.clickable {
  cursor: pointer;
}

.security-item.clickable:active {
  transform: scale(0.98);
  background: #eef0f2;
}

.security-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.security-item.disabled:active {
  transform: none;
}

.item-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.item-icon {
  font-size: 24px;
}

.item-content {
  flex: 1;
}

.item-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.item-desc {
  font-size: 12px;
  color: #999;
  line-height: 1.4;
}

.item-right {
  display: flex;
  align-items: center;
}

.status-badge {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.enabled {
  background: #f0f9ff;
  color: #0284c7;
}

.status-badge.disabled {
  background: #fef2f2;
  color: #dc2626;
}

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

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