<script setup lang="ts">
import { formatTimeAgo } from '@vueuse/core'
import type { Notification } from '../types'

const { t } = useI18n()
const localePath = useLocalePath()
const { isOpen } = useNotificationsSlideover()
const log = useLogger('Notifications')

// Use notifications composable for shared state
const { unreadCount, fetchUnreadCount, decrementUnreadCount } = useNotifications()

const { data: notifications, refresh } = await useApiFetch<Notification[]>('/api/user/notifications')

// Show only the most recent 5 notifications in the slideover
const recentNotifications = computed(() => {
  const notifs = notifications.value
  return Array.isArray(notifs) ? notifs.slice(0, 5) : []
})
const hasMoreNotifications = computed(() => {
  const notifs = notifications.value
  return Array.isArray(notifs) && notifs.length > 5
})

// Computed title with unread count
const slideoverTitle = computed(() => {
  const baseTitle = t('account.notifications')
  return unreadCount.value > 0 ? `${baseTitle} (${unreadCount.value})` : baseTitle
})

// Mark notification as read when clicked
const handleNotificationClick = async (notification: Notification) => {
  // Only mark as read if it's currently unread
  if (notification.unread) {
    try {
      // Mark as read in the backend
      const apiCall = useApiCall()
      await apiCall(`/api/user/notifications/${notification.id}/mark-read`, {
        method: 'PATCH'
      })

      // Update local state
      notification.unread = false

      // Update shared unread count
      decrementUnreadCount()
    } catch (error) {
      log.error('Failed to mark notification as read:', error)
    }
  }

  // Close the slideover
  isOpen.value = false
}

watch(isOpen, (newVal) => {
  if (newVal) {
    // Refresh both the notifications list and the unread count
    refresh()
    fetchUnreadCount()
  }
})
</script>

<template>
  <USlideover
    v-model:open="isOpen"
    :title="slideoverTitle"
  >
    <template #body>
      <PageRefresh :on-refresh="refresh" />
      <div
        v-if="!recentNotifications || recentNotifications.length === 0"
        class="text-center py-8 text-muted"
      >
        <UIcon
          :name="useSolarIcon('bell')"
          class="h-12 w-12 mx-auto mb-3 opacity-50"
        />
        <p class="text-sm">
          {{ t('account.noNotifications') }}
        </p>
      </div>

      <div
        v-else
        class="space-y-1"
      >
        <NuxtLink
          v-for="notification in recentNotifications"
          :key="notification.id"
          :to="notification.url"
          class="px-3 py-2.5 rounded-md hover:bg-elevated/50 flex items-center gap-3 relative -mx-3 first:-mt-3"
          @click="() => handleNotificationClick(notification)"
        >
          <UChip
            color="error"
            :show="notification.unread"
            inset
          >
            <UAvatar
              v-bind="notification.sender.avatar"
              :alt="notification.sender.name"
              size="md"
            />
          </UChip>

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

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

            <p class="text-dimmed">
              {{ notification.body }}
            </p>
          </div>
        </NuxtLink>

        <!-- See all link -->
        <div class="pt-3 -mx-3 -mb-3 border-t border-default">
          <NuxtLink
            :to="localePath('/dashboard/account/notifications')"
            class="px-3 py-2.5 rounded-md hover:bg-elevated/50 flex items-center justify-center gap-2 text-sm font-medium text-primary"
            @click="isOpen = false"
          >
            <span>{{ t('account.seeAllNotifications') }}</span>
            <UIcon
              v-if="hasMoreNotifications"
              :name="useSolarIcon('alt-arrow-right')"
              class="h-4 w-4"
            />
          </NuxtLink>
        </div>
      </div>
    </template>
  </USlideover>
</template>
