import { computed } from 'vue'
import { useRoute, type RouteRecordName } from 'vue-router'
import type { Menu } from '@/core/types/menu'
import mainMenu from '@/main/side-menu'

type MenuList = (string | Menu)[]

function routeMatchesMenu(
  routeName: RouteRecordName | null | undefined,
  routePath: string,
  menu: Menu,
): boolean {
  if (!menu.route_name) return false
  if (menu.route_name === '/') return routePath === '/'
  return (
    routeName === menu.route_name ||
    routePath.includes(String(menu.route_name))
  )
}

function findTrailInMenuList(
  menus: MenuList,
  ancestors: string[],
  routeName: RouteRecordName | null | undefined,
  routePath: string,
): string[] | null {
  for (const entry of menus) {
    if (typeof entry === 'string') continue

    const pathTitles = entry.title ? [...ancestors, entry.title] : ancestors

    if (entry.route_name && routeMatchesMenu(routeName, routePath, entry)) {
      return pathTitles
    }

    if (entry.sub_menu) {
      const found = findTrailInMenuList(
        entry.sub_menu,
        pathTitles,
        routeName,
        routePath,
      )
      if (found) return found
    }
  }

  return null
}

function trailFromRouteMeta(route: ReturnType<typeof useRoute>): string[] {
  const breadcrumb = route.meta.breadcrumb
  if (
    Array.isArray(breadcrumb) &&
    breadcrumb.length > 0 &&
    breadcrumb.every((item) => typeof item === 'string')
  ) {
    return breadcrumb
  }

  const title = route.meta.title
  if (typeof title !== 'string' || !title) return []

  const module = route.meta.module
  if (typeof module === 'string' && module) {
    const section = module.charAt(0).toUpperCase() + module.slice(1)
    return [section, title]
  }

  return [title]
}

export function useBreadcrumb(extraMenus: MenuList[] = []) {
  const route = useRoute()

  return computed(() => {
    for (const menu of [mainMenu, ...extraMenus]) {
      const trail = findTrailInMenuList(menu, [], route.name, route.path)
      if (trail?.length) return trail
    }

    return trailFromRouteMeta(route)
  })
}
