import { Menu as MenuRaw } from 'antd'
import { useRoute, findRouteByPathName } from 'router'

import type { MenuProps } from 'antd'
import type { RouteConfig, RouteConfigTree } from 'router'

type MenuItems = Required<MenuProps>['items']
type MenuProp = { 
  routes: RouteConfig[] | undefined,
  onSelect?: (route: RouteConfigTree) => void
}

export const routesToMenuItems = (routes: MenuProp['routes']): MenuItems | undefined => {
  if (!routes) {
    return;
  }
  return routes
    .filter(route => route.meta)
    .map(route => ({
      ...route.meta,
      icon: route.meta?.icon && <route.meta.icon />,
      key: route.path,
      children: routesToMenuItems(route.children)
    }))
}

export const RouteMenu = ({ routes, onSelect }: MenuProp) => {
  const route = useRoute()
  const menuItems = routesToMenuItems(routes)
  const onClick: MenuProps['onClick'] = e => {
    const routeTree = findRouteByPathName(e.key) as RouteConfigTree
    onSelect && onSelect(routeTree)
  };
  const selectKeys = route?.path ? [route?.path] : []

  return (
    <MenuRaw
      onClick={onClick}
      defaultSelectedKeys={selectKeys}
      mode="inline"
      items={menuItems}
    />
  )
}