import { lazy, Suspense, useMemo } from 'react'
import { Navigate, Outlet } from 'react-router'
import { useUserMenu } from '@/store/userStore'
import type { AppRouteObject } from '#/router'
import type { Permission } from '#/entity'
import { BasicStatus, MenuType, PermissionType } from '#/enum'
import { isEmpty } from 'ramda'
import { clone } from 'ramda'
import { flattenTrees } from '@/utils/tree'
import { Tag } from 'antd'
import { Iconify } from '@/components/icon'
import { CircleLoading } from '@/components/loading'
import { getRoutesFromModules } from '../utils'

const ENTRY_PATH = '/src/pages'
const PAGES = import.meta.glob('/src/pages/**/*.tsx')
// console.log(PAGES)
export const loadComponentFromPath = (path: string) => PAGES[`${ENTRY_PATH}${path}.tsx`]

/**
 * Build complete route path by traversing from current permission to root
 * @param {Permission} permission - current permission
 * @param {Permission[]} flattenedPermissions - flattened permission array
 * @param {string[]} segments - route segments accumulator
 * @returns {string} normalized complete route path
 */
function buildCompleteRoute(
  permission: Permission,
  flattenedPermissions: Permission[],
  segments: string[] = []
): string {
  // debugger
  // Add current route segment
  segments.unshift(permission.path)

  // Base case: reached root permission
  if (permission.parentId === '-1') {
    // debugger
    return segments.join('')
  }

  // Find parent and continue recursion
  const parent = flattenedPermissions.find((p) => p.id === permission.parentId)
  if (!parent) {
    debugger
    console.warn(`Parent permission not found for ID: ${permission.parentId}`)
    return `/${segments.join('/')}`
  }

  return buildCompleteRoute(parent, flattenedPermissions, segments)
}

// Components
function NewFeatureTag() {
  return (
    <Tag color='cyan' className='!ml-2'>
      <div className='flex items-center gap-1'>
        <Iconify icon='solar:bell-bing-bold-duotone' size={12} />
        <span className='ms-1'>NEW</span>
      </div>
    </Tag>
  )
}

// Route Transformers
const createBaseRoute = (menuItem: API.MenuChildrenItem, completeRoute: string): AppRouteObject => {
  // const { route, label, icon, order, hide, hideTab, status, frameSrc, newFeature } = permission
  const { path, meta, name, sortOrder } = menuItem
  const baseRoute: AppRouteObject = {
    path: path,
    meta: {
      label: name,
      key: completeRoute,
      hideMenu: !!meta?.isHide,
      // hideTab,
      // disabled: status === BasicStatus.DISABLE
      ...meta
    }
  }

  if (sortOrder) baseRoute.order = sortOrder
  // if (baseRoute.meta) {
  // if (frameSrc) baseRoute.meta.frameSrc = frameSrc
  // if (newFeature) baseRoute.meta.suffix = <NewFeatureTag /> // 菜单上的铃铛
  // }

  return baseRoute
}

const createCatalogueRoute = (
  menuItem: API.MenuChildrenItem,
  flattenedPermissions: API.MenuChildrenItem[]
): AppRouteObject => {
  // 1.创建基础路由
  // console.log(buildCompleteRoute(permission, flattenedPermissions))
  // console.log('0000', menuItem.path)
  const baseRoute = createBaseRoute(menuItem, menuItem.path)
  // console.log(baseRoute)
  if (baseRoute.meta) {
    baseRoute.meta.hideTab = true
  }

  const { parentId, children = [] } = menuItem
  if (parentId === '-1') {
    baseRoute.element = (
      <Suspense fallback={<CircleLoading />}>
        <Outlet />
      </Suspense>
    )
  }

  baseRoute.children = transformMenuToRoutes(children, flattenedPermissions)

  if (!isEmpty(children)) {
    baseRoute.children.unshift({
      index: true,
      element: <Navigate to={children[0].path} replace />
    })
  }

  return baseRoute
}

const createMenuRoute = (
  menuItem: API.MenuChildrenItem,
  flattenedPermissions: API.MenuChildrenItem[]
): AppRouteObject => {
  // console.log('1111', menuItem.path)
  const baseRoute = createBaseRoute(menuItem, menuItem.path)
  if (menuItem.path) {
    const Element = lazy(loadComponentFromPath(menuItem.path) as any)

    if (menuItem.frameSrc) {
      baseRoute.element = <Element src={menuItem.frameSrc} />
    } else {
      baseRoute.element = (
        <Suspense fallback={<CircleLoading />}>
          <Element />
        </Suspense>
      )
    }
  }

  return baseRoute
}

function transformMenuToRoutes(
  menu: API.MenuChildrenItem[],
  flattenedPermissions: API.MenuChildrenItem[]
): AppRouteObject[] {
  return menu.map((menuItem) => {
    // 创建目录路由
    if (menuItem.type === PermissionType.CATALOGUE) {
      return createCatalogueRoute(menuItem, flattenedPermissions)
    }
    // 创建菜单路由
    return createMenuRoute(menuItem, flattenedPermissions)
  })
}

const addTypeToMenu = (menu: API.MenuResult) => {
  menu.forEach((item) => {
    if (item.children && item.children.length > 0) {
      item.type = 0
      addTypeToMenu(item.children)
    } else {
      item.type = 1
    }
  })
}
export function usePermissionRoutes() {
  const menu = useUserMenu()

  return useMemo(() => {
    if (!menu) return []

    const menuCopy = clone(menu)
    // 给menu的每一级添加type, type为0, 即为目录, type为1, 即为菜单, 只有最后一级才是菜单
    addTypeToMenu(menuCopy)
    console.log('添加type后的菜单', menuCopy)

    const flattenedMenu = flattenTrees(menuCopy) // 拍平成功

    console.log('~~~~~~', transformMenuToRoutes(menuCopy, flattenedMenu))
    // 将菜单转换成路由
    return transformMenuToRoutes(menuCopy, flattenedMenu)
  }, [menu])
}
