<script lang='ts' setup>
import { toastController } from "@ionic/vue";
import dayjs from "dayjs";
import { checkmarkCircleOutline } from "ionicons/icons";
import { client, safeClient } from "@/api";

const [start, end] = [dayjs().startOf("month"), dayjs().endOf("month")];
const { data } = await safeClient(client.api.checkIns.get({
  query: {
    startDate: start.toISOString(),
    endDate: end.toISOString(),
  },
}));

const { data: current_streak } = await safeClient(client.api.checkIns.current_streak.get());
const { data: total_count } = await safeClient(client.api.checkIns.total_days.get());
const { data: today_checkin } = await safeClient(client.api.checkIns.today.get({ query: { timezone: "IANA" } }));

const checkedInDates = computed(() => {
  if (!data.value?.data)
    return new Set<string>();
  return new Set(data.value.data.map(item => dayjs(item.checkInAt).format("YYYY-MM-DD")));
});

function isCheckedIn(day: number) {
  const dateStr = dayjs().year(start.year()).month(start.month()).date(day).format("YYYY-MM-DD");
  return checkedInDates.value.has(dateStr);
}

async function handleSignup() {
  await safeClient(client.api.checkIns.post());
  toastController.create({
    message: "签到成功！",
    duration: 2000,
    color: "success",
  }).then(toast => toast.present());
}
</script>

<template>
  <ion-page>
    <ion-content>
      <!-- 顶部横幅 -->
      <img src="@/assets/images/signup-banner.jpg" class="h-50 w-full object-cover" alt="服务页横幅">

      <div class="ion-padding">
        <!-- 主标题卡片 -->
        <section class="mt-3 mb-4">
          <div class="relative z-1">
            <div class="flex items-center justify-center gap-2 mb-4">
              <img src="@/assets/images/icon-1.png" class="size-6">
              <div class="text-4xl text-[#c41e3a] font-bold m-0">
                初心如磐 使命如坚
              </div>
              <img src="@/assets/images/icon-1.png" class="size-6">
            </div>
            <div class="text-center text-sm text-[#333] font-bold opacity-90 tracking-widest mb-1">
              讲党性 / 树新风 / 作表率 / 当先锋
            </div>
            <div class="text-center text-sm text-[#c41e3a] font-bold tracking-wider">
              红色印记，燃动今日的奋斗之光
            </div>
          </div>
        </section>

        <!-- 签到统计卡片 -->
        <section class="mb-8 mt-10">
          <div class="card rounded-2xl shadow-lg p-6">
            <div class="grid grid-cols-2 gap-4 mb-4">
              <div class="bg-white/20 backdrop-blur-sm rounded-xl p-4 text-center">
                <div class="text-xs opacity-90 mb-1">
                  连续签到
                </div>
                <div class="text-4xl font-bold mb-1">
                  {{ current_streak?.currentStreakDays }}
                </div>
                <div class="text-xs opacity-80">
                  天
                </div>
              </div>
              <div class="bg-white/20 backdrop-blur-sm rounded-xl p-4 text-center">
                <div class="text-xs opacity-90 mb-1">
                  累计签到
                </div>
                <div class="text-4xl font-bold mb-1">
                  {{ total_count?.totalDays }}
                </div>
                <div class="text-xs opacity-80">
                  天
                </div>
              </div>
            </div>

            <!-- 签到按钮 -->
            <ion-button
              expand="block"
              :disabled="today_checkin?.checkedInToday"
              @click="handleSignup"
            >
              <ion-icon slot="start" :icon="checkmarkCircleOutline" class="text-xl" />
              {{ today_checkin?.checkedInToday ? '今日已签到' : '立即签到' }}
            </ion-button>
          </div>
        </section>

        <section class="mb-8">
          <div class="card rounded-2xl shadow-lg p-5">
            <div class="flex items-center gap-2 mb-5">
              <img src="@/assets/images/icon.png" class="size-7">
              <div class="text-xl font-bold text-[#1a1a1a]">
                {{ dayjs().format('YYYY年MM月') }} 签到日历
              </div>
            </div>

            <!-- 日历表头 - 星期 -->
            <div class="grid grid-cols-7 gap-2 mb-3">
              <div
                v-for="weekday in ['日', '一', '二', '三', '四', '五', '六']"
                :key="weekday"
                class="text-center text-xs font-bold text-[#999]"
              >
                {{ weekday }}
              </div>
            </div>

            <!-- 日历日期 -->
            <div class="grid grid-cols-7 gap-2">
              <!-- 填充空白日期（月初之前） -->
              <div
                v-for="blank in Array.from({ length: start.day() })"
                :key="`blank-${blank}`"
                class="aspect-square"
              />

              <!-- 实际日期 -->
              <div
                v-for="day in start.daysInMonth()"
                :key="day"
                class="aspect-square flex-center"
              >
                <div
                  class="w-full h-full rounded-lg flex flex-col items-center justify-center text-sm font-medium transition-all relative"
                  :class="isCheckedIn(day)
                    ? 'bg-linear-to-br from-[#c41e3a] to-[#8b1a2e] text-white shadow-md'
                    : dayjs().date() === day
                      ? 'bg-[#fff7f0] text-[#c41e3a] border-2 border-[#c41e3a]'
                      : 'bg-gray-50 text-[#666]'"
                >
                  <span class="text-base">{{ day }}</span>
                </div>
              </div>
            </div>

            <!-- 图例说明 -->
            <div class="flex items-center justify-center gap-4 mt-4 pt-4 border-t border-gray-100">
              <div class="flex items-center gap-2">
                <div class="w-4 h-4 rounded bg-linear-to-br from-[#c41e3a] to-[#8b1a2e]" />
                <span class="text-xs text-[#666]">已签到</span>
              </div>
              <div class="flex items-center gap-2">
                <div class="w-4 h-4 rounded bg-[#fff7f0] border-2 border-[#c41e3a]" />
                <span class="text-xs text-[#666]">今天</span>
              </div>
              <div class="flex items-center gap-2">
                <div class="w-4 h-4 rounded bg-gray-50" />
                <span class="text-xs text-[#666]">未签到</span>
              </div>
            </div>
          </div>
        </section>
      </div>
    </ion-content>
  </ion-page>
</template>

<style lang='css' scoped>
.signup-btn {
  --background: white;
  --color: #c41e3a;
  --border-radius: 12px;
  --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  font-weight: 700;
  font-size: 16px;
  height: 50px;
  text-transform: none;
}

.card {
  background: linear-gradient(180deg, #ffeef1, #ffffff 15%);
}
ion-datetime {
  --background: transparent;
}
</style>
