<script setup lang="ts">
import { Boxes, CreditCard, Gauge, Key, LogOut, User, Users } from 'lucide-vue-next'
import { computed, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'

import NavTeam from '@/components/app-sidebar/nav-team.vue'
import TeamSwitcher from '@/components/app-sidebar/team-switcher.vue'
import LanguageChange from '@/components/language-change.vue'
import ThemePopover from '@/components/custom-theme/theme-popover.vue'
import ToggleTheme from '@/components/toggle-theme.vue'

const router = useRouter()

const user = reactive({
  name: '代理商',
  email: 'agent@example.com',
  avatar: '/avatars/agent.jpg',
  role: 'agent',
})

onMounted(() => {
  const storedUser = localStorage.getItem('user')
  if (storedUser) {
    try {
      const parsedUser = JSON.parse(storedUser)
      user.name = parsedUser.username || user.name
      user.email = parsedUser.email || user.email
      user.avatar = parsedUser.avatar || user.avatar
      user.role = parsedUser.role || user.role
    }
    catch (e) {
      console.error('Failed to parse user from localStorage', e)
    }
  }
})

const teams = [
  {
    name: '代理商后台',
    logo: Users,
    plan: 'Agent',
  },
]

const navMain = [
  {
    title: '主要功能',
    items: [
      {
        title: '控制台',
        url: '/agent',
        icon: Gauge,
      },
      {
        title: '应用管理',
        url: '/agent/apps',
        icon: Boxes,
      },
      {
        title: '卡密管理',
        url: '/agent/cards',
        icon: Key,
      },
      {
        title: '用户管理',
        url: '/agent/users',
        icon: Users,
      },
    ],
  },
  {
    title: '财务',
    items: [
      {
        title: '财务管理',
        url: '/agent/finance',
        icon: CreditCard,
      },
    ],
  },
]

const breadcrumbs = computed(() => {
  const path = router.currentRoute.value.path
  const parts = path.split('/').filter(Boolean)
  const crumbs = [{ title: '控制台', path: '/agent' }]

  const titleMap: Record<string, string> = {
    apps: '应用管理',
    cards: '卡密管理',
    users: '用户管理',
    finance: '财务管理',
    profile: '个人中心',
    create: '创建',
  }

  let currentPath = '/agent'
  for (let i = 1; i < parts.length; i++) {
    const part = parts[i]
    currentPath += `/${part}`

    if (titleMap[part]) {
      crumbs.push({
        title: titleMap[part],
        path: currentPath,
      })
    }
    else if (!isNaN(Number(part))) {
      crumbs.push({
        title: '详情',
        path: currentPath,
      })
    }
  }

  return crumbs
})

function handleLogout() {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  router.push('/login')
}
</script>

<template>
  <UiSidebarProvider>
    <UiSidebar collapsible="icon" class="z-50">
      <UiSidebarHeader>
        <TeamSwitcher :teams="teams" />
      </UiSidebarHeader>

      <UiSidebarContent>
        <NavTeam :nav-main="navMain" />
      </UiSidebarContent>

      <UiSidebarFooter>
        <UiSidebarMenu>
          <UiSidebarMenuItem>
            <UiDropdownMenu>
              <UiDropdownMenuTrigger as-child>
                <UiSidebarMenuButton
                  size="lg"
                  class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
                >
                  <UiAvatar class="size-8 rounded-lg">
                    <UiAvatarImage :src="user.avatar" :alt="user.name" />
                    <UiAvatarFallback class="rounded-lg">
                      {{ user.name?.charAt(0)?.toUpperCase() }}
                    </UiAvatarFallback>
                  </UiAvatar>
                  <div class="grid flex-1 text-sm leading-tight text-left">
                    <span class="font-semibold truncate">{{ user.name }}</span>
                    <span class="text-xs truncate">{{ user.email }}</span>
                  </div>
                </UiSidebarMenuButton>
              </UiDropdownMenuTrigger>
              <UiDropdownMenuContent
                class="w-[--radix-dropdown-menu-trigger-width] min-w-56 rounded-lg"
                side="right"
                align="start"
                :side-offset="4"
              >
                <UiDropdownMenuLabel class="p-0 font-normal">
                  <div class="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
                    <UiAvatar class="size-8 rounded-lg">
                      <UiAvatarImage :src="user.avatar" :alt="user.name" />
                      <UiAvatarFallback class="rounded-lg">
                        {{ user.name?.charAt(0)?.toUpperCase() }}
                      </UiAvatarFallback>
                    </UiAvatar>
                    <div class="grid flex-1 text-sm leading-tight text-left">
                      <span class="font-semibold truncate">{{ user.name }}</span>
                      <span class="text-xs truncate">{{ user.email }}</span>
                    </div>
                  </div>
                </UiDropdownMenuLabel>

                <UiDropdownMenuSeparator />
                <UiDropdownMenuGroup>
                  <UiDropdownMenuItem @click="router.push('/agent/profile')">
                    <User class="mr-2 h-4 w-4" />
                    个人中心
                  </UiDropdownMenuItem>
                </UiDropdownMenuGroup>

                <UiDropdownMenuSeparator />
                <UiDropdownMenuItem class="text-red-500" @click="handleLogout">
                  <LogOut class="mr-2 h-4 w-4" />
                  退出登录
                </UiDropdownMenuItem>
              </UiDropdownMenuContent>
            </UiDropdownMenu>
          </UiSidebarMenuItem>
        </UiSidebarMenu>
      </UiSidebarFooter>

      <UiSidebarRail />
    </UiSidebar>

    <UiSidebarInset>
      <header class="flex h-14 shrink-0 items-center gap-2 border-b px-4">
        <UiSidebarTrigger class="-ml-1" />
        <UiSeparator orientation="vertical" class="mr-2 h-4" />
        <UiBreadcrumb>
          <UiBreadcrumbList>
            <template v-for="(crumb, index) in breadcrumbs" :key="crumb.path">
              <UiBreadcrumbItem v-if="index < breadcrumbs.length - 1">
                <UiBreadcrumbLink as-child>
                  <router-link :to="crumb.path">
                    {{ crumb.title }}
                  </router-link>
                </UiBreadcrumbLink>
              </UiBreadcrumbItem>
              <UiBreadcrumbItem v-else>
                <UiBreadcrumbPage>{{ crumb.title }}</UiBreadcrumbPage>
              </UiBreadcrumbItem>
              <UiBreadcrumbSeparator v-if="index < breadcrumbs.length - 1" />
            </template>
          </UiBreadcrumbList>
        </UiBreadcrumb>
        <div class="ml-auto flex items-center gap-2">
          <LanguageChange />
          <ToggleTheme />
          <ThemePopover />
        </div>
      </header>

      <main class="flex-1 overflow-auto p-4 md:p-6">
        <router-view />
      </main>
    </UiSidebarInset>
  </UiSidebarProvider>
</template>
