<template>
  <div>
    <DefaultHeaderPage />

    <div class="q-pt-sm">

      <div v-if="loading" class="flex flex-center q-pa-xl">
        <q-spinner color="violet-normal" size="50px" />
      </div>

      <div v-else-if="pagedItems.length === 0" class="flex flex-center q-pa-xl text-grey-6">
        {{ $t('notification.empty') }}
      </div>

      <div v-else>
        <div class="notifications-grid q-px-md">
          <NotificationCard
            v-for="item in pagedItems"
            :key="item.id"
            :notification="item.notification"
            :unread="!item.read"
            :date="item.created_at"
            @click="openDetail(item)"
          />
        </div>

        <div v-if="totalPages > 1" class="flex flex-center q-mt-lg">
          <q-pagination
            v-model="currentPage"
            :max="totalPages"
            :max-pages="6"
            boundary-numbers
            color="violet-normal"
            active-color="violet-normal"
            direction-links
          />
        </div>
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useQuasar } from "quasar";
import { getMyNotificationsAssociado } from "src/api/notification";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import NotificationCard from "src/components/NotificationCard.vue";
import NotificationDetailDialog from "src/components/NotificationDetailDialog.vue";

const $q = useQuasar();

const loading = ref(true);
const notifications = ref([]);
const currentPage = ref(1);
const PER_PAGE = 12;

const totalPages = computed(() => Math.max(1, Math.ceil(notifications.value.length / PER_PAGE)));

const pagedItems = computed(() => {
  const start = (currentPage.value - 1) * PER_PAGE;
  return notifications.value.slice(start, start + PER_PAGE);
});

const openDetail = (item) => {
  $q.dialog({
    component: NotificationDetailDialog,
    componentProps: { item },
  }).onOk((markedId) => {
    if (!markedId) return;
    const found = notifications.value.find((n) => n.id === markedId);
    if (found) found.read = true;
  });
};

onMounted(async () => {
  try {
    notifications.value = await getMyNotificationsAssociado();
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
});
</script>

