<template>
  <div class="notification-tab">
    <div v-if="loading" class="loading-container">
      <n-spin size="medium" />
    </div>
    <div v-else-if="!settings?.enabled" class="empty-state">
      <span class="text-muted">{{ t('Notifications Disabled') }}</span>
    </div>
    <div v-else>
      <div v-if="notifications.length" class="notifications-container">
        <div
          v-for="notification in notifications"
          :key="notification.name"
          class="notification-item"
          :class="{ unread: !notification.read }"
          @click="handleNotificationClick(notification)"
        >
          <div class="notification-body">
            <div class="notification-indicator" />
            <div class="notification-avatar">
              <n-avatar
                :size="36"
                round
              >
                {{ getInitial(notification.from_user) }}
              </n-avatar>
            </div>
            <div class="message">
              <div v-html="getNotificationMessage(notification.subject)" />
              <div class="notification-timestamp text-muted">
                {{ formatTimestamp(notification.creation) }}
              </div>
            </div>
          </div>
          <div
            v-if="!notification.read"
            class="mark-as-read-btn"
            :title="t('Mark as Read')"
            @click.stop="markAsRead(notification.name)"
          >
            <n-icon size="16">
              <Icon icon="tabler:check" />
            </n-icon>
          </div>
        </div>
        <div class="list-footer" @click="goToNotificationList">
          {{ t('See all Activity') }}
        </div>
      </div>
      <div v-else class="empty-state">
        <div class="empty-state-content">
          <n-icon size="64" color="#d1d8dd">
            <Icon icon="tabler:bell-off" />
          </n-icon>
          <div class="subtitle">
            {{ t("No notifications yet.") }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { NSpin, NAvatar, NIcon } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { 
  getNotificationLogs, 
  markNotificationAsRead,
  type NotificationLog 
} from '../api/notifications'
import { t } from '../i18n'
import { useAuthStore } from '../stores/auth'
import { pageTypeToSlug } from '../utils/slug'

const props = defineProps<{
  settings?: any
}>()

const emit = defineEmits<{
  (e: 'close'): void
  (e: 'update-unseen', hasUnseen: boolean): void
}>()

const router = useRouter()
const authStore = useAuthStore()
const notifications = ref<NotificationLog[]>([])
const loading = ref(true)

onMounted(async () => {
  await loadNotifications()
})

const loadNotifications = async () => {
  loading.value = true
  const result = await getNotificationLogs(20)
  if (result.success && result.data) {
    notifications.value = result.data.notification_logs || []
    // Check if there are unread notifications
    const hasUnread = notifications.value.some(n => !n.read)
    emit('update-unseen', hasUnread)
  }
  loading.value = false
}

const markAsRead = async (docname: string) => {
  const result = await markNotificationAsRead(docname)
  if (result.success) {
    const notification = notifications.value.find(n => n.name === docname)
    if (notification) {
      notification.read = 1
    }
    // Check if there are still unread notifications
    const hasUnread = notifications.value.some(n => !n.read)
    emit('update-unseen', hasUnread)
  }
}

const handleNotificationClick = async (notification: NotificationLog) => {
  if (!notification.read) {
    await markAsRead(notification.name)
  }
  
  // Navigate to the link
  const link = getNotificationLink(notification)
  if (link) {
    if (link.startsWith('http')) {
      window.open(link, '_blank')
    } else {
      router.push(link)
    }
  }
  
  emit('close')
}

const getNotificationLink = (notification: NotificationLog): string => {
  if (notification.link) {
    return notification.link
  }
  const pagetype = notification.document_type || 'Notification Log'
  const docname = notification.document_name || notification.name
  // Convert pagetype to slug format (kebab-case) to match global routing convention
  const pagetypeSlug = pageTypeToSlug(pagetype)
  // Encode docname to handle special characters
  const encodedDocname = encodeURIComponent(docname)
  return `/app/${pagetypeSlug}/${encodedDocname}`
}

const getNotificationMessage = (subject: string): string => {
  // Extract title from subject and truncate if needed
  const titleMatch = subject.match(/<b class="subject-title">(.*?)<\/b>/)
  if (titleMatch) {
    const title = titleMatch[1]
    const truncated = title.length > 100 ? title.substring(0, 100) + '...' : title
    return subject.replace(titleMatch[1], truncated)
  }
  return subject
}

const formatTimestamp = (timestamp: string): string => {
  if (!timestamp) return ''
  
  const date = new Date(timestamp.replace(/-/g, '/').replace(/[TZ]/g, ' ').replace(/\.[0-9]*/, ''))
  const now = new Date()
  const diff = Math.floor((now.getTime() - date.getTime()) / 1000)
  const dayDiff = Math.floor(diff / 86400)
  
  if (isNaN(dayDiff) || dayDiff < 0) return ''
  
  // Today
  if (dayDiff === 0) {
    if (diff < 60) {
      return t('just now')
    } else if (diff < 120) {
      return t('1 minute ago')
    } else if (diff < 3600) {
      return t('{0} minutes ago', { 0: Math.floor(diff / 60).toString() })
    } else if (diff < 7200) {
      return t('1 hour ago')
    } else if (diff < 86400) {
      return t('{0} hours ago', { 0: Math.floor(diff / 3600).toString() })
    }
  }
  
  // Past days
  if (dayDiff === 1) {
    return t('yesterday')
  } else if (dayDiff < 7) {
    return t('{0} days ago', { 0: dayDiff.toString() })
  } else if (dayDiff < 14) {
    return t('1 week ago')
  } else if (dayDiff < 31) {
    return t('{0} weeks ago', { 0: Math.floor(dayDiff / 7).toString() })
  } else if (dayDiff < 62) {
    return t('1 month ago')
  } else if (dayDiff < 365) {
    return t('{0} months ago', { 0: Math.floor(dayDiff / 30).toString() })
  } else if (dayDiff < 730) {
    return t('1 year ago')
  } else {
    return t('{0} years ago', { 0: Math.floor(dayDiff / 365).toString() })
  }
  
  return ''
}

const getInitial = (user: string): string => {
  if (!user) return '?'
  return user.charAt(0).toUpperCase()
}

const goToNotificationList = () => {
  const notificationLogSlug = pageTypeToSlug('Notification Log')
  router.push(`/app/${notificationLogSlug}`)
  emit('close')
}

defineExpose({
  loadNotifications
})
</script>

<style scoped>
.notification-tab {
  width: 100%;
  max-height: 450px;
  overflow-y: auto;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.empty-state {
  min-height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.empty-state-content {
  text-align: center;
}

.empty-state .title {
  margin-top: 16px;
  font-size: 16px;
  font-weight: 600;
}

.empty-state .subtitle {
  margin-top: 8px;
  font-size: 14px;
  color: var(--n-text-color-disabled);
}

.notifications-container {
  padding: 4px 0;
}

.notification-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 10px 10px 10px 0;
  margin: 10px 10px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.notification-item:hover {
  background-color: var(--n-color-hover);
}

.notification-body {
  display: flex;
  gap: 10px;
  flex: 1;
  min-width: 0;
}

.notification-indicator {
  width: 6px;
  height: 6px;
  min-width: 6px;
  margin-top: 16px;
  margin-left: 2px;
  border-radius: 50%;
  background: transparent;
}

.notification-item.unread .notification-indicator {
  background: var(--n-color-target);
}

.notification-avatar {
  flex-shrink: 0;
}

.message {
  flex: 1;
  min-width: 0;
  max-width: 260px;
}

.message :deep(b) {
  font-weight: 500;
}

.notification-timestamp {
  font-size: 12px;
  margin-top: 4px;
}

.text-muted {
  color: var(--n-text-color-disabled);
}

.mark-as-read-btn {
  flex-shrink: 0;
  align-self: center;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.2s;
}

.notification-item:hover .mark-as-read-btn {
  opacity: 1;
}

.mark-as-read-btn:hover {
  background-color: var(--n-color-hover);
}

.list-footer {
  text-align: center;
  padding: 10px;
  color: var(--n-text-color-disabled);
  cursor: pointer;
  transition: color 0.2s;
}

.list-footer:hover {
  color: var(--n-text-color);
}
</style>
