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

const TABS_STORAGE_KEY = 'robot-admin-tabs'

export interface TabItem {
  path: string
  title: string
}

interface StoredTabs {
  tabs: TabItem[]
  activePath: string
}

function getTabTitle(route: RouteLocationNormalizedLoaded): string {
  const code = route.params?.code as string | undefined
  if (code) {
    return code
  }
  return (route.meta?.title as string) || '未命名'
}

export const useTabsStore = defineStore('tabs', {
  state: () => ({
    tabs: [] as TabItem[],
    saveEnabled: false,
  }),
  actions: {
    addOrSwitch(route: RouteLocationNormalizedLoaded) {
      const path = route.path
      const title = getTabTitle(route)
      const idx = this.tabs.findIndex((t) => t.path === path)
      if (idx >= 0) {
        this.tabs[idx].title = title
      } else {
        this.tabs.push({ path, title })
      }
      if (this.saveEnabled) {
        this.saveToStorage(route.path)
      }
    },
    enableSave() {
      this.saveEnabled = true
    },
    remove(path: string) {
      const idx = this.tabs.findIndex((t) => t.path === path)
      if (idx >= 0) {
        this.tabs.splice(idx, 1)
      }
    },
    reorder(fromIndex: number, toIndex: number) {
      if (fromIndex < 0 || fromIndex >= this.tabs.length || toIndex < 0 || toIndex >= this.tabs.length) return
      const [item] = this.tabs.splice(fromIndex, 1)
      this.tabs.splice(toIndex, 0, item)
    },
    closeOthers(path: string) {
      this.tabs = this.tabs.filter((t) => t.path === path)
    },
    closeRight(pathOrIndex: string | number) {
      const idx =
        typeof pathOrIndex === 'number'
          ? pathOrIndex
          : this.tabs.findIndex((t) => t.path === pathOrIndex)
      if (idx >= 0 && idx < this.tabs.length - 1) {
        this.tabs.splice(idx + 1)
      }
    },
    getTabTitle(route: RouteLocationNormalizedLoaded) {
      return getTabTitle(route)
    },
    saveToStorage(activePath: string) {
      try {
        const data: StoredTabs = { tabs: [...this.tabs], activePath }
        sessionStorage.setItem(TABS_STORAGE_KEY, JSON.stringify(data))
      } catch {
        /* ignore */
      }
    },
    restoreFromStorage(): string | null {
      try {
        const raw = sessionStorage.getItem(TABS_STORAGE_KEY)
        if (!raw) return null
        const data = JSON.parse(raw) as StoredTabs
        if (Array.isArray(data.tabs) && data.tabs.length > 0) {
          this.tabs = data.tabs
          return data.activePath || data.tabs[0]?.path || null
        }
      } catch {
        /* ignore */
      }
      return null
    },
  },
})
