<template>
  <q-dialog ref="dialogRef" persistent @hide="onDialogHide">
    <q-card class="unread-dialog-card">

      <q-card-section class="q-pb-sm">
        <div class="text-h6 text-violet-normal">{{ $t('notification.pending_read_title') }}</div>
        <div class="text-caption text-grey-6 q-mt-xs">{{ $t('notification.pending_read_subtitle') }}</div>
      </q-card-section>

      <q-separator />

      <q-card-section class="unread-dialog-card__scroll q-pa-sm">
        <div v-if="loading" class="flex flex-center q-pa-xl">
          <q-spinner color="violet-normal" size="48px" />
        </div>

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

      <q-separator />

      <q-card-actions align="right" class="q-pa-md">
        <div class="text-caption text-grey-6 q-mr-auto">
          {{ localUnreadCount > 0 ? $t('notification.pending_read_hint') : '' }}
        </div>
        <q-btn
          v-if="localUnreadCount === 0"
          unelevated
          color="violet-normal"
          :label="$t('notification.pending_read_close')"
          @click="onDialogOK()"
        />
      </q-card-actions>

    </q-card>
  </q-dialog>
</template>

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

defineEmits([...useDialogPluginComponent.emits]);

const { dialogRef, onDialogHide, onDialogOK } = useDialogPluginComponent();
const $q = useQuasar();

const loading = ref(false);
const notifications = ref([]);

const localUnreadCount = computed(() => notifications.value.filter((n) => !n.read).length);

const openDetail = (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;
    }
  });
};

const fetchUnread = async () => {
  loading.value = true;
  try {
    notifications.value = await getMyUnreadNotificationsAssociado();
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
};

fetchUnread();
</script>

<style scoped lang="scss">
.unread-dialog-card {
  width: 90vw;
  max-width: 900px;
  min-width: 300px;

  &__scroll {
    max-height: 60vh;
    overflow-y: auto;
  }
}
</style>
