import { useEffect, useMemo, useState } from 'react'
import { useMatches, useNavigate } from 'react-router'
import { useSettingActions, useSettings } from '@/store/settingStore'
import {
  useFlattenedRoutes,
  usePathname,
  usePermissionRoutes,
  useRouteToMenuFn
} from '@/router/hooks'
import { menuFilter } from '@/router/utils'
import { ThemeLayout, ThemeMode } from '#/enum'
import { Layout, Menu, type MenuProps } from 'antd'
import Scrollbar from '@/components/scrollbar'
import { NAV_WIDTH } from '../config'
import NavLogo from './nav-logo'

const { VITE_APP_HOMEPAGE: HOMEPAGE } = import.meta.env

const { Sider } = Layout

type Props = {
  closeSideBarDrawer?: () => void
}
export default function NavVertical(props: Props) {
  const navigate = useNavigate()
  const matches = useMatches()
  const pathname = usePathname()

  const settings = useSettings()
  // 从设置中获取布局、模式和暗色侧边栏
  const { themeLayout, themeMode, darkSidebar } = settings
  const { setSettings } = useSettingActions()

  // 使用useRouteToMenuFn钩子函数获取路由到菜单的函数
  const routeToMenuFn = useRouteToMenuFn()
  // 使用usePermissionRoutes钩子函数获取权限路由
  const permissionRoutes = usePermissionRoutes()
  // 使用useFlattenedRoutes钩子函数获取扁平化的路由
  const flattenedRoutes = useFlattenedRoutes()

  // 根据布局设置是否折叠
  const collapsed = useMemo(() => themeLayout === ThemeLayout.Mini, [themeLayout])

  // 根据权限路由和路由到菜单的函数生成菜单列表
  const menuList = useMemo(() => {
    const withOutDashboard = permissionRoutes.filter((e) => e.path !== HOMEPAGE)
    const menuRoutes = menuFilter(withOutDashboard)
    return routeToMenuFn(menuRoutes)
  }, [routeToMenuFn, permissionRoutes])

  // 根据当前路径名生成选中的菜单项
  const selectedKeys = useMemo(() => [pathname], [pathname])

  // 使用useState钩子函数设置展开的菜单项
  const [openKeys, setOpenKeys] = useState<string[]>([])
  // 首次加载时设置 openKeys
  useEffect(() => {
    if (!collapsed) {
      const keys = matches
        .filter((match) => match.pathname !== '/' && match.pathname !== pathname)
        .map((match) => match.pathname)
      setOpenKeys(keys)
    }
  }, [collapsed, matches, pathname])

  const handleToggleCollapsed = () => {
    setSettings({
      ...settings,
      themeLayout: collapsed ? ThemeLayout.Vertical : ThemeLayout.Mini
    })
  }

  const onClick: MenuProps['onClick'] = ({ key }) => {
    const nextLink = flattenedRoutes?.find((e) => e.key === key)
    if (nextLink?.hideTab && nextLink?.frameSrc) {
      window.open(nextLink?.frameSrc, '_blank')
      return
    }

    navigate(key)
    props?.closeSideBarDrawer?.()
  }

  const handleOpenChange: MenuProps['onOpenChange'] = (keys) => {
    setOpenKeys(keys)
  }

  const sidebarTheme = useMemo(() => {
    if (themeMode === ThemeMode.Dark) {
      return darkSidebar ? 'light' : 'dark'
    }
    return darkSidebar ? 'dark' : 'light'
  }, [themeMode, darkSidebar])

  return (
    <Sider
      trigger={null}
      collapsible
      collapsed={collapsed}
      width={NAV_WIDTH}
      theme={sidebarTheme}
      className='!fixed left-0 top-0 h-screen border-r border-dashed border-border'>
      <div className='flex h-full flex-col'>
        <NavLogo collapsed={collapsed} onToggle={handleToggleCollapsed} />

        <Scrollbar>
          <Menu
            mode='inline'
            items={menuList}
            theme={sidebarTheme}
            selectedKeys={selectedKeys}
            openKeys={openKeys}
            onOpenChange={handleOpenChange}
            className='!border-none'
            onClick={onClick}
          />
        </Scrollbar>
      </div>
    </Sider>
  )
}
