import { Menu, MenuProps } from 'antd'
import { useCallback, useMemo } from 'react'
import { history } from 'umi'
import { Routes, routes } from '../../../config/routes'

export const MenuTab = () => {
  const menus = useMemo(() => {
    function getMenus(routes?: Routes[]): MenuProps['items'] {
      return routes
        ?.filter((route) => !route.hideInMenu)
        ?.map((route) => ({
          label: route.title,
          key: route.path,
          children: !route.hideChildrenInMenu && getMenus(route.routes),
        }))
    }

    return getMenus(routes)
  }, [])

  const defaultSelectedKeys: MenuProps['defaultSelectedKeys'] = useMemo(
    () => [history.location.pathname],
    [],
  )

  const onSelect: MenuProps['onSelect'] = useCallback((info) => {
    history.push(info.key)
  }, [])

  return (
    <Menu
      mode="inline"
      items={menus}
      defaultSelectedKeys={defaultSelectedKeys}
      onSelect={onSelect}
    />
  )
}
