<script setup lang="ts">
import type { NavigationMenuItem } from '@nuxt/ui'
import type { NavigationItem } from '../../types/i18nLists'
import type { ExtendedUser } from '../../types/database'
import { useI18nMenus } from '../composables/useI18nMenus'

const { t, tm, rt } = useI18n()
const localePath = useLocalePath()
const { user } = useAuth()
const extendedUser = computed(() => user.value as unknown as ExtendedUser | null)
const userIsSuperAdmin = computed(() => isSuperAdmin(user.value))
const { isOpen: isNotificationsSlideoverOpen } = useNotificationsSlideover()
const feedbackModal = ref(false)
const { getConfigBoolean } = useSiteConfig()
const isSidebarCollapsible = ref(false)
const isCollapsed = useState<boolean>('dashboard:sidebar:collapse', () => false)

// Fetch sidebar config asynchronously without blocking
getConfigBoolean('dashboard.sidebar.collapsible', false).then((value) => {
  isSidebarCollapsible.value = value
})
const pageTitle = defineModel<string>('page-title', { required: true })
const parent = defineModel<NavigationItem>('parent', { required: false })
const type = defineModel<string>('type', { required: false, default: 'dashboard' })
const bodyClass = defineModel<string>('body-class', { required: false, default: '' })

// Use notifications composable for shared state
const { unreadCount, fetchUnreadCount, startPolling } = useNotifications()
const unreadCountValue = computed(() => unreadCount.value)

// Fetch initial unread count and start polling
onMounted(() => {
  fetchUnreadCount()
  startPolling() // Default 30 second interval, pauses when tab hidden
})

// eslint-disable-next-line @typescript-eslint/no-explicit-any
useRuntimeHook('dashboard:sidebar:collapse' as any, (value: boolean) => {
  isCollapsed.value = value
})

const sidebarItems = computed(() => {
  return useI18nMenus<NavigationMenuItem>('dashboard.menuItems', tm, rt)
})

const sidebarCollapsed = computed(() => {
  return isSidebarCollapsible.value && isCollapsed.value
})

const adminSidebarItems = computed(() => {
  return isSuperAdmin(user.value)
    ? useI18nMenus<NavigationMenuItem>('admin.menuItems', tm, rt)
    : []
})
const isAdminPage = computed(() => type.value === 'admin')
const groups = computed(() => [{
  id: 'links',
  label: t('nav.goTo'),
  items: sidebarItems.value.flat() as unknown as Array<{ label: string, icon?: string, to: string }>
},
{
  id: 'account',
  label: t('account.title'),
  items: [{
    label: t('account.profile'),
    icon: useSolarIcon('user'),
    to: localePath('/dashboard/account')
  }, {
    label: t('account.settings'),
    icon: useSolarIcon('settings'),
    to: localePath('/dashboard/account/settings')
  }] as unknown as Array<{ label: string, icon?: string, to: string }>
}])

const breadcrumbItems = [
  {
    label: t('dashboard.title'),
    to: localePath('/dashboard')
  },
  ...(parent.value
    ? [{
        label: parent.value.label,
        to: parent.value.to
      }]
    : []),
  {
    label: (pageTitle as unknown as string)
  }
]
</script>

<template>
  <SuperAdminImpersonationBanner
    v-if="extendedUser?._impersonated"
    :user="extendedUser"
  />
  <UDashboardGroup :class="[extendedUser?._impersonated ? 'mt-4' : '']">
    <UDashboardSidebar
      :collapsible="isSidebarCollapsible"
      :collapsed="sidebarCollapsed"
    >
      <template #header="{ collapsed }">
        <div class="w-full">
          <slot name="title">
            <h1 class="focus-visible:outline-primary shrink-0 font-bold text-lg sm:text-xl text-highlighted flex items-end gap-1.5">
              <NuxtLink
                :to="localePath('/')"
                class="cursor-pointer truncate"
              >
                {{ collapsed ? t('website.titleShorter') : t('website.title') }}
              </NuxtLink>
            </h1>
          </slot>
        </div>

        <UDashboardSidebarCollapse
          v-if="isSidebarCollapsible"
          :icon="useSolarIcon('double-alt-arrow-right')"
          :class="collapsed ? 'rotate-0' : 'rotate-180'"
          as="button"
          variant="subtle"
          size="sm"
          :disabled="false"
        />
      </template>

      <template #default="{ collapsed }">
        <UDashboardSearchButton
          :collapsed="collapsed"
          :icon="useSolarIcon('magnifer')"
          class="bg-transparent ring-default mb-3.5"
        />

        <UNavigationMenu
          v-if="!isAdminPage"
          :collapsed="collapsed"
          :items="sidebarItems[0]"
          orientation="vertical"
        />
        <UNavigationMenu
          v-if="userIsSuperAdmin && !isAdminPage"
          :items="[{
            label: 'Super Admin',
            icon: useSolarIcon('settings-minimalistic'),
            to: localePath('/dashboard/admin')
          }]"
          orientation="vertical"
        />

        <UNavigationMenu
          v-if="isAdminPage"
          :items="[{
            label: t('dashboard.backToDashboard'),
            icon: useSolarIcon('alt-arrow-left'),
            to: localePath('/dashboard')
          }]"
          orientation="vertical"
        />
        <UNavigationMenu
          v-if="userIsSuperAdmin && isAdminPage"
          :collapsed="collapsed"
          :items="adminSidebarItems"
          orientation="vertical"
        />

        <UNavigationMenu
          :collapsed="collapsed"
          :items="[
            { label: 'Support', icon: useSolarIcon('question-circle'), onSelect: () => feedbackModal = true },
            ...(sidebarItems.length > 1 ? sidebarItems[1] : [])
          ]"
          orientation="vertical"
          class="mt-auto"
        />
      </template>

      <template #footer="{ collapsed }">
        <UserMenu :collapsed="collapsed" />
      </template>
    </UDashboardSidebar>

    <UDashboardSearch
      :groups="groups"
      :icon="useSolarIcon('magnifer')"
    />

    <UDashboardPanel
      id="home"
      :ui="{
        body: bodyClass
      }"
    >
      <template #header>
        <UDashboardNavbar>
          <template #title>
            {{ pageTitle }}
          </template>
          <template #right>
            <UTooltip
              :text="t('nav.notifications')"
              :shortcuts="['N']"
            >
              <UChip
                :text="String(unreadCountValue)"
                size="3xl"
                inset
                :ui="{
                  root: 'p-2',
                  base: unreadCountValue > 0 ? 'h-4 w-4' : 'hidden'
                }"
              >
                <UButton
                  :icon="useSolarIcon('bell')"
                  color="neutral"
                  variant="outline"
                  @click="isNotificationsSlideoverOpen = true"
                />
              </UChip>
            </UTooltip>

            <LanguageSwitcher />
            <UserMenu collapsed />
          </template>
        </UDashboardNavbar>

        <UDashboardToolbar>
          <template #left>
            <UBreadcrumb
              :items="breadcrumbItems"
              :separator-icon="useSolarIcon('alt-arrow-right')"
            />
          </template>
          <template #right>
            <slot name="actions" />
          </template>
        </UDashboardToolbar>
      </template>

      <template #body>
        <slot />
      </template>
    </UDashboardPanel>
    <NotificationsSlideover />
    <UModal
      v-model:open="feedbackModal"
      title="Need help?"
      description="Have a question or need assistance? We're here to help!"
    >
      <template #body>
        <AppFeedbackForm @close="feedbackModal = false" />
      </template>
    </UModal>
  </UDashboardGroup>
</template>
