<script lang='ts' setup>
import { actionSheetController, alertController, toastController } from "@ionic/vue";
import {
  addOutline,
  cardOutline,
  checkmarkCircle,
  ellipsisHorizontal,
  star,
} from "ionicons/icons";
import { client, safeClient } from "@/api";

const { t } = useI18n();
const router = useRouter();
const { syncBankAccounts } = useWalletStore();

const { data, execute, onFetchResponse } = await safeClient(() => client.api.bank_account.get());
const bankCards = computed(() => data.value?.data || []);

onFetchResponse((data) => {
  data?.data && syncBankAccounts(data.data);
});

function handleAddCard() {
  router.push("/trade-settings/bank-management/add");
}

async function handleCardOptions(card: any) {
  const actionSheet = await actionSheetController.create({
    header: card.bankName,
    buttons: [
      {
        text: card.isDefault ? t("bankCard.list.defaultCard") : t("bankCard.list.setDefault"),
        handler: () => {
          if (!card.isDefault) {
            handleSetDefault(card);
          }
        },
      },
      {
        text: t("bankCard.list.delete"),
        role: "destructive",
        handler: () => {
          handleDeleteCard(card);
        },
      },
      {
        text: t("bankCard.list.cancel"),
        role: "cancel",
      },
    ],
  });

  await actionSheet.present();
}

// 设置默认银行卡
async function handleSetDefault(card: any) {
  await safeClient(() => client.api.bank_account({ id: card.id }).set_default.post());
  const toast = await toastController.create({
    message: t("bankCard.messages.setDefaultSuccess"),
    duration: 2000,
    position: "bottom",
    color: "success",
  });

  await toast.present();
  execute();
}

// 删除银行卡
async function handleDeleteCard(card: any) {
  const alert = await alertController.create({
    header: "删除银行卡",
    message: `确定要删除 ${card.bankName} (${card.accountName}) 吗？此操作无法撤销。`,
    buttons: [
      {
        text: "取消",
        role: "cancel",
      },
      {
        text: "删除",
        role: "destructive",
        handler: async () => {
          await safeClient(() => client.api.bank_account({ id: card.id }).delete());
          const toast = await toastController.create({
            message: t("bankCard.messages.deleteSuccess"),
            duration: 2000,
            position: "bottom",
            color: "success",
          });
          await toast.present();
          execute();
        },
      },
    ],
  });

  await alert.present();
}

onUpdated(() => {
  execute();
});
</script>

<template>
  <IonPage>
    <ion-header>
      <ion-toolbar class="ion-toolbar">
        <ui-back-button slot="start" />
        <ion-title>{{ t('bankCard.management') }}</ion-title>
      </ion-toolbar>
    </ion-header>

    <IonContent :fullscreen="true">
      <div class="min-h-full">
        <div v-if="bankCards?.length === 0" class="flex flex-col items-center justify-center min-h-[60vh] p-8 text-center">
          <div class="w-20 h-20 rounded-full flex items-center justify-center mb-6 shadow-lg">
            <ion-icon :icon="cardOutline" class="text-4xl text-white" />
          </div>
          <h3 class="text-xl font-semibold text-text-200 mb-2">
            {{ t('bankCard.empty.title') }}
          </h3>
          <p class="text-sm leading-relaxed mb-8">
            {{ t('bankCard.empty.description') }}
          </p>
          <ion-button expand="block" fill="solid" @click="handleAddCard">
            <ion-icon slot="start" :icon="addOutline" />
            {{ t('bankCard.empty.addButton') }}
          </ion-button>
        </div>

        <div v-else class="p-4">
          <div class="mb-6">
            <ion-button expand="block" @click="handleAddCard">
              <ion-icon slot="start" :icon="addOutline" class="text-xl" />
              {{ t('bankCard.list.addCard') }}
            </ion-button>
          </div>

          <!-- 银行卡列表 -->
          <div class="mb-8">
            <div class="mb-4">
              <span class="text-sm text-gray-600 dark:text-gray-400 font-medium">{{ t('bankCard.list.boundCards') }} ({{ bankCards?.length }})</span>
            </div>

            <div
              v-for="card in bankCards"
              :key="card.id"
              class="bg-faint rounded-2xl mb-4 overflow-hidden shadow-sm transition-all duration-300 relative"
            >
              <div class="p-5 flex items-center justify-between">
                <div class="flex items-center flex-1">
                  <div class="w-12 h-12 rounded-xl flex items-center justify-center mr-4 font-bold text-sm shadow-sm bg-[#0F5AA6]">
                    <span class="text-white">{{ card.bankCode }}</span>
                  </div>
                  <div class="flex-1">
                    <div class="flex items-center gap-2 mb-1">
                      <h4 class="text-lg font-semibold m-0">
                        {{ card.bankName }}
                      </h4>
                      <span
                        v-if="card.isDefault"
                        class="bg-linear-to-r from-green-500 to-emerald-600 text-white text-xs px-2 py-0.5 rounded-lg font-medium"
                      >
                        {{ t('bankCard.list.defaultCard') }}
                      </span>
                    </div>
                    <p class="text-base m-0 mb-2 tracking-wider">
                      {{ card.maskAccountNumber }}
                    </p>
                    <div class="flex gap-4 text-sm">
                      <ui-tag size="small">
                        {{ t('bankCard.list.debitCard') }}
                      </ui-tag>
                      <span>{{ card.accountName }}</span>
                    </div>
                  </div>
                </div>

                <div class="ml-4">
                  <ion-button
                    fill="clear"
                    @click="handleCardOptions(card)"
                  >
                    <ion-icon slot="icon-only" :icon="ellipsisHorizontal" />
                  </ion-button>
                </div>
              </div>

              <!-- 默认标识条 -->
              <div v-if="card.isDefault" class="bg-linear-to-r from-green-500 to-emerald-600 text-white px-5 py-2 flex items-center gap-2 text-sm font-medium">
                <ion-icon :icon="star" class="text-base" />
                <span>{{ t('bankCard.list.defaultCard') }}</span>
              </div>
            </div>
          </div>

          <!-- 底部提示 -->
          <div class="rounded-xl p-4 mt-4 b-2px bg-faint">
            <div class="flex items-center gap-3 mb-3 text-sm">
              <ion-icon :icon="checkmarkCircle" class="text-base text-green-500" />
              <span>{{ t('bankCard.tips.encryption') }}</span>
            </div>
            <div class="flex items-center gap-3 text-sm">
              <ion-icon :icon="checkmarkCircle" class="text-base text-green-500" />
              <span>{{ t('bankCard.tips.support') }}</span>
            </div>
          </div>
        </div>
      </div>
    </IonContent>
  </IonPage>
</template>

<style lang="css" scoped></style>
