<script lang="ts" setup>
import { BookOpen, Boxes, ChevronDown, Code, CreditCard, DollarSign, FileLock, Gauge, GitBranch, Hash, Home, Key, LayoutDashboard, LogOut, Megaphone, Menu, MessageSquare, Monitor, Moon, Plug, ScrollText, Share2, Shield, Sun, User, Users, Variable, Wifi } from 'lucide-vue-next'
import { useColorMode } from '@vueuse/core'
import { computed, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'

import ThemePopover from '@/components/custom-theme/theme-popover.vue'
import LanguageChange from '@/components/language-change.vue'

const { t } = useI18n()
const mode = useColorMode()
const route = useRoute()
const router = useRouter()

const isLoggedIn = ref(false)
const currentUser = ref<any>(null)
const mobileMenuOpen = ref(false)

function checkLoginStatus() {
  isLoggedIn.value = !!localStorage.getItem('token')
}

const siteSettings = ref({
  siteName: window.__SITE_CONFIG__?.siteName || '',
  logoLight: window.__SITE_CONFIG__?.logoLight || '',
  logoDark: window.__SITE_CONFIG__?.logoDark || '',
  favicon: window.__SITE_CONFIG__?.favicon || '',
})

const siteName = computed(() => siteSettings.value.siteName)

const userAvatar = computed(() => {
  const avatar = currentUser.value?.avatar
  if (!avatar)
    return ''
  if (avatar.startsWith('http'))
    return avatar
  return `${import.meta.env.VITE_API_BASE || 'http://localhost:8080'}${avatar}`
})

function getAssetUrl(path: string) {
  if (!path)
    return ''
  if (path.startsWith('http'))
    return path
  return `${import.meta.env.VITE_API_BASE || 'http://localhost:8080'}${path}`
}

const logoSrc = computed(() => {
  if (mode.value === 'dark') {
    if (siteSettings.value.logoDark) {
      return getAssetUrl(siteSettings.value.logoDark)
    }
    return '/logo.svg'
  }
  else {
    if (siteSettings.value.logoLight) {
      return getAssetUrl(siteSettings.value.logoLight)
    }
    return '/logo-black.svg'
  }
})

const adminMenus = computed(() => ({
  main: {
    title: t('nav.mainFeatures'),
    items: [
      { title: t('nav.console'), url: '/admin', icon: Gauge },
      { title: t('nav.applications'), url: '/admin/applications', icon: Boxes },
      { title: t('nav.cardTypes'), url: '/admin/card-types', icon: Hash },
      { title: t('nav.cards'), url: '/admin/cards', icon: Key },
      { title: t('nav.announcements'), url: '/admin/announcements', icon: Megaphone },
      { title: t('nav.versions'), url: '/admin/versions', icon: GitBranch },
      { title: t('nav.users'), url: '/admin/users', icon: Users },
      { title: t('nav.devices'), url: '/admin/devices', icon: Monitor },
      { title: t('nav.sessions'), url: '/admin/sessions', icon: Wifi },
      { title: t('nav.agentApps'), url: '/admin/agent-apps', icon: Share2 },
    ],
  },
  business: {
    title: t('nav.businessManagement'),
    items: [
      { title: t('nav.finance'), url: '/admin/finance', icon: DollarSign },
      { title: t('nav.logs'), url: '/admin/logs', icon: ScrollText },
      { title: t('nav.tickets'), url: '/admin/tickets', icon: MessageSquare },
    ],
  },
  advanced: {
    title: t('nav.advancedFeatures'),
    items: [
      { title: t('nav.cloudConstants'), url: '/admin/cloud-constants', icon: FileLock },
      { title: t('nav.cloudVariables'), url: '/admin/cloud-variables', icon: Variable },
      { title: t('nav.cloudFunction'), url: '/admin/cloud-function', icon: Code },
      { title: t('nav.riskControl'), url: '/admin/risk-control', icon: Shield },
      { title: t('nav.extension'), url: '/admin/extension', icon: Plug },
    ],
  },
}))

const publicMenus = computed(() => [
  { title: t('nav.home'), url: '/', icon: Home },
  { title: t('nav.docs'), url: '/docs', icon: BookOpen },
  { title: t('nav.pricing'), url: '/pricing', icon: CreditCard },
])

function isMenuActive(items: { url: string }[]) {
  return items.some(item => route.path === item.url)
}

function isActive(url: string) {
  return route.path === url
}

function navigateTo(url: string) {
  router.push(url)
  mobileMenuOpen.value = false
}

function updateFavicon() {
  if (siteSettings.value.favicon) {
    const link: HTMLLinkElement = document.querySelector('link[rel*=\'icon\']') || document.createElement('link')
    link.type = 'image/x-icon'
    link.rel = 'shortcut icon'
    link.href = getAssetUrl(siteSettings.value.favicon)
    document.getElementsByTagName('head')[0].appendChild(link)
  }
}

function handleLogout() {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  currentUser.value = null
  isLoggedIn.value = false
  mobileMenuOpen.value = false
  router.push('/')
}

onMounted(() => {
  checkLoginStatus()
  const userStr = localStorage.getItem('user')
  if (userStr) {
    try {
      currentUser.value = JSON.parse(userStr)
    }
    catch (error) {
      console.error('Failed to parse user data:', error)
    }
  }
  if (siteSettings.value.favicon) {
    updateFavicon()
  }
  if (siteSettings.value.siteName) {
    document.title = siteSettings.value.siteName
  }
})

watch(mode, () => {
  updateFavicon()
})

watch(route, () => {
  mobileMenuOpen.value = false
})
</script>

<template>
  <header class="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
    <div class="mx-auto max-w-6xl flex h-14 items-center px-4 sm:px-6 lg:px-8">
      <div class="mr-4 hidden md:flex items-center">
        <router-link to="/" class="mr-4 flex items-center space-x-2">
          <UiAvatar class="h-7 w-7">
            <UiAvatarImage :src="logoSrc" alt="Logo" />
          </UiAvatar>
          <span class="hidden font-bold sm:inline-block">{{ siteName }}</span>
        </router-link>
        <nav class="flex items-center space-x-1 text-sm font-medium">
          <router-link
            to="/"
            class="transition-colors hover:text-foreground/80 px-3 py-2 rounded-lg"
            :class="route.name === 'Home' ? 'text-foreground bg-accent' : 'text-foreground/60'"
          >
            {{ t('nav.home') }}
          </router-link>
          <router-link
            to="/docs"
            class="transition-colors hover:text-foreground/80 px-3 py-2 rounded-lg"
            :class="route.name === 'Docs' ? 'text-foreground bg-accent' : 'text-foreground/60'"
          >
            {{ t('nav.docs') }}
          </router-link>
          <router-link
            to="/pricing"
            class="transition-colors hover:text-foreground/80 px-3 py-2 rounded-lg"
            :class="route.name === 'Pricing' ? 'text-foreground bg-accent' : 'text-foreground/60'"
          >
            {{ t('nav.pricing') }}
          </router-link>

          <template v-if="isLoggedIn && currentUser?.role === 'admin'">
            <div class="w-px h-4 bg-border mx-1" />

            <UiDropdownMenu>
              <UiDropdownMenuTrigger as-child>
                <button
                  class="transition-colors hover:text-foreground/80 px-3 py-2 rounded-lg flex items-center gap-1"
                  :class="isMenuActive(adminMenus.main.items) ? 'text-foreground bg-accent' : 'text-foreground/60'"
                >
                  {{ adminMenus.main.title }}
                  <ChevronDown class="h-4 w-4" />
                </button>
              </UiDropdownMenuTrigger>
              <UiDropdownMenuContent align="start" class="w-40">
                <UiDropdownMenuItem
                  v-for="item in adminMenus.main.items"
                  :key="item.url"
                  :class="route.path === item.url ? 'bg-accent' : ''"
                  @click="router.push(item.url)"
                >
                  <component :is="item.icon" class="mr-2 h-4 w-4" />
                  {{ item.title }}
                </UiDropdownMenuItem>
              </UiDropdownMenuContent>
            </UiDropdownMenu>

            <UiDropdownMenu>
              <UiDropdownMenuTrigger as-child>
                <button
                  class="transition-colors hover:text-foreground/80 px-3 py-2 rounded-lg flex items-center gap-1"
                  :class="isMenuActive(adminMenus.business.items) ? 'text-foreground bg-accent' : 'text-foreground/60'"
                >
                  {{ adminMenus.business.title }}
                  <ChevronDown class="h-4 w-4" />
                </button>
              </UiDropdownMenuTrigger>
              <UiDropdownMenuContent align="start" class="w-40">
                <UiDropdownMenuItem
                  v-for="item in adminMenus.business.items"
                  :key="item.url"
                  :class="route.path === item.url ? 'bg-accent' : ''"
                  @click="router.push(item.url)"
                >
                  <component :is="item.icon" class="mr-2 h-4 w-4" />
                  {{ item.title }}
                </UiDropdownMenuItem>
              </UiDropdownMenuContent>
            </UiDropdownMenu>

            <UiDropdownMenu>
              <UiDropdownMenuTrigger as-child>
                <button
                  class="transition-colors hover:text-foreground/80 px-3 py-2 rounded-lg flex items-center gap-1"
                  :class="isMenuActive(adminMenus.advanced.items) ? 'text-foreground bg-accent' : 'text-foreground/60'"
                >
                  {{ adminMenus.advanced.title }}
                  <ChevronDown class="h-4 w-4" />
                </button>
              </UiDropdownMenuTrigger>
              <UiDropdownMenuContent align="start" class="w-40">
                <UiDropdownMenuItem
                  v-for="item in adminMenus.advanced.items"
                  :key="item.url"
                  :class="route.path === item.url ? 'bg-accent' : ''"
                  @click="router.push(item.url)"
                >
                  <component :is="item.icon" class="mr-2 h-4 w-4" />
                  {{ item.title }}
                </UiDropdownMenuItem>
              </UiDropdownMenuContent>
            </UiDropdownMenu>
          </template>
        </nav>
      </div>

      <button
        class="md:hidden mr-2 flex items-center justify-center size-9 rounded-md hover:bg-accent"
        @click="mobileMenuOpen = true"
      >
        <Menu class="size-5" />
      </button>

      <router-link to="/" class="mr-6 flex items-center space-x-2 md:hidden">
        <UiAvatar class="h-7 w-7">
          <UiAvatarImage :src="logoSrc" alt="Logo" />
        </UiAvatar>
        <span class="font-bold">{{ siteName }}</span>
      </router-link>

      <div class="flex flex-1 items-center justify-end space-x-2">
        <LanguageChange />

        <UiButton
          variant="ghost"
          size="icon"
          class="h-9 w-9"
          @click="mode = mode === 'dark' ? 'light' : 'dark'"
        >
          <Sun
            class="h-5 w-5 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"
          />
          <Moon
            class="absolute h-5 w-5 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"
          />
          <span class="sr-only">切换主题</span>
        </UiButton>

        <ThemePopover />

        <template v-if="isLoggedIn">
          <UiDropdownMenu>
            <UiDropdownMenuTrigger as-child>
              <UiButton variant="ghost" class="relative h-9 w-9 rounded-full">
                <UiAvatar class="h-9 w-9">
                  <UiAvatarImage :src="userAvatar" alt="用户头像" />
                  <UiAvatarFallback>{{ currentUser?.username?.charAt(0).toUpperCase() || 'U' }}</UiAvatarFallback>
                </UiAvatar>
              </UiButton>
            </UiDropdownMenuTrigger>
            <UiDropdownMenuContent align="end" class="w-48">
              <UiDropdownMenuLabel>
                <div class="flex flex-col space-y-1">
                  <p class="text-sm font-medium leading-none">
                    {{ currentUser?.username || '用户' }}
                  </p>
                  <p class="text-xs leading-none text-muted-foreground">
                    {{ currentUser?.email || '' }}
                  </p>
                </div>
              </UiDropdownMenuLabel>
              <UiDropdownMenuSeparator />
              <UiDropdownMenuItem @click="router.push('/profile')">
                <User class="mr-2 h-4 w-4" />
                <span>{{ t('nav.profile') }}</span>
              </UiDropdownMenuItem>
              <UiDropdownMenuItem v-if="currentUser?.role === 'admin'" @click="router.push('/admin')">
                <LayoutDashboard class="mr-2 h-4 w-4" />
                <span>{{ t('nav.adminDashboard') }}</span>
              </UiDropdownMenuItem>
              <UiDropdownMenuItem v-if="currentUser?.role === 'agent'" @click="router.push('/agent')">
                <LayoutDashboard class="mr-2 h-4 w-4" />
                <span>{{ t('nav.agentDashboard') }}</span>
              </UiDropdownMenuItem>
              <UiDropdownMenuSeparator />
              <UiDropdownMenuItem @click="handleLogout">
                <LogOut class="mr-2 h-4 w-4" />
                <span>{{ t('nav.logout') }}</span>
              </UiDropdownMenuItem>
            </UiDropdownMenuContent>
          </UiDropdownMenu>
        </template>
        <template v-else>
          <UiButton variant="ghost" size="sm" as-child>
            <router-link to="/login">
              {{ t('nav.login') }}
            </router-link>
          </UiButton>
          <UiButton size="sm" as-child class="hidden sm:flex">
            <router-link to="/register">
              {{ t('nav.register') }}
            </router-link>
          </UiButton>
        </template>
      </div>
    </div>

    <UiSheet v-model:open="mobileMenuOpen">
      <UiSheetContent side="left" class="w-72 overflow-y-auto">
        <div class="flex flex-col h-full">
          <div class="flex items-center justify-between mb-6">
            <div class="flex items-center space-x-2">
              <UiAvatar class="h-7 w-7">
                <UiAvatarImage :src="logoSrc" alt="Logo" />
              </UiAvatar>
              <span class="font-bold">{{ siteName }}</span>
            </div>
          </div>

          <nav class="flex-1 space-y-6">
            <div class="space-y-1">
              <p class="text-xs font-medium text-muted-foreground px-3 mb-2">
                {{ t('nav.navigation') }}
              </p>
              <button
                v-for="item in publicMenus"
                :key="item.url"
                class="w-full flex items-center gap-3 px-3 py-2 text-sm rounded-lg transition-colors"
                :class="isActive(item.url) ? 'bg-accent text-foreground' : 'text-muted-foreground hover:bg-accent hover:text-foreground'"
                @click="navigateTo(item.url)"
              >
                <component :is="item.icon" class="size-4" />
                {{ item.title }}
              </button>
            </div>

            <template v-if="isLoggedIn && currentUser?.role === 'admin'">
              <div class="space-y-1">
                <p class="text-xs font-medium text-muted-foreground px-3 mb-2">
                  {{ adminMenus.main.title }}
                </p>
                <button
                  v-for="item in adminMenus.main.items"
                  :key="item.url"
                  class="w-full flex items-center gap-3 px-3 py-2 text-sm rounded-lg transition-colors"
                  :class="isActive(item.url) ? 'bg-accent text-foreground' : 'text-muted-foreground hover:bg-accent hover:text-foreground'"
                  @click="navigateTo(item.url)"
                >
                  <component :is="item.icon" class="size-4" />
                  {{ item.title }}
                </button>
              </div>

              <div class="space-y-1">
                <p class="text-xs font-medium text-muted-foreground px-3 mb-2">
                  {{ adminMenus.business.title }}
                </p>
                <button
                  v-for="item in adminMenus.business.items"
                  :key="item.url"
                  class="w-full flex items-center gap-3 px-3 py-2 text-sm rounded-lg transition-colors"
                  :class="isActive(item.url) ? 'bg-accent text-foreground' : 'text-muted-foreground hover:bg-accent hover:text-foreground'"
                  @click="navigateTo(item.url)"
                >
                  <component :is="item.icon" class="size-4" />
                  {{ item.title }}
                </button>
              </div>

              <div class="space-y-1">
                <p class="text-xs font-medium text-muted-foreground px-3 mb-2">
                  {{ adminMenus.advanced.title }}
                </p>
                <button
                  v-for="item in adminMenus.advanced.items"
                  :key="item.url"
                  class="w-full flex items-center gap-3 px-3 py-2 text-sm rounded-lg transition-colors"
                  :class="isActive(item.url) ? 'bg-accent text-foreground' : 'text-muted-foreground hover:bg-accent hover:text-foreground'"
                  @click="navigateTo(item.url)"
                >
                  <component :is="item.icon" class="size-4" />
                    {{ item.title }}
                </button>
              </div>
            </template>
          </nav>

          <div v-if="!isLoggedIn" class="pt-4 border-t mt-4 space-y-2">
            <UiButton variant="outline" class="w-full" as-child @click="mobileMenuOpen = false">
              <router-link to="/login">
                {{ t('nav.login') }}
              </router-link>
            </UiButton>
            <UiButton class="w-full" as-child @click="mobileMenuOpen = false">
              <router-link to="/register">
                {{ t('nav.register') }}
              </router-link>
            </UiButton>
          </div>

          <div v-else class="pt-4 border-t mt-4">
            <div class="flex items-center gap-3 px-3 py-2">
              <UiAvatar class="h-9 w-9">
                <UiAvatarImage :src="userAvatar" alt="用户头像" />
                <UiAvatarFallback>{{ currentUser?.username?.charAt(0).toUpperCase() || 'U' }}</UiAvatarFallback>
              </UiAvatar>
              <div class="flex-1 min-w-0">
                <p class="text-sm font-medium truncate">
                  {{ currentUser?.username || '用户' }}
                </p>
                <p class="text-xs text-muted-foreground truncate">
                  {{ currentUser?.email || '' }}
                </p>
              </div>
            </div>
            <UiButton variant="outline" class="w-full mt-2" @click="handleLogout">
              <LogOut class="mr-2 h-4 w-4" />
              {{ t('nav.logout') }}
            </UiButton>
          </div>
        </div>
      </UiSheetContent>
    </UiSheet>
  </header>
</template>
