<script lang='ts' setup>
import type { Treaty } from "@elysiajs/eden";
import type { InfiniteScrollCustomEvent } from "@ionic/vue";
import type { TreatyQuery } from "@/api/types";
import { modalController } from "@ionic/vue";
import { calendarOutline, cardOutline, timeOutline, trendingUpOutline } from "ionicons/icons";
import { client, safeClient } from "@/api";
import Subscribe from "./components/subscribe.vue";

type Product = Treaty.Data<typeof client.api.subscription.products.get>["data"][number];
type ProductQuery = TreatyQuery<typeof client.api.subscription.products.get>;

const modalInst = useTemplateRef<ModalInstance>("modalInst");
const [query] = useResetRef<ProductQuery>({
  offset: 0,
  limit: 10,
});
const data = ref<Product[]>([]);
const isFinished = ref(false);
const walletStore = useWalletStore();

async function fetchData() {
  const { data: responseData } = await safeClient(client.api.subscription.products.get({ query: { ...query.value } }));
  data.value.push(...(responseData.value?.data || []));
  isFinished.value = responseData.value?.pagination.hasNextPage === false;
}
async function handleInfinite(event: InfiniteScrollCustomEvent) {
  if (isFinished.value) {
    event.target.complete();
    event.target.disabled = true;
    return;
  }
  query.value.offset! += query.value.limit!;
  await fetchData();
  setTimeout(() => {
    event.target.complete();
  }, 500);
}

function handleProductClick(product: Product) {
  console.log("查看产品:", product.name);
  // TODO: 跳转到产品详情
}

async function handleSubscribe(product: Product) {
  console.log("申购产品:", product.name);
  await walletStore.syncWallets();
  const wallets = walletStore.wallets.filter(w => w.walletType.allowTransaction === true);
  const modal = await modalController.create({
    component: Subscribe,
    componentProps: {
      productId: product.id,
      wallets,
      onClose: () => {
        modal.dismiss();
      },
      onSuccess: () => {
        modal.dismiss();
        console.log("申购成功");
      },
    },
  });
  await modal.present();
}

onMounted(() => {
  fetchData();
});
</script>

<template>
  <ion-page>
    <ion-header class="ion-no-border">
      <ion-toolbar class="ion-toolbar">
        <img slot="start" src="@/assets/images/icon-1.png" class="h-8 w-8 ml-2" alt="Logo">
        <ion-title>锐意进取</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content :fullscreen="true">
      <img src="@/assets/images/product-banner.jpg" class="h-50 w-full object-cover" alt="服务页横幅">

      <!-- 基金产品列表 -->
      <section class="mb-5 -mt-5 ion-padding-horizontal">
        <div class="flex justify-between items-center mb-4">
          <div class="flex justify-between items-center mb-4">
            <div class="flex items-center gap-2">
              <img src="@/assets/images/icon.png" class="size-7">
              <div class="text-xl font-bold text-[#1a1a1a]">
                基金产品
              </div>
            </div>
          </div>
        </div>

        <empty v-if="data.length === 0" message="暂无基金产品信息" />
        <div v-else class="flex flex-col gap-4">
          <div
            v-for="product in data"
            :key="product.id"
            class="bg-white rounded-2xl overflow-hidden shadow-sm cursor-pointer transition-all active:translate-y-0.5 active:shadow-sm"
            @click="handleProductClick(product)"
          >
            <!-- 顶部缩略图 -->
            <div class="relative w-full h-45 overflow-hidden bg-gradient-to-br from-[#f5f5f5] to-[#e8e8e8]">
              <img v-if="product.coverImage" :src="product.coverImage" :alt="product.name" class="w-full h-full object-cover">
              <div class="fund-tag absolute top-3 left-3 bg-gradient-to-br from-[#c41e3a] to-[#8b1a2e] text-white px-3 py-1 rounded-xl text-xs font-semibold shadow-lg">
                推荐
              </div>
            </div>

            <!-- 底部信息 -->
            <div class="p-4">
              <div class="text-xl font-bold text-[#1a1a1a] mb-2 leading-snug">
                {{ product.name }}
              </div>
              <div class="flex items-center gap-1 text-xs text-[#999] mb-3">
                <ion-icon :icon="timeOutline" class="text-sm" />
                <span>申购截止：{{ useDateFormat(product.subscribeEndAt, 'YYYY-MM-DD') }}</span>
              </div>

              <!-- 产品信息 -->
              <div class="grid grid-cols-3 gap-3 mb-3">
                <div class="flex flex-col">
                  <span class="text-xs text-[#999] mb-1">当前价格</span>
                  <span class="text-lg font-bold text-[#c41e3a]">¥{{ Number(product.price) }}</span>
                </div>
                <div class="flex flex-col">
                  <span class="text-xs text-[#999] mb-1">到期收益</span>
                  <span class="text-lg font-bold text-[#52c41a] flex items-center gap-0.5">
                    ¥{{ Number(product.maturityYield) }}
                  </span>
                </div>
                <div class="flex flex-col">
                  <span class="text-xs text-[#999] mb-1">周期(天)</span>
                  <span class="text-lg font-bold text-[#1a1a1a] flex items-center gap-0.5">
                    <ion-icon :icon="calendarOutline" class="text-base" />
                    {{ Number(product.cycleDays) }}
                  </span>
                </div>
              </div>

              <!-- 申购按钮 -->
              <ion-button
                expand="block"
                class="subscribe-btn"
                @click.stop="handleSubscribe(product)"
              >
                <ion-icon slot="start" :icon="cardOutline" />
                我要申购
              </ion-button>

              <ion-modal />
            </div>
          </div>
        </div>
      </section>
    </ion-content>
  </ion-page>
</template>

<style lang='css' scoped>
.header-toolbar {
  --background: #c32120;
  --color: #fff;
}

.header-bg {
  background: linear-gradient(180deg, #c32120 0%, transparent 100%);
}

.fund-tag {
  backdrop-filter: blur(4px);
}

.subscribe-btn {
  --background: linear-gradient(135deg, #c41e3a 0%, #8b1a2e 100%);
  --background-activated: linear-gradient(135deg, #8b1a2e 0%, #6d1523 100%);
  --border-radius: 12px;
  --box-shadow: 0 2px 8px rgba(196, 30, 58, 0.3);
  font-weight: 600;
  font-size: 15px;
  height: 44px;
  text-transform: none;
}

.subscribe-btn::part(native) {
  font-weight: 600;
}
</style>
