<template>
  <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="notifications.length === 0" class="flex flex-center q-pa-xl text-grey-6">
      {{ $t('notification.empty') }}
    </div>

    <div v-else>
      <div class="row q-px-md q-col-gutter-md">
        <div
          v-for="item in notifications"
          :key="item.id"
          class="col-xl-4 col-lg-4 col-md-4 col-sm-6 col-12"
        >
          <NotificationCard :notification="item" />
        </div>
      </div>

      <div class="flex flex-center q-mt-lg">
        <q-pagination
          v-model="page"
          :max="totalPages"
          :max-pages="6"
          boundary-numbers
          color="violet-normal"
          active-color="violet-normal"
          direction-links
          @update:model-value="fetchData"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { getNotificationsPaginated } from "src/api/notification";
import NotificationCard from "./NotificationCard.vue";

const PER_PAGE = 12;

const loading = ref(true);
const notifications = ref([]);
const page = ref(1);
const total = ref(0);

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

const fetchData = async () => {
  loading.value = true;
  try {
    const result = await getNotificationsPaginated({ page: page.value, perPage: PER_PAGE });
    notifications.value = result.data;
    total.value = result.total;
  } finally {
    loading.value = false;
  }
};

const refresh = async () => {
  page.value = 1;
  await fetchData();
};

defineExpose({ refresh });

onMounted(fetchData);
</script>
