import { Setting } from '@element-plus/icons-vue'
import type { Component } from 'vue'
import type { Scope } from '@/types/auth'
import {
  ADMIN_MENU, MONITOR_MENU, flattenNavMenu, type NavMenuItem
} from '@/config/navMenu'

export const MAX_QUICK_ENTRIES = 16
export const QUICK_GRID_COLUMNS = 8

export interface QuickEntryDef {
  key: string
  label: string
  path: string
  icon: Component
  hint?: string
  primary?: boolean
  pageKey: string
  group?: string
}

/** 当前页即总览，不作为快捷入口候选 */
const EXCLUDED_QUICK_ENTRY_KEYS = new Set(['admin-dashboard', 'monitor-dashboard'])

/** 旧版别名 key -> 菜单 key */
const LEGACY_KEY_ALIASES: Record<string, string> = {
  'platform-config': 'admin-map-editor',
  mission: 'admin-task-templates',
  cars: 'admin-cars',
  auth: 'admin-config-system-center',
  system: 'admin-config-system-center',
  ops: 'admin-config-ops-center',
  tasks: 'admin-config-strategy'
}

/** Platform 域下固定保留、不可删除的快捷入口 */
export const MANDATORY_PLATFORM_QUICK_KEYS = [
  'admin-maps',
  'admin-map-editor',
  'admin-cars',
  'admin-map-monitor',
  'admin-vehicle-hub',
  'admin-task-templates'
] as const

/** 与后端 DashboardShortcutCatalog.DefaultPlatformKeys 对齐 */
export const DEFAULT_PLATFORM_QUICK_KEYS = [
  ...MANDATORY_PLATFORM_QUICK_KEYS,
  'admin-config-system-center',
  'admin-config-ops-center',
  'admin-config-strategy'
] as const

export const DEFAULT_MONITOR_QUICK_KEYS = [
  'monitor-vehicle-hub', 'monitor-map', 'monitor-ops'
] as const

export function normalizeQuickKey(key: string): string {
  return LEGACY_KEY_ALIASES[key] ?? key
}

export function normalizeQuickKeys(keys: string[]): string[] {
  const seen = new Set<string>()
  const out: string[] = []
  for (const raw of keys) {
    const k = normalizeQuickKey(raw.trim())
    if (!k || seen.has(k) || EXCLUDED_QUICK_ENTRY_KEYS.has(k)) continue
    seen.add(k)
    out.push(k)
  }
  return out
}

export function isMandatoryQuickKey(key: string, scope: Scope): boolean {
  if (scope !== 'Platform') return false
  return (MANDATORY_PLATFORM_QUICK_KEYS as readonly string[]).includes(normalizeQuickKey(key))
}

/** 保证固定项始终存在且排在最前 */
export function ensureMandatoryQuickKeys(keys: string[], scope: Scope): string[] {
  const normalized = normalizeQuickKeys(keys)
  if (scope !== 'Platform') return normalized

  const mandatory = [...MANDATORY_PLATFORM_QUICK_KEYS]
  const rest = normalized.filter((k) => !(MANDATORY_PLATFORM_QUICK_KEYS as readonly string[]).includes(k))
  return [...mandatory, ...rest].slice(0, MAX_QUICK_ENTRIES)
}

export function finalizeQuickKeys(keys: string[], scope: Scope): string[] {
  return ensureMandatoryQuickKeys(normalizeQuickKeys(keys), scope)
}

function menuItemToQuick(item: NavMenuItem): QuickEntryDef | null {
  if (!item.key || EXCLUDED_QUICK_ENTRY_KEYS.has(item.key)) return null
  return {
    key: item.key,
    label: item.label,
    path: item.path,
    icon: item.icon ?? Setting,
    pageKey: item.key,
    group: item.group
  }
}

function buildCatalog(scope: Scope): Map<string, QuickEntryDef> {
  const map = new Map<string, QuickEntryDef>()
  const menu = scope === 'RCSMonitor' ? MONITOR_MENU : ADMIN_MENU
  for (const item of flattenNavMenu(menu)) {
    const q = menuItemToQuick(item)
    if (q) map.set(q.key, q)
  }
  return map
}

export function getQuickEntryCatalog(scope: Scope): QuickEntryDef[] {
  return [...buildCatalog(scope).values()]
}

export function resolveQuickEntry(key: string, scope: Scope): QuickEntryDef | undefined {
  return buildCatalog(scope).get(normalizeQuickKey(key))
}

export function defaultQuickKeys(scope: Scope): string[] {
  return scope === 'RCSMonitor'
    ? [...DEFAULT_MONITOR_QUICK_KEYS]
    : finalizeQuickKeys([...DEFAULT_PLATFORM_QUICK_KEYS], scope)
}

export function groupQuickEntries(items: QuickEntryDef[]): { group: string; items: QuickEntryDef[] }[] {
  const groups = new Map<string, QuickEntryDef[]>()
  for (const item of items) {
    const g = item.group ?? '其他'
    if (!groups.has(g)) groups.set(g, [])
    groups.get(g)!.push(item)
  }
  return [...groups.entries()].map(([group, list]) => ({ group, items: list }))
}
