import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { usePermissionStore } from './permissions'
import { slugToPageType, pageTypeToSlug } from '../utils/slug'
import { getWorkspaceSidebarItems, transformWorkspacePages, WorkspacePage } from '../api/workspace'

export interface AppMenuItem {
  id: string
  key: string
  label: string
  icon?: string
  type: 'pagetype' | 'route' | 'url' | 'workspace' | 'group'  // 菜单类型，新增 group
  pagetype?: string    // 页面类型名称（如：Local AI Agent）
  routeName?: string   // 路由名
  url?: string         // URL路径
  workspaceName?: string // Workspace 名称（工作区文档名）
  isPrivate?: boolean  // Whether this is a private workspace
  // 层级关系
  parentId?: string | null
  order?: number
  hidden?: boolean
  children?: AppMenuItem[]
  page?: {
    pagetype: string
    list?: boolean
    detail?: boolean
    order_by?: string
  }
}

const STORAGE_KEY = 'app.menu.items'

function loadFromStorage(): AppMenuItem[] {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (!raw) return []
    const parsed = JSON.parse(raw)
    if (Array.isArray(parsed)) return parsed
    return []
  } catch {
    return []
  }
}

function saveToStorage(items: AppMenuItem[]) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
}

// 默认空菜单 - 菜单现在完全由后端数据驱动
function getDefaultMenus(): AppMenuItem[] {
  return []
}

export const useMenuStore = defineStore('menu', () => {
  // 标记是否已从后端加载过
  const loadedFromBackend = ref(false)

  // Loading promise to prevent duplicate calls
  let loadingPromise: Promise<any> | null = null

  // Workspace dictionary for quick lookup (like jingrow.workspaces in old frontend)
  // Key: slug(workspace.name), Value: workspace data
  const workspaces = ref<Record<string, WorkspacePage>>({})

  // Access flags from backend
  const hasWorkspaceAccess = ref(false)
  const hasCreateWorkspaceAccess = ref(false)
  
  // 正确初始化为数组，而不是函数
  const initItems = () => {
    const cached = loadFromStorage()
    if (Array.isArray(cached) && cached.length) return cached as AppMenuItem[]
    const defaults = getDefaultMenus()
    saveToStorage(defaults)
    return defaults
  }
  const items = ref<AppMenuItem[]>(initItems())

  // 统一保存
  function persist() {
    // 分层排序：先按层级分组，再分别排序
    const rootMenus = items.value.filter(m => !m.parentId)
    const childMenus = items.value.filter(m => m.parentId)
    
    // 对根菜单排序
    rootMenus.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
    
    // 对子菜单按父菜单分组排序
    const groupedChildren = childMenus.reduce((acc, child) => {
      const parentId = child.parentId!
      if (!acc[parentId]) acc[parentId] = []
      acc[parentId].push(child)
      return acc
    }, {} as Record<string, AppMenuItem[]>)
    
    // 对每个父菜单的子菜单排序
    Object.values(groupedChildren).forEach(children => {
      children.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
    })
    
    // 重新组合：先放根菜单，再按父菜单顺序放子菜单
    const sorted: AppMenuItem[] = []
    rootMenus.forEach(root => {
      sorted.push(root)
      if (groupedChildren[root.id]) {
        sorted.push(...groupedChildren[root.id])
      }
    })
    
    saveToStorage(sorted)
    items.value = sorted
  }

  function addMenu(item: AppMenuItem) {
    const newItem = { ...item, id: item.id || crypto.randomUUID() }
    
    // 如果没有指定order，自动分配
    if (newItem.order === undefined || newItem.order === null) {
      if (newItem.parentId) {
        // 子菜单：在父菜单下分配独立的order
        const siblings = items.value.filter(m => m.parentId === newItem.parentId)
        const maxSiblingOrder = Math.max(...siblings.map(s => s.order ?? 0), 0)
        newItem.order = maxSiblingOrder + 1
      } else {
        // 父菜单：在根级别分配独立的order
        const rootMenus = items.value.filter(m => !m.parentId)
        const maxRootOrder = Math.max(...rootMenus.map(r => r.order ?? 0), 0)
        newItem.order = maxRootOrder + 1
      }
    }
    
    items.value.push(newItem)
    persist()
  }

  function updateMenu(id: string, patch: Partial<AppMenuItem>) {
    const idx = items.value.findIndex(m => m.id === id)
    if (idx >= 0) {
      items.value[idx] = { ...items.value[idx], ...patch }
      persist()
    }
  }

  function removeMenu(id: string) {
    items.value = items.value.filter(m => m.id !== id)
    persist()
  }

  function resetDefault() {
    items.value = getDefaultMenus()
    persist()
  }

  function clearCache() {
    localStorage.removeItem(STORAGE_KEY)
    items.value = getDefaultMenus()
    persist()
  }

  /**
   * 从后端加载 Workspace 菜单数据
   * 菜单完全由后端数据驱动
   */
  async function loadFromBackend() {
    // Return existing promise if already loading (prevent duplicate calls)
    if (loadingPromise) return loadingPromise
    // Already loaded
    if (loadedFromBackend.value) return { success: true, count: items.value.length }

    loadingPromise = (async () => {
      try {
        const response = await getWorkspaceSidebarItems()
        const workspaceMenuItems = transformWorkspacePages(response.pages)

        // Build workspace dictionary (key: slug(workspace.name))
        const dict: Record<string, WorkspacePage> = {}
        for (const page of response.pages) {
          const slugKey = pageTypeToSlug(page.name)
          dict[slugKey] = page
        }
        workspaces.value = dict

        // Store access flags
        hasWorkspaceAccess.value = response.has_access || false
        hasCreateWorkspaceAccess.value = response.has_create_access || false

        // 直接使用后端返回的菜单数据
        items.value = workspaceMenuItems
        persist()

        loadedFromBackend.value = true

        return { success: true, count: workspaceMenuItems.length }
      } catch (error: any) {
        console.error('Failed to load menu from backend:', error)
        return { success: false, error: error.message }
      } finally {
        loadingPromise = null
      }
    })()

    return loadingPromise
  }

  /**
   * 强制重新加载后端菜单数据（忽略缓存）
   */
  async function reloadFromBackend() {
    loadedFromBackend.value = false
    loadingPromise = null
    return loadFromBackend()
  }

  const visibleItems = computed(() => {
    const permissionStore = usePermissionStore()

    return items.value.filter(m => {
      if (m.hidden) return false

      // 权限驱动规则：pagetype 类型的菜单仅在有 read 权限时显示
      if (m.type === 'pagetype' && m.pagetype) {
        const pagetypeName = m.pagetype
        if (!permissionStore.canRead(pagetypeName)) {
          return false
        }
      }

      // workspace 类型暂时不做细粒度 pagetype 检查，由 WorkspacePage 内部再过滤链接
      return true
    })
  })

  return {
    items,
    visibleItems,
    loadedFromBackend,
    workspaces,
    hasWorkspaceAccess,
    hasCreateWorkspaceAccess,
    addMenu,
    updateMenu,
    removeMenu,
    resetDefault,
    clearCache,
    persist,
    loadFromBackend,
    reloadFromBackend
  }
})


