import { useState, Suspense, lazy } from 'react'
import classNames from 'classnames'
import Drawer from '@/components/ui/Drawer'
import { NAV_MODE_THEMED, NAV_MODE_TRANSPARENT, DIR_RTL } from '@/constants/theme.constant'
import withHeaderItem, { WithHeaderItemProps } from '@/utils/hoc/withHeaderItem'
import NavToggle from '@/components/shared/NavToggle'
import useResponsive from '@/utils/hooks/useResponsive'
import { useStoreState } from '@/store'

const VerticalMenuContent = lazy(() => import('@/components/template/VerticalMenuContent'))

type MobileNavToggleProps = {
  toggled?: boolean
}

const MobileNavToggle = withHeaderItem<MobileNavToggleProps & WithHeaderItemProps>(NavToggle)

const MobileNav = () => {
  const [isOpen, setIsOpen] = useState(false)

  const openDrawer = () => {
    setIsOpen(true)
  }

  const onDrawerClose = () => {
    setIsOpen(false)
  }

  const themeColor = useStoreState((state) => state.theme.themeColor)
  const primaryColorLevel = useStoreState((state) => state.theme.primaryColorLevel)
  const navMode = useStoreState((state) => state.theme.navMode)
  const mode = useStoreState((state) => state.theme.mode)
  const direction = useStoreState((state) => state.theme.direction)
  const currentRouteKey = useStoreState((state) => state.base.common.currentRouteKey)
  const sideNavCollapse = useStoreState((state) => state.theme.layout.sideNavCollapse)
  const userAuthority = useStoreState((state) => state.auth.user.authority)

  const { smaller } = useResponsive()

  const navColor = () => {
    if (navMode === NAV_MODE_THEMED) {
      return `bg-${themeColor}-${primaryColorLevel} side-nav-${navMode}`
    }

    if (navMode === NAV_MODE_TRANSPARENT) {
      return `side-nav-${mode}`
    }

    return `side-nav-${navMode}`
  }

  const { mainMenu: navigationConfig } = useStoreState((state) => state.abpConfig.menu)

  return (
    <>
      {smaller.md && (
        <>
          <div className="text-2xl" onClick={openDrawer}>
            <MobileNavToggle toggled={isOpen} />
          </div>
          <Drawer
            title="Navigation"
            isOpen={isOpen}
            bodyClass={classNames(navColor(), 'p-0')}
            width={330}
            placement={direction === DIR_RTL ? 'right' : 'left'}
            onClose={onDrawerClose}
            onRequestClose={onDrawerClose}
          >
            <Suspense fallback={<></>}>
              {isOpen && (
                <VerticalMenuContent
                  navMode={navMode}
                  collapsed={false}
                  navigationTree={navigationConfig}
                  routeKey={currentRouteKey}
                  userAuthority={userAuthority as string[]}
                  direction={direction}
                  onMenuItemClick={onDrawerClose}
                />
              )}
            </Suspense>
          </Drawer>
        </>
      )}
    </>
  )
}

export default MobileNav
