import { Box, HoverCard, NavLink } from '@tidbcloud/uikit'
import { type LocationDescriptor } from 'history'
import { isBoolean, isString } from 'lodash-es'
import { useCallback, useMemo } from 'react'
import { useHistory, useLocation } from 'react-router-dom'

interface NavItemProps {
  label: React.ReactNode
  tooltip?: React.ReactNode
  to?: LocationDescriptor
  manualActive?: boolean
  disabled?: boolean
  onClick?: () => void
  'data-testid'?: string
}

const NavItem = ({ label, tooltip, to, manualActive, disabled, onClick, 'data-testid': dataTestId }: NavItemProps) => {
  const history = useHistory()
  const { pathname } = useLocation()

  const isPathMatched = useMemo(() => {
    const navPath = isString(to) ? to : to?.pathname

    return !!navPath && pathname.startsWith(navPath)
  }, [to, pathname])
  const active = isBoolean(manualActive) ? manualActive : isPathMatched

  const clickHandler = useCallback(() => {
    onClick?.()

    const navPath = isString(to) ? to : to?.pathname

    if (to && pathname !== navPath) {
      history.push(to)
    }
  }, [history, onClick, pathname, to])

  const navlink = (
    <NavLink
      lh={1.5}
      fw={500}
      styles={{
        label: { lineHeight: '16px' }
      }}
      sx={{ textWrap: 'nowrap' }}
      disabled={disabled}
      label={label}
      active={active}
      onClick={clickHandler}
      data-testid={dataTestId}
    />
  )

  return (
    <Box py={2} sx={{ '&:first-of-type': { paddingTop: 0 } }}>
      {tooltip ? (
        <HoverCard position="right" shadow="md" width={300} withArrow>
          <HoverCard.Target>
            <span>{navlink}</span>
          </HoverCard.Target>
          <HoverCard.Dropdown>
            <span>{tooltip}</span>
          </HoverCard.Dropdown>
        </HoverCard>
      ) : (
        navlink
      )}
    </Box>
  )
}

export default NavItem
