<script lang='ts' setup>
import { Camera, CameraResultType, CameraSource } from "@capacitor/camera";
import { actionSheetController, toastController } from "@ionic/vue";
import { cameraOutline, cardOutline, checkmarkCircleOutline, imageOutline, personOutline } from "ionicons/icons";
import zod from "zod";
import { client, safeClient } from "@/api";

const router = useRouter();

interface RealNameFormData {
  kycMethod: "id_card";
  documentName: string;
  documentNumber: string;
  fileId1: string;
  fileId2: string;
}

const formData = ref<RealNameFormData>({
  kycMethod: "id_card",
  documentName: "",
  documentNumber: "",
  fileId1: "",
  fileId2: "",
});
const image1 = ref<string>("");
const image2 = ref<string>("");

const isSubmitting = ref(false);
const status = ref<"unverified" | "pending" | "approved" | "rejected">("unverified");

// 计算属性：是否可以编辑
const canEdit = computed(() => {
  return status.value === "unverified" || status.value === "rejected";
});

// 计算属性：状态文本和颜色
const statusInfo = computed(() => {
  switch (status.value) {
    case "pending":
      return { text: "审核中", color: "#faad14", bg: "#fff7e6" };
    case "approved":
      return { text: "已通过", color: "#52c41a", bg: "#f6ffed" };
    case "rejected":
      return { text: "已拒绝", color: "#f5222d", bg: "#fff1f0" };
    default:
      return { text: "未认证", color: "#999", bg: "#f7f8fa" };
  }
});

// 表单验证 Schema
const RealNameSchema = zod.object({
  documentName: zod
    .string()
    .min(2, "请输入真实姓名")
    .max(10, "姓名长度不能超过10个字符"),

  documentNumber: zod
    .string()
    .min(1, "请输入身份证号码")
    .regex(
      /(^\d{15}$)|(^\d{18}$)|(^\d{17}([\dX])$)/i,
      "请输入正确的身份证号码",
    ),

  fileId1: zod
    .string()
    .min(1, "请上传身份证正面照片"),

  fileId2: zod
    .string()
    .min(1, "请上传身份证反面照片"),
});

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 takePicture(type: "front" | "back") {
  try {
    const image = await Camera.getPhoto({
      quality: 80,
      allowEditing: false,
      resultType: CameraResultType.DataUrl,
      source: CameraSource.Camera,
      width: 1200,
      height: 800,
    });

    if (image.dataUrl) {
      if (type === "front") {
        formData.value.fileId1 = image.dataUrl;
      }
      else {
        formData.value.fileId2 = image.dataUrl;
      }
    }
  }
  catch (error: any) {
    if (error?.message !== "User cancelled photos app") {
      await showToast("拍照失败，请重试", "danger");
    }
  }
}

async function selectFromGallery(type: "front" | "back") {
  try {
    const image = await Camera.getPhoto({
      quality: 80,
      allowEditing: false,
      resultType: CameraResultType.DataUrl,
      source: CameraSource.Photos,
      width: 1200,
      height: 800,
    });
    const file = new File(
      [image.dataUrl ? await (await fetch(image.dataUrl)).blob() : ""],
      "upload.jpeg",
      { type: "image/jpeg" },
    );
    const fileId = await uploadToS3(file, {
      fetchOptions: {
        fileName: `idCard_${Date.now()}.jpeg`,
        fileSize: image.dataUrl?.length || 0,
        businessType: "kyc_document",
      },
    });

    if (image.dataUrl) {
      if (type === "front") {
        formData.value.fileId1 = fileId;
        image1.value = image.dataUrl;
      }
      else {
        formData.value.fileId2 = fileId;
        image2.value = image.dataUrl;
      }
    }
  }
  catch (error: any) {
    if (error?.message !== "User cancelled photos app") {
      await showToast("选择图片失败，请重试", "danger");
    }
  }
}

async function showImageSourceOptions(type: "front" | "back") {
  const actionSheet = await actionSheetController.create({
    header: "选择图片来源",
    buttons: [
      {
        text: "拍照",
        handler: () => takePicture(type),
      },
      {
        text: "从相册选择",
        handler: () => selectFromGallery(type),
      },
      {
        text: "取消",
        role: "cancel",
      },
    ],
  });

  await actionSheet.present();
}

async function handleSubmit() {
  const result = RealNameSchema.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.kyc({ kycMethod: "id_card" }).post({
      ...formData.value,
    }));

    await showToast("实名认证提交成功，等待审核", "success");
    router.back();
  }
  catch (error) {
    await showToast("提交失败，请重试", "danger");
  }
  finally {
    isSubmitting.value = false;
  }
}

