<template>
  <div class="notificacoes-page">
    <DefaultHeaderPage class="q-px-md"/>

    <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 q-px-md">
      {{ $t('notification.empty') }}
    </div>

    <div v-else 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="onRead(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>
</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 NotificationDetailDialog from "src/components/NotificationDetailDialog.vue";
import NotificationCard from "src/components/NotificationCard.vue";

const $q = useQuasar();

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

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 onRead = (item) => {
  $q.dialog({ component: NotificationDetailDialog, componentProps: { item } }).onOk((markedId) => {
    if (markedId) {
      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>

<style scoped lang="scss">
@use "src/css/quasar.variables.scss" as vars;

.notificacoes-page {
  background: vars.$violet-light;
  min-height: calc(100dvh - 68px);
  box-sizing: border-box;
  overflow-x: hidden;
  padding-bottom: 16px;
}
</style>
