<script lang='ts' setup>
import type { Treaty } from "@elysiajs/eden";
import { alertController, toastController } from "@ionic/vue";
import { addOutline, callOutline, checkmarkCircleOutline, createOutline, locationOutline, trashOutline } from "ionicons/icons";
import { client, safeClient } from "@/api";

type Address = Treaty.Data<typeof client.api.shipping_address.get>["data"][number];

const router = useRouter();
const { data: addresses, execute } = await safeClient(() => client.api.shipping_address.get());

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

function handleAdd() {
  router.push("/address/add");
}

function handleEdit(address: Address) {
  router.push(`/address/add?id=${address.id}`);
}
async function handleSetDefault(address: Address) {
  if (address.isDefault) {
    return;
  }
  await safeClient(client.api.shipping_address({ id: address.id }).default.post());
  await showToast("已设为默认地址");
  execute();
}

async function handleDelete(address: Address) {
  const alert = await alertController.create({
    header: "确认删除",
    message: `确定要删除"${address.recipientName}"的收货地址吗？`,
    buttons: [
      {
        text: "取消",
        role: "cancel",
      },
      {
        text: "删除",
        role: "destructive",
        handler: async () => {
          await safeClient(client.api.shipping_address({ id: address.id }).delete());
          await showToast("删除成功");
          execute();
        },
      },
    ],
  });

  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-buttons slot="end">
          <ion-button @click="handleAdd">
            <ion-icon slot="icon-only" :icon="addOutline" />
          </ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>

    <ion-content>
      <div v-if="addresses?.data.length === 0" class="empty-state">
        <empty title="暂无收货地址">
          <template #icon>
            <ion-icon :icon="locationOutline" class="empty-icon" />
          </template>
          <template #extra>
            <ion-button class="add-button" @click="handleAdd">
              <ion-icon slot="start" :icon="addOutline" />
              添加收货地址
            </ion-button>
          </template>
        </empty>
      </div>

      <div v-else class="ion-padding">
        <div class="space-y-3">
          <div
            v-for="address in addresses?.data"
            :key="address.id"
            class="address-card"
          >
            <!-- 地址信息 -->
            <div class="address-info">
              <div class="flex items-center justify-between mb-3">
                <div class="flex items-center gap-2">
                  <ion-icon :icon="locationOutline" class="text-xl text-primary" />
                  <span class="name">{{ address.recipientName }}</span>
                  <span class="phone">{{ address.phoneNumber }}</span>
                </div>
                <ion-badge v-if="address.isDefault" color="danger" class="default-badge">
                  默认
                </ion-badge>
              </div>

              <div class="address-text">
                {{ address.detailAddress }}
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="address-actions">
              <ion-button
                fill="clear"
                size="small"
                :color="address.isDefault ? 'primary' : 'medium'"
                @click="handleSetDefault(address)"
              >
                <ion-icon slot="start" :icon="checkmarkCircleOutline" />
                {{ address.isDefault ? '默认地址' : '设为默认' }}
              </ion-button>

              <div class="flex gap-2">
                <ion-button
                  fill="clear"
                  size="small"
                  color="medium"
                  @click="handleEdit(address)"
                >
                  <ion-icon slot="start" :icon="createOutline" />
                  编辑
                </ion-button>

                <ion-button
                  fill="clear"
                  size="small"
                  color="danger"
                  @click="handleDelete(address)"
                >
                  <ion-icon slot="start" :icon="trashOutline" />
                  删除
                </ion-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-if="addresses?.data && addresses.data.length > 0" class="fixed-bottom">
        <ion-button expand="block" class="add-button" @click="handleAdd">
          <ion-icon slot="start" :icon="addOutline" />
          添加新地址
        </ion-button>
      </div>
    </ion-content>
  </ion-page>
</template>

<style lang='css' scoped>
.address-card {
  background: white;
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.address-info {
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 12px;
}

.name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.phone {
  font-size: 14px;
  color: #666;
}

.default-badge {
  font-size: 11px;
  padding: 2px 8px;
}

.address-text {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin-top: 8px;
}

.address-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-actions ion-button {
  --padding-start: 8px;
  --padding-end: 8px;
  font-size: 13px;
  text-transform: none;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
  padding: 40px 20px;
}

.empty-icon {
  font-size: 80px;
  color: #ddd;
}

.add-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: 15px;
  text-transform: none;
  letter-spacing: 0.5px;
  margin-top: 12px;
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px 16px;
  background: white;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.08);
  z-index: 10;
  padding-bottom: calc(12px + var(--ion-safe-area-bottom));
}
</style>
