<template>
  <USlideover v-model:open="isOpen" :title="$t('notifications.title')">
    <template #body>
      <!-- Action buttons at the top -->
      <div v-if="notifications.length > 0" class="flex gap-2 mb-4 -mt-2">
        <UButton
          :label="$t('notifications.markAllRead')"
          icon="i-lucide-check-check"
          color="neutral"
          variant="outline"
          size="sm"
          :disabled="!hasUnreadNotifications"
          @click="onMarkAllAsRead"
        />
        <UButton
          :label="$t('notifications.deleteAll')"
          icon="i-lucide-trash-2"
          color="error"
          variant="outline"
          size="sm"
          @click="onDeleteAll"
        />
      </div>

      <div v-if="notifications.length === 0" class="text-center py-8 text-muted">
        <UIcon name="i-heroicons-bell-slash" class="h-8 w-8 mx-auto mb-2" />
        <p>{{ $t('notifications.empty') }}</p>
      </div>

      <div
        v-for="notification in notifications"
        :key="notification.id"
        class="px-3 py-2.5 rounded-md hover:bg-elevated/50 flex items-center gap-3 relative -mx-3 first:-mt-3 last:-mb-3 group"
      >
        <NuxtLink
          :to="notification.clickTarget"
          class="flex items-center gap-3 flex-1"
          @click="onNotificationClick(notification)"
        >
          <UChip
            :color="notification.type === 'ERROR' ? 'error' : notification.type === 'WARNING' ? 'warning' : 'primary'"
            :show="!notification.isRead"
            inset
          >
            <UIcon
              :name="
                notification.type === 'ERROR'
                  ? 'i-heroicons-x-circle'
                  : notification.type === 'WARNING'
                    ? 'i-heroicons-exclamation-triangle'
                    : 'i-heroicons-information-circle'
              "
              class="h-6 w-6"
            />
          </UChip>

          <div class="text-sm flex-1">
            <p class="flex items-center justify-between">
              <span class="text-highlighted font-medium">{{ notification.title }}</span>

              <time
                :datetime="notification.createdAt.toISOString()"
                class="text-muted text-xs"
                v-text="formatTimeAgo(notification.createdAt)"
              />
            </p>

            <p class="text-dimmed">
              {{ notification.message }}
            </p>

            <div class="flex items-center gap-2 mt-1">
              <UBadge
                :color="notification.type === 'ERROR' ? 'error' : notification.type === 'WARNING' ? 'warning' : 'info'"
                variant="subtle"
                size="xs"
              >
                {{ notification.type }}
              </UBadge>
            </div>
          </div>
        </NuxtLink>

        <!-- Delete button for individual notification -->
        <UButton
          icon="i-lucide-x"
          color="neutral"
          variant="ghost"
          size="xs"
          square
          class="opacity-0 group-hover:opacity-100 transition-opacity shrink-0"
          :aria-label="$t('notifications.delete')"
          @click.stop.prevent="onDeleteNotification(notification.id)"
        />
      </div>
    </template>
  </USlideover>
</template>

<script setup lang="ts">
import { formatTimeAgo } from '@vueuse/core'
import type { NotificationDto } from '~~/.api-client'
import { useNotificationStore } from '~~/stores/useNotificationStore'

const { t: $t } = useI18n()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

const props = defineProps<{
  modelValue: boolean
}>()

const isOpen = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const notificationStore = useNotificationStore()
const { notifications } = storeToRefs(notificationStore)

const hasUnreadNotifications = computed(() => notifications.value.some((n) => !n.isRead))

watch(isOpen, async (newValue) => {
  if (newValue) {
    await notificationStore.fetchNotifications()
  }
})

function onNotificationClick(notification: NotificationDto) {
  notificationStore.handleNotificationClick(notification)
  emit('update:modelValue', false)
}

async function onMarkAllAsRead() {
  await notificationStore.markAllAsRead()
}

async function onDeleteAll() {
  await notificationStore.deleteAllNotifications()
}

async function onDeleteNotification(notificationId: string) {
  await notificationStore.deleteSingleNotification(notificationId)
}
</script>
