<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useQuasar } from "quasar";
import { useLight, q, m, navigateTo } from "#imports";
const $q = useQuasar();
const light = useLight();
const notifications = ref([]);
const unreadCount = ref(0);
const loading = ref(false);
const fetchUnreadCount = async () => {
  try {
    const data = await q({
      my: {
        unreadNotificationCount: true
      }
    });
    unreadCount.value = data.my.unreadNotificationCount || 0;
  } catch {
  }
};
const fetchNotifications = async () => {
  loading.value = true;
  try {
    const data = await q({
      app: {
        listNotification: {
          data: {
            __args: {
              limit: 10,
              offset: 0
            },
            notification_id: true,
            type: true,
            title: true,
            message: true,
            link: true,
            is_read: true,
            created_time: true
          },
          meta: {
            total: true,
            key: true,
            name: true
          }
        }
      }
    });
    notifications.value = data.app.listNotification.data || [];
  } catch (e) {
    $q.notify({ message: e.message, color: "negative" });
  } finally {
    loading.value = false;
  }
};
const markRead = async (notification) => {
  if (notification.is_read) return;
  try {
    await m("markNotificationRead", { id: notification.notification_id });
    notification.is_read = 1;
    unreadCount.value = Math.max(0, unreadCount.value - 1);
  } catch (e) {
    $q.notify({ message: e.message, color: "negative" });
  }
};
const markAllRead = async () => {
  try {
    await m("markAllNotificationsRead");
    notifications.value.forEach((n) => n.is_read = 1);
    unreadCount.value = 0;
  } catch (e) {
    $q.notify({ message: e.message, color: "negative" });
  }
};
const goToInbox = () => {
  navigateTo("/Notification");
};
const onClickNotification = (notification) => {
  markRead(notification);
  if (notification.link) {
    navigateTo(notification.link);
  }
};
const iconForType = (type) => {
  switch (type) {
    case "success":
      return "sym_o_check_circle";
    case "warning":
      return "sym_o_warning";
    case "error":
      return "sym_o_error";
    default:
      return "sym_o_info";
  }
};
const colorForType = (type) => {
  switch (type) {
    case "success":
      return "positive";
    case "warning":
      return "warning";
    case "error":
      return "negative";
    default:
      return "info";
  }
};
let pollInterval;
onMounted(() => {
  fetchUnreadCount();
  pollInterval = setInterval(fetchUnreadCount, 6e4);
});
onUnmounted(() => {
  if (pollInterval) clearInterval(pollInterval);
});
const openDropdown = () => {
};
const unreadNotifications = computed(() => notifications.value.filter((n) => !n.is_read));
const readNotifications = computed(() => notifications.value.filter((n) => n.is_read));
</script>

<template>
    <q-btn dense flat round icon="sym_o_notifications" class="q-mr-xs">
        <q-badge v-if="unreadCount > 0" color="negative" floating rounded>{{ unreadCount > 99 ? '99+' : unreadCount }}</q-badge>
        <q-menu :offset="[0, 8]" max-width="360px" max-height="480px" auto-close @show="fetchNotifications">
            <q-card flat bordered>
                <q-card-section class="row items-center justify-between q-py-sm">
                    <div class="text-subtitle2">{{ $t('Notifications') }}</div>
                    <q-btn v-if="unreadCount > 0" flat dense size="sm" color="primary" @click="markAllRead">
                        {{ $t('Mark all read') }}
                    </q-btn>
                </q-card-section>
                <q-separator />

                <q-card-section v-if="loading" class="text-center q-py-md">
                    <q-spinner color="primary" size="2em" />
                </q-card-section>

                <q-list v-else-if="notifications.length" padding dense separator>
                    <template v-if="unreadNotifications.length">
                        <q-item-label header class="text-caption text-uppercase text-grey">{{ $t('Unread') }}</q-item-label>
                        <q-item v-for="n in unreadNotifications" :key="n.notification_id" clickable v-ripple
                            class="bg-blue-1" @click="onClickNotification(n)">
                            <q-item-section avatar top>
                                <q-icon :name="iconForType(n.type)" :color="colorForType(n.type)" size="24px" />
                            </q-item-section>
                            <q-item-section>
                                <q-item-label class="text-weight-bold">{{ n.title }}</q-item-label>
                                <q-item-label caption lines="2">{{ n.message }}</q-item-label>
                                <q-item-label caption class="text-grey">{{ n.created_time }}</q-item-label>
                            </q-item-section>
                            <q-item-section side>
                                <q-btn flat round dense icon="sym_o_done" size="sm" color="primary"
                                    @click.stop="markRead(n)">
                                    <q-tooltip>{{ $t('Mark as read') }}</q-tooltip>
                                </q-btn>
                            </q-item-section>
                        </q-item>
                    </template>

                    <template v-if="readNotifications.length">
                        <q-item-label header class="text-caption text-uppercase text-grey">{{ $t('Earlier') }}</q-item-label>
                        <q-item v-for="n in readNotifications" :key="n.notification_id" clickable v-ripple
                            @click="onClickNotification(n)">
                            <q-item-section avatar top>
                                <q-icon :name="iconForType(n.type)" color="grey" size="24px" />
                            </q-item-section>
                            <q-item-section>
                                <q-item-label>{{ n.title }}</q-item-label>
                                <q-item-label caption lines="2">{{ n.message }}</q-item-label>
                                <q-item-label caption class="text-grey">{{ n.created_time }}</q-item-label>
                            </q-item-section>
                        </q-item>
                    </template>
                </q-list>

                <q-card-section v-else class="text-center text-grey q-py-md">
                    {{ $t('No notifications') }}
                </q-card-section>

                <q-separator />
                <q-card-actions align="center">
                    <q-btn flat color="primary" size="sm" @click="goToInbox">{{ $t('View all notifications') }}</q-btn>
                </q-card-actions>
            </q-card>
        </q-menu>
    </q-btn>
</template>
