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

const { t } = useI18n()
const localePath = useLocalePath()
const { showStatus } = useStatus()
const log = useLogger('Notifications')

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

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

// Track which notification is being marked as read
const markingAsRead = ref<number | null>(null)
const markingAllAsRead = ref(false)

// Mark notification as read
const markAsRead = async (notificationId: number) => {
  try {
    markingAsRead.value = notificationId

    const apiCall = useApiCall()
    await apiCall(`/api/user/notifications/${notificationId}/mark-read`, {
      method: 'PATCH'
    })

    // Update the local notification data
    const notifs = notifications.value
    if (Array.isArray(notifs)) {
      const notification = notifs.find((n: Notification) => n.id === notificationId)
      if (notification) {
        notification.unread = false
        // Update shared unread count
        decrementUnreadCount()
      }
    }
  } catch (err) {
    log.error('Failed to mark notification as read:', err)
    showStatus(
      t('account.markAsReadFailed'),
      t('account.markAsReadFailedDescription'),
      'error'
    )
  } finally {
    markingAsRead.value = null
  }
}

// Mark all as read
const markAllAsRead = async () => {
  try {
    markingAllAsRead.value = true

    const apiCall = useApiCall()
    await apiCall('/api/user/notifications/mark-all-read', {
      method: 'PATCH'
    })

    // Update all local notifications
    const notifs = notifications.value
    if (Array.isArray(notifs)) {
      notifs.forEach((notification: Notification) => {
        notification.unread = false
      })
    }

    // Reset shared unread count
    resetUnreadCount()

    showStatus(
      t('account.allMarkedAsRead'),
      t('account.allMarkedAsReadDescription'),
      'success'
    )
  } catch (err) {
    log.error('Failed to mark all notifications as read:', err)
    showStatus(
      t('account.markAllAsReadFailed'),
      t('account.markAllAsReadFailedDescription'),
      'error'
    )
  } finally {
    markingAllAsRead.value = false
  }
}

// Computed values
const unreadCount = computed(() => {
  const notifs = notifications.value
  return Array.isArray(notifs) ? notifs.filter((n: Notification) => n.unread).length : 0
})
const hasNotifications = computed(() => {
  const notifs = notifications.value
  return Array.isArray(notifs) && notifs.length > 0
})
const notificationsList = computed(() => {
  const notifs = notifications.value
  return Array.isArray(notifs) ? notifs : []
})
</script>

<template>
  <NuxtLayout
    :page-title="t('account.notifications')"
    :parent="{
      label: t('account.title'),
      to: localePath('/dashboard/account')
    }"
    name="dashboard"
    type="account"
  >
    <UPageBody>
      <PageRefresh :on-refresh="refresh" />
      <PageMainCard
        :title="t('account.notifications')"
        :description="t('account.notificationsDescription')"
        :icon="useSolarIcon('bell')"
        :loading="pending"
        :on-refresh="refresh"
      >
        <template #header-actions>
          <UButton
            v-if="hasNotifications && unreadCount > 0"
            color="neutral"
            variant="outline"
            size="sm"
            :loading="markingAllAsRead"
            :disabled="markingAllAsRead"
            @click="() => markAllAsRead()"
          >
            {{ t('account.markAllAsRead') }}
          </UButton>
        </template>

        <!-- Loading state -->
        <div
          v-if="pending"
          class="flex justify-center py-12"
        >
          <UIcon
            name="lucide:loader"
            class="animate-spin h-8 w-8 text-muted"
          />
        </div>

        <!-- Error state -->
        <div
          v-else-if="error"
          class="text-red-500 py-8 text-center"
        >
          <UIcon
            :name="useSolarIcon('danger-triangle')"
            class="h-12 w-12 mx-auto mb-3"
          />
          <p>{{ t('account.notificationsError') }}</p>
          <UButton
            color="neutral"
            variant="outline"
            class="mt-4"
            @click="() => refresh()"
          >
            {{ t('common.retry') }}
          </UButton>
        </div>

        <!-- Empty state -->
        <div
          v-else-if="!hasNotifications"
          class="text-muted py-12 text-center"
        >
          <UIcon
            :name="useSolarIcon('bell')"
            class="h-16 w-16 mx-auto mb-4 opacity-50"
          />
          <p class="text-lg font-medium mb-2">
            {{ t('account.noNotifications') }}
          </p>
          <p class="text-sm">
            {{ t('account.noNotificationsDescription') }}
          </p>
        </div>

        <!-- Notifications list -->
        <div
          v-else
          class="divide-y divide-default"
        >
          <NuxtLink
            v-for="notification in notificationsList"
            :key="notification.id"
            :to="notification.url"
            class="block px-4 py-4 hover:bg-elevated/50 transition-colors"
            :class="{ 'bg-elevated/30': notification.unread }"
            @click="() => notification.unread && markAsRead(notification.id)"
          >
            <div class="flex items-start gap-4">
              <!-- Avatar with unread indicator -->
              <div class="relative shrink-0">
                <UChip
                  color="error"
                  :show="notification.unread"
                  inset
                >
                  <UAvatar
                    v-bind="notification.sender.avatar"
                    :alt="notification.sender.name"
                    size="lg"
                  />
                </UChip>
              </div>

              <!-- Notification content -->
              <div class="flex-1 min-w-0">
                <div class="flex items-start justify-between gap-2 mb-1">
                  <p class="font-medium text-highlighted">
                    {{ notification.sender.name }}
                  </p>
                  <time
                    :datetime="notification.date"
                    class="text-xs text-muted shrink-0"
                    v-text="formatTimeAgo(new Date(notification.date))"
                  />
                </div>

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

                <!-- Email if available -->
                <p
                  v-if="notification.sender.email"
                  class="text-xs text-muted mt-1"
                >
                  {{ notification.sender.email }}
                </p>
              </div>

              <!-- Arrow icon -->
              <div class="shrink-0 self-center">
                <UIcon
                  :name="useSolarIcon('alt-arrow-right')"
                  class="h-5 w-5 text-muted"
                />
              </div>
            </div>
          </NuxtLink>
        </div>
      </PageMainCard>
    </UPageBody>
  </NuxtLayout>
</template>
