import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'

export interface TabItem {
  path: string
  title: string
  name: string
}

// 首页 tab 始终保留
const HOME_TAB: TabItem = {
  path: '/dashboard',
  title: '仪表盘',
  name: 'Dashboard'
}

export const useTabsStore = defineStore(
  'tabs',
  () => {
    const tabs = ref<TabItem[]>([{ ...HOME_TAB }])
    const activeTab = ref('/dashboard')

    function addTab(route: RouteLocationNormalizedLoaded) {
      const title = (route.meta?.title as string) || route.name as string
      const path = route.path
      if (!title || path === '/') return
      const exists = tabs.value.some((t) => t.path === path)
      if (!exists) {
        tabs.value.push({
          path,
          title,
          name: route.name as string
        })
      }
      activeTab.value = path
    }

    function closeTab(path: string, currentPath: string): string {
      // 不允许关闭首页
      if (path === HOME_TAB.path) return currentPath

      const idx = tabs.value.findIndex((t) => t.path === path)
      if (idx === -1) return currentPath
      tabs.value.splice(idx, 1)

      // 如果关闭的是当前激活 tab，则跳转到相邻 tab
      if (path === currentPath) {
        const nextTab = tabs.value[idx] || tabs.value[idx - 1]
        const nextPath = nextTab ? nextTab.path : HOME_TAB.path
        activeTab.value = nextPath
        return nextPath
      }
      return currentPath
    }

    function closeOthers(path: string) {
      // 只保留首页和当前 tab
      tabs.value = tabs.value.filter(
        (t) => t.path === HOME_TAB.path || t.path === path
      )
      activeTab.value = path
    }

    function closeAll() {
      tabs.value = [{ ...HOME_TAB }]
      activeTab.value = HOME_TAB.path
    }

    function closeRight(path: string) {
      const idx = tabs.value.findIndex((t) => t.path === path)
      if (idx === -1) return
      tabs.value = tabs.value.slice(0, idx + 1)
      activeTab.value = path
    }

    function setActive(path: string) {
      activeTab.value = path
    }

    return {
      tabs,
      activeTab,
      addTab,
      closeTab,
      closeOthers,
      closeAll,
      closeRight,
      setActive
    }
  },
  {
    persist: {
      key: 'snack-admin-tabs',
      pick: ['tabs', 'activeTab']
    }
  }
)