onMounted(async () => {
  const { data } = await safeClient(client.api.kyc({ kycMethod: "id_card" }).get(), { silent: true });
  if (data.value) {
    formData.value.documentName = data.value.documentName || "";
    formData.value.documentNumber = data.value.documentNumber || "";
    formData.value.fileId1 = data.value.fileId1 || "";
    formData.value.fileId2 = data.value.fileId2 || "";
    status.value = data.value?.status || "unverified";
  }
  const { data: urls } = await safeClient(client.api.file_storage.access_urls.post({
    fileIds: [formData.value.fileId1, formData.value.fileId2],
  }));
  image1.value = urls.value?.[0].url || "";
  image2.value = urls.value?.[1].url || "";
});
</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 v-if="status !== 'unverified'" class="status-card" :style="{ background: statusInfo.bg, borderColor: statusInfo.color }">
          <ion-icon :icon="checkmarkCircleOutline" class="text-2xl" :style="{ color: statusInfo.color }" />
          <div class="flex-1">
            <div class="text-sm font-semibold" :style="{ color: statusInfo.color }">
              认证状态：{{ statusInfo.text }}
            </div>
            <div v-if="status === 'pending'" class="text-xs text-[#666] mt-1">
              您的认证资料正在审核中，请耐心等待
            </div>
            <div v-else-if="status === 'approved'" class="text-xs text-[#666] mt-1">
              您已完成实名认证
            </div>
            <div v-else-if="status === 'rejected'" class="text-xs text-[#666] mt-1">
              认证未通过，请重新提交资料
            </div>
          </div>
        </div>

        <!-- 提示信息 -->
        <div v-if="status === 'unverified'" class="info-card">
          <ion-icon :icon="checkmarkCircleOutline" 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="personOutline" class="text-lg text-primary" />
                <label class="form-label">真实姓名</label>
              </div>
              <ion-item lines="none" class="input-item">
                <ion-input
                  v-model="formData.documentName"
                  type="text"
                  placeholder="请输入真实姓名"
                  class="custom-input"
                  :disabled="!canEdit"
                />
              </ion-item>
            </div>

            <!-- 身份证号码 -->
            <div class="form-item">
              <div class="flex items-center gap-2 mb-2">
                <ion-icon :icon="cardOutline" class="text-lg text-primary" />
                <label class="form-label">身份证号码</label>
              </div>
              <ion-item lines="none" class="input-item">
                <ion-input
                  v-model="formData.documentNumber"
                  type="text"
                  placeholder="请输入身份证号码"
                  class="custom-input"
                  :maxlength="18"
                  :disabled="!canEdit"
                />
              </ion-item>
            </div>

            <!-- 身份证正面 -->
            <div class="form-item">
              <div class="flex items-center gap-2 mb-2">
                <ion-icon :icon="cardOutline" class="text-lg text-primary" />
                <label class="form-label">身份证正面</label>
              </div>
              <div
                class="upload-box"
                :class="{ 'upload-disabled': !canEdit }"
                @click="canEdit && showImageSourceOptions('front')"
              >
                <div v-if="!formData.fileId1" class="upload-placeholder">
                  <ion-icon :icon="cameraOutline" class="text-4xl text-[#999]" />
                  <div class="text-sm text-[#999] mt-2">
                    点击拍照或选择照片
                  </div>
                  <div class="text-xs text-[#bbb] mt-1">
                    请上传人像面
                  </div>
                </div>
                <img
                  v-else
                  :src="image1"
                  alt="身份证正面"
                  class="uploaded-image"
                >
              </div>
            </div>

            <!-- 身份证反面 -->
            <div class="form-item">
              <div class="flex items-center gap-2 mb-2">
                <ion-icon :icon="cardOutline" class="text-lg text-primary" />
                <label class="form-label">身份证反面</label>
              </div>
              <div
                class="upload-box"
                :class="{ 'upload-disabled': !canEdit }"
                @click="canEdit && showImageSourceOptions('back')"
              >
                <div v-if="!formData.fileId2" class="upload-placeholder">
                  <ion-icon :icon="cameraOutline" class="text-4xl text-[#999]" />
                  <div class="text-sm text-[#999] mt-2">
                    点击拍照或选择照片
                  </div>
                  <div class="text-xs text-[#bbb] mt-1">
                    请上传国徽面
                  </div>
                </div>
                <img
                  v-else
                  :src="image2"
                  alt="身份证反面"
                  class="uploaded-image"
                >
              </div>
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <ion-button
          v-if="canEdit"
          expand="block"
          class="submit-button"
          :disabled="isSubmitting"
          @click="handleSubmit"
        >
          <ion-spinner v-if="isSubmitting" name="crescent" />
          <span v-else>{{ status === 'rejected' ? '重新提交' : '提交认证' }}</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>• 请确保身份证照片清晰完整，信息可见</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-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;
}

.upload-box {
  position: relative;
  width: 100%;
  aspect-ratio: 16/10;
  background: #f7f8fa;
  border: 2px dashed #ddd;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-box:active {
  transform: scale(0.98);
  border-color: var(--ion-color-primary);
}

.upload-disabled {
  opacity: 0.6;
  cursor: not-allowed;
  pointer-events: none;
}

.status-card {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  border-radius: 12px;
  border: 1px solid;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 20px;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.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>
