<script setup lang="ts">
import type { InfiniteScrollCustomEvent, RefresherCustomEvent } from "@ionic/vue";
import type { NotificationBody, NotificationData } from "@/api/types";
import { toastController } from "@ionic/vue";
import IcBaselineNotificationsNone from "~icons/ic/baseline-notifications-none";
import IconParkOutlineClearFormat from "~icons/icon-park-outline/clear-format";
import MaterialSymbolsAndroidContacts from "~icons/material-symbols/android-contacts";
import { client, safeClient } from "@/api";
import { NotificationTypeIcon } from "./enum";

const { t } = useI18n();
const router = useRouter();
const [query] = useResetRef<NotificationBody>({
  limit: 20,
  offset: 0,
});
const data = ref<NotificationData[]>([]);
const isFinished = ref(false);

async function fetchData() {
  const { data: responseData } = await safeClient(() => client.api.notifications.get({
    query: query.value,
  }));
  data.value.push(...(responseData.value?.data || []));
  isFinished.value = (responseData.value?.data.length || 0) < query.value.limit!;
}
function resetRwaData() {
  query.value.offset = 0;
  data.value = [];
  isFinished.value = false;
}
async function handleRefresh(event: RefresherCustomEvent) {
  resetRwaData();
  await fetchData();
  setTimeout(() => {
    event.target.complete();
  }, 500);
}
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 handleItemClick(item: NotificationData) {
  safeClient(client.api.notifications({ id: item.id }).read.post()).then(() => {
    item.status = "read";
  });
  router.push(`/notify/${item.id}`);
}
async function handleAllRead() {
  await safeClient(() => client.api.notifications["batch-read"].post({
    ids: [],
  }));
  const toast = await toastController.create({
    message: t("notify.markAllReadSuccess"),
    duration: 2000,
    position: "bottom",
    color: "success",
  });
  await toast.present();
  data.value.forEach((item) => {
    item.status = "read";
  });
}
function getConfigByType(type: string) {
  return NotificationTypeIcon[type];
}

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

<template>
  <IonPage>
    <IonHeader class="ion-no-border">
      <ion-toolbar class="ion-toolbar">
        <ion-button slot="end" fill="clear" @click="handleAllRead">
          <IconParkOutlineClearFormat slot="icon-only" />
        </ion-button>
        <!-- <ion-button slot="end" fill="clear">
          <MaterialSymbolsAndroidContacts slot="icon-only" />
        </ion-button> -->
        <ion-title>{{ t('notify.title') }}</ion-title>
      </ion-toolbar>
    </IonHeader>
    <IonContent :fullscreen="true">
      <!-- <ion-searchbar placeholder="Search" /> -->
      <ion-refresher slot="fixed" @ion-refresh="handleRefresh($event)">
        <ion-refresher-content />
      </ion-refresher>

      <ion-list lines="none">
        <ion-item
          v-for="item in data"
          :key="item.id"
          class="py-3"
          @click="handleItemClick(item)"
        >
          <div slot="start" class="bg-(--bg-icon-color) p-3 rounded-full icon">
            <Icon :icon="getConfigByType(item.notification.type).icon" class="text-xl text-[#3b7901]" />
          </div>
          <div class="pl-3 w-full">
            <div class="flex items-center justify-between mb-1">
              <div class="flex-center gap-2">
                <div class="text-md font-semibold">
                  {{ item.notification.title }}
                </div>
                <div v-show="item.status === 'unread'" class="h-2 w-2 bg-red-500 rounded-full" />
              </div>
              <ion-note slot="end" class="text-xs">
                {{ useDateFormat(item.createdAt, 'MM/DD HH:mm') }}
              </ion-note>
            </div>
            <div class="text-xs overflow-hidden text-ellipsis">
              {{ item.notification.content }}
            </div>
          </div>
        </ion-item>
      </ion-list>
      <ion-infinite-scroll threshold="100px" @ion-infinite="handleInfinite">
        <ion-infinite-scroll-content
          loading-spinner="bubbles"
          :loading-text="t('notify.loading')"
        />
      </ion-infinite-scroll>
    </IonContent>
  </IonPage>
</template>

<style lang="css" scoped>
.icon {
  --bg-icon-color: #d5e8b4;
}

.ion-palette-dark .icon {
  --bg-icon-color: #262d1b;
}
</style>
