import { lazy, Suspense, useMemo } from 'react'
import { Navigate, Outlet } from 'react-router'
import { useUserMenu } from '@/store/userStore'
import type { AppRouteObject } from '#/router'
import { PermissionType } from '#/enum'
import { isEmpty } from 'ramda'
import { clone } from 'ramda'
// import { Tag } from 'antd'
// import { Iconify } from '@/components/icon'
import { CircleLoading } from '@/components/loading'

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

// 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): AppRouteObject => {
  const baseRoute = createBaseRoute(menuItem, menuItem.path)
  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)

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

  return baseRoute
}

const createMenuRoute = (menuItem: API.MenuChildrenItem): AppRouteObject => {
  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[]): AppRouteObject[] {
  return menu.map((menuItem) => {
    // 创建目录路由
    if (menuItem.type === PermissionType.CATALOGUE) {
      return createCatalogueRoute(menuItem)
    }
    // 创建菜单路由
    return createMenuRoute(menuItem)
  })
}

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 || !menu.length) return []

    const menuCopy = clone(menu)
    // 给menu的每一级添加type, type为0, 即为目录, type为1, 即为菜单, 只有最后一级才是菜单
    addTypeToMenu(menuCopy)
    // console.log('添加type后的菜单', menuCopy)
    const constantMenu: API.MenuResult = [
      {
        id: 'dashboard',
        parentId: '-1',
        weight: 0,
        name: '首页',
        path: '/dashboard/index',
        visible: true,
        isKeepAlive: false,
        sortOrder: 1,
        icon: 'fengxiankongzhi1',
        menuType: 'MENU',
        label: '',
        type: 1,
        title: '首页',
        isHide: false
      }
    ]
    menuCopy.unshift(...constantMenu)

    // console.log('动态路由:', transformMenuToRoutes(menuCopy))
    return transformMenuToRoutes(menuCopy)
  }, [menu])
}
