import Tooltip from '@/components/ui/Tooltip'
import Menu from '@/components/ui/Menu'
import VerticalMenuIcon from './VerticalMenuIcon'
import { Link } from 'react-router-dom'
import { Trans, useTranslation } from 'react-i18next'
import type { CommonProps } from '@/@types/common'
import type { Direction } from '@/@types/theme'
import type { NavigationTree } from '@/@types/navigation'
import { PermissionCheck } from '@/components/shared'

const { MenuItem } = Menu

interface CollapsedItemProps extends CommonProps {
  title: string
  translateKey: string
  direction?: Direction
}

interface DefaultItemProps {
  nav: NavigationTree
  onLinkClick?: (link: { key: string; title: string; path: string }) => void
  sideCollapsed?: boolean
  userAuthority: string[]
  icon?: string
}

interface VerticalMenuItemProps extends CollapsedItemProps, DefaultItemProps {}

const CollapsedItem = ({ title, translateKey, children, direction }: CollapsedItemProps) => {
  const { t } = useTranslation()

  return (
    <Tooltip title={t(translateKey) || title} placement={direction === 'rtl' ? 'left' : 'right'}>
      {children}
    </Tooltip>
  )
}

const DefaultItem = (props: DefaultItemProps) => {
  const { nav, onLinkClick, sideCollapsed } = props

  return (
    <PermissionCheck permissions={nav.authority}>
      <MenuItem key={nav.key} icon={nav.icon} eventKey={nav.key}>
        <Link
          to={nav.path}
          className="flex items-center h-full w-full"
          onClick={() =>
            onLinkClick?.({
              key: nav.key,
              title: nav.title,
              path: nav.path,
            })
          }
          target={nav.isExternalLink ? '_blank' :  ''}
        >
          <VerticalMenuIcon icon={nav.icon} />
          {!sideCollapsed && (
            <span>
              <Trans i18nKey={nav.translateKey} defaults={nav.title} />
            </span>
          )}
        </Link>
      </MenuItem>
    </PermissionCheck>
  )
}

const VerticalSingleMenuItem = ({
  nav,
  onLinkClick,
  sideCollapsed,
  userAuthority,
  direction,
  icon,
}: Omit<VerticalMenuItemProps, 'title' | 'translateKey'>) => {
  return (
    <PermissionCheck permissions={nav.authority}>
      {sideCollapsed ? (
        <CollapsedItem title={nav.title} translateKey={nav.translateKey} direction={direction}>
          <DefaultItem
            nav={nav}
            sideCollapsed={sideCollapsed}
            userAuthority={userAuthority}
            icon={icon}
            onLinkClick={onLinkClick}
          />
        </CollapsedItem>
      ) : (
        <DefaultItem
          nav={nav}
          sideCollapsed={sideCollapsed}
          userAuthority={userAuthority}
          icon={icon}
          onLinkClick={onLinkClick}
        />
      )}
    </PermissionCheck>
  )
}

export default VerticalSingleMenuItem
