import { Navigate } from 'react-router-dom'
import { Home } from '@mui/icons-material'
import YaLayout from '@/layouts/Base'
import HomePage from '@/pages/home'
import LazyImport from '@/components/asyncImport'
import { defineConfig } from '@/utils/common'
import type { DefinedRouteObject } from '@/configs/config'

// async import component
const ChartLazyComponent = LazyImport({
  action: import('@/pages/showcase/Echarts'),
})

const genRoutesMap = (
  routes: DefinedRouteObject[],
  res: Map<string, DefinedRouteObject>,
  prefix: string,
): Map<string, DefinedRouteObject> | undefined => {
  if (!routes || !Array.isArray(routes) || routes.length === 0) return
  routes.forEach(({ children = [], element, ...rest }) => {
    if (rest.path === '/' || rest.path === '*') {
      genRoutesMap(children, res, '')
    } else {
      const key = prefix === '' ? `/${rest.path}` : `${prefix}/${rest.path}`
      res.set(key, rest)
      genRoutesMap(children, res, key)
    }
  })
  return res
}

const routes: DefinedRouteObject[] = [
  {
    path: '/',
    element: <YaLayout />,
    children: [
      // 解决重定向问题
      { path: '/', element: <Navigate replace to="/home" /> },
      {
        path: 'home',
        element: <HomePage />,
        meta: {
          name: 'Home',
          type: 'LINK',
          icon: <Home />,
          desc: 'Home view!',
        },
      },
      {
        path: 'showcase',
        meta: {
          name: 'Showcase',
          type: 'ROOT',
        },
        children: [
          {
            path: 'charts',
            element: <ChartLazyComponent />,
            meta: {
              name: 'Charts',
              type: 'LINK',
            },
          },
        ],
      },
    ],
  },
  {
    path: '*',
    element: <Navigate replace to="/" />,
  },
]

// return path => routeObject mapping
export const useRoutesMap = () => {
  return defineConfig(genRoutesMap(routes, new Map(), '')) as Map<string, DefinedRouteObject>
}

export default defineConfig(routes)
