<template>
  <n-popover
    trigger="click"
    placement="bottom-end"
    :show="showDropdown"
    @update:show="handleDropdownUpdate"
    :show-arrow="false"
    :style="{ padding: 0 }"
    raw
  >
    <template #trigger>
      <n-button
        quaternary
        circle
      >
        <template #icon>
          <n-badge :dot="hasUnseen" :offset="[-2, 2]">
            <Icon icon="tabler:bell" :size="20" />
          </n-badge>
        </template>
      </n-button>
    </template>
    
    <div class="notification-dropdown">
      <div class="notification-header">
        <div class="header-tabs">
          <n-tabs
            v-model:value="activeTab"
            type="line"
            size="small"
            :tabs-padding="0"
          >
            <n-tab-pane name="notifications" :tab="t('Notifications')" />
            <n-tab-pane name="events" :tab="t('Events')" />
            <n-tab-pane name="whats-new" :tab="t(`What's New`)" />
          </n-tabs>
        </div>
        <div class="header-actions">
          <n-button
            text
            size="small"
            @click="handleMarkAllAsRead"
            :title="t('Mark all as read')"
          >
            <template #icon>
              <Icon icon="tabler:checks" />
            </template>
          </n-button>
          <n-button
            text
            size="small"
            @click="goToSettings"
            :title="t('Notification Settings')"
          >
            <template #icon>
              <Icon icon="tabler:settings" />
            </template>
          </n-button>
        </div>
      </div>
      
      <div class="notification-body">
        <NotificationTab
          v-show="activeTab === 'notifications'"
          ref="notificationTabRef"
          :settings="notificationSettings"
          @close="closeDropdown"
          @update-unseen="updateUnseenStatus"
        />
        <EventTab
          v-show="activeTab === 'events'"
          ref="eventTabRef"
          @close="closeDropdown"
        />
        <ChangelogTab
          v-show="activeTab === 'whats-new'"
          ref="changelogTabRef"
          @close="closeDropdown"
        />
      </div>
    </div>
  </n-popover>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { NPopover, NButton, NTabs, NTabPane, NBadge } from 'naive-ui'
import { Icon } from '@iconify/vue'
import NotificationTab from './NotificationTab.vue'
import EventTab from './EventTab.vue'
import ChangelogTab from './ChangelogTab.vue'
import { 
  markAllNotificationsAsRead, 
  setNotificationSeenValue,
  getNotificationSettings 
} from '../api/notifications'
import { useAuthStore } from '../stores/auth'
import { t } from '../i18n'

const router = useRouter()
const authStore = useAuthStore()

const showDropdown = ref(false)
const activeTab = ref('notifications')
const hasUnseen = ref(false)
const notificationSettings = ref<any>(null)

const notificationTabRef = ref<InstanceType<typeof NotificationTab> | null>(null)
const eventTabRef = ref<InstanceType<typeof EventTab> | null>(null)
const changelogTabRef = ref<InstanceType<typeof ChangelogTab> | null>(null)

onMounted(async () => {
  // Get notification settings from API
  if (authStore.user) {
    const result = await getNotificationSettings(authStore.user.name)
    if (result.success && result.data) {
      notificationSettings.value = result.data
      // Check if there are unseen notifications
      hasUnseen.value = result.data.seen === 0
    } else {
      // Default to enabled if fetch fails
      notificationSettings.value = { enabled: 1, seen: 1 }
    }
  }
})

const handleDropdownUpdate = (show: boolean) => {
  showDropdown.value = show
  
  if (show) {
    handleDropdownOpen()
  }
}

const handleDropdownOpen = async () => {
  // Set seen value when dropdown opens
  if (hasUnseen.value && authStore.user) {
    await setNotificationSeenValue(1, authStore.user.name)
    hasUnseen.value = false
  }
  
  // Refresh content of active tab
  if (activeTab.value === 'notifications' && notificationTabRef.value) {
    notificationTabRef.value.loadNotifications()
  } else if (activeTab.value === 'events' && eventTabRef.value) {
    eventTabRef.value.loadEvents()
  } else if (activeTab.value === 'whats-new' && changelogTabRef.value) {
    changelogTabRef.value.loadChangelogFeed()
  }
}

const closeDropdown = () => {
  showDropdown.value = false
}

const updateUnseenStatus = (unseen: boolean) => {
  hasUnseen.value = unseen
}

const handleMarkAllAsRead = async () => {
  const result = await markAllNotificationsAsRead()
  if (result.success) {
    hasUnseen.value = false
    // Refresh notifications tab
    if (notificationTabRef.value) {
      notificationTabRef.value.loadNotifications()
    }
  }
}

const goToSettings = () => {
  if (authStore.user) {
    router.push(`/app/Notification Settings/${authStore.user.name}`)
  }
  closeDropdown()
}
</script>

<style scoped>
.notification-dropdown {
  width: 360px;
  min-height: 480px;
  background: var(--n-color);
  border-radius: 8px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  overflow: hidden;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid var(--n-border-color);
}

.header-tabs {
  flex: 1;
  min-width: 0;
}

.header-tabs :deep(.n-tabs) {
  width: 100%;
}

.header-tabs :deep(.n-tabs-nav) {
  padding: 0;
}

.header-tabs :deep(.n-tabs-tab) {
  padding: 12px 0;
  margin-right: 16px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
  margin-left: 8px;
}

.notification-body {
  position: relative;
  max-height: 450px;
}

/* Custom scrollbar */
.notification-body :deep(*::-webkit-scrollbar) {
  width: 6px;
}

.notification-body :deep(*::-webkit-scrollbar-track) {
  background: transparent;
}

.notification-body :deep(*::-webkit-scrollbar-thumb) {
  background: var(--n-scrollbar-color);
  border-radius: 3px;
}

.notification-body :deep(*::-webkit-scrollbar-thumb:hover) {
  background: var(--n-scrollbar-color-hover);
}
</style>
