<script lang='ts' setup>
import type { Treaty } from "@elysiajs/eden";
import type { TreatyBody } from "@/api/types";
import { toastController } from "@ionic/vue";
import { callOutline, locationOutline, personOutline } from "ionicons/icons";
import zod from "zod";
import { client, safeClient } from "@/api";

type Address = TreatyBody<typeof client.api.shipping_address.post>;

const router = useRouter();
const route = useRoute();

const formData = ref<Address>({
  recipientName: "",
  phoneNumber: "",
  detailAddress: "",
  isDefault: false,
});

const isSubmitting = ref(false);
const isEditMode = computed(() => !!route.query.id);

// 表单验证 Schema
const AddressSchema = zod.object({
  recipientName: zod
    .string()
    .max(20, "姓名长度不能超过20个字符"),

  phoneNumber: zod
    .string()
    .min(1, "请输入手机号")
    .regex(/^1[3-9]\d{9}$/, "请输入正确的手机号码"),

  detailAddress: zod
    .string()
    .min(5, "请输入详细地址")
    .max(200, "地址长度不能超过200个字符"),
});

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

onMounted(async () => {
  if (isEditMode.value) {
    const id = route.query.id as string;
    const { data } = await safeClient(client.api.shipping_address({ id }).get());
    formData.value = {
      recipientName: data.value?.recipientName || "",
      phoneNumber: data.value?.phoneNumber || "",
      detailAddress: data.value?.detailAddress || "",
      isDefault: data.value?.isDefault || false,
    };
  }
});

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

  isSubmitting.value = true;
  try {
    if (isEditMode.value) {
      const id = route.query.id as string;
      await safeClient(client.api.shipping_address({ id }).patch({
        ...formData.value,
      }));
    }
    else {
      await safeClient(client.api.shipping_address.post({
        ...formData.value,
      }));
    }

    await showToast(isEditMode.value ? "地址修改成功" : "地址添加成功", "success");
    router.back();
  }
  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>{{ isEditMode ? '编辑地址' : '添加地址' }}</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content class="ion-padding">
      <div class="space-y-5">
        <!-- 提示信息 -->
        <div class="info-card">
          <ion-icon :icon="locationOutline" 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.recipientName"
                  type="text"
                  placeholder="请输入收货人姓名"
                  class="custom-input"
                  :maxlength="20"
                />
              </ion-item>
            </div>

            <!-- 手机号码 -->
            <div class="form-item">
              <div class="flex items-center gap-2 mb-2">
                <ion-icon :icon="callOutline" class="text-lg text-primary" />
                <label class="form-label">手机号码</label>
              </div>
              <ion-item lines="none" class="input-item">
                <ion-input
                  v-model="formData.phoneNumber"
                  type="tel"
                  placeholder="请输入手机号码"
                  class="custom-input"
                  :maxlength="11"
                />
              </ion-item>
            </div>

            <!-- 详细地址 -->
            <div class="form-item">
              <div class="flex items-center gap-2 mb-2">
                <ion-icon :icon="locationOutline" class="text-lg text-primary" />
                <label class="form-label">详细地址</label>
              </div>
              <ion-item lines="none" class="input-item textarea-item">
                <ion-textarea
                  v-model="formData.detailAddress"
                  placeholder="请输入详细地址（省市区街道门牌号等）"
                  class="custom-textarea"
                  :rows="4"
                  :maxlength="200"
                  auto-grow
                />
              </ion-item>
            </div>

            <!-- 设为默认地址 -->
            <div class="form-item">
              <div class="flex items-center justify-between">
                <label class="form-label">设为默认地址</label>
                <ion-toggle v-model="formData.isDefault" color="danger" />
              </div>
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <ion-button
          expand="block"
          class="submit-button"
          :disabled="isSubmitting"
          @click="handleSubmit"
        >
          <ion-spinner v-if="isSubmitting" name="crescent" />
          <span v-else>{{ isEditMode ? '保存修改' : '保存地址' }}</span>
        </ion-button>
      </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;
}

.textarea-item {
  --min-height: auto;
  --padding-top: 12px;
  --padding-bottom: 12px;
}

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

.custom-textarea {
  --placeholder-color: #999;
  --placeholder-opacity: 1;
  font-size: 15px;
  min-height: 100px;
}

.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;
}
</style>
