<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 bg-[#171717] 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-gray-600 dark:text-gray-400 text-sm leading-relaxed mb-8">
            {{ t('bankCard.empty.description') }}
          </p>
          <ion-button
            expand="block"
            fill="outline"
            @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">
            <div
              class="bg-gray-50 dark:bg-gray-900 rounded-xl p-4 flex items-center cursor-pointer transition-all duration-300 border-2 border-dashed border-gray-200 dark:border-gray-600"
              @click="handleAddCard"
            >
              <div class="w-10 h-10 rounded-full bg-linear-to-r from-green-500 to-emerald-600 flex items-center justify-center mr-3">
                <ion-icon :icon="addOutline" class="text-white text-xl" />
              </div>
              <span class="font-semibold text-#151515 dark:text-white">{{ t('bankCard.list.addCard') }}</span>
            </div>
          </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-gray-50 dark:bg-gray-900 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 text-white 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 text-#151515 dark:text-white 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-gray-600 dark:text-gray-400 text-base m-0 mb-2 tracking-wider">
                      {{ card.maskAccountNumber }}
                    </p>
                    <div class="flex gap-4 text-sm text-gray-500 dark:text-gray-400">
                      <span class="px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded-md text-xs">
                        {{ t('bankCard.list.debitCard') }}
                      </span>
                      <span>{{ card.accountName }}</span>
                    </div>
                  </div>
                </div>

                <div class="ml-4">
                  <ion-button
                    fill="clear"
                    class="[--color:var(--color-gray-600)] [--background:transparent] w-10 h-10 hover:[--background:var(--color-gray-100)]"
                    @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-gray-50 dark:bg-gray-900">
            <div class="flex items-center gap-3 mb-3 text-sm text-gray-600 dark:text-gray-400">
              <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 text-gray-600 dark:text-gray-400">
              <ion-icon :icon="checkmarkCircle" class="text-base text-green-500" />
              <span>{{ t('bankCard.tips.support') }}</span>
            </div>
          </div>
        </div>
      </div>
    </IonContent>
  </IonPage>
</template>

<style scoped>
@media (max-width: 768px) {
  .p-4 {
    padding: 0.75rem;
  }

  .p-8 {
    padding: 1.5rem;
  }

  .w-20 {
    width: 4.25rem;
    height: 4.25rem;
  }

  .p-5 {
    padding: 1rem;
  }

  .w-12 {
    width: 2.75rem;
    height: 2.75rem;
    font-size: 0.75rem;
  }

  .text-lg {
    font-size: 1rem;
  }
}
</style>
