import { useStyleConfig, vui } from '../core'
import List from '../list'
import { cs, MouseEvent, useCallbackRef } from '../utils'
import { useHeaderContext } from './context'
import { HeaderLinkItemProps } from './header.types'

/** Individual link item of the Header. */
export const HeaderLinkItem = vui<'li', HeaderLinkItemProps>((props, ref) => {
  const { className, icon, isActive, linkProps, onClick: onClickProp, url, ...rest } = props
  const { isMobile, setIsMobileOpen } = useHeaderContext() ?? {}
  const styles = useStyleConfig('Header', useHeaderContext()).linkItem

  const onClick = useCallbackRef((e: MouseEvent<HTMLLIElement>) => {
    setIsMobileOpen(false)
    onClickProp?.(e)
  })
  const linkPropsExtended = { ...linkProps, display: 'inline-flex', alignItems: 'center' }
  const linkActiveProps = isActive
    ? isMobile
      ? {
          bg: 'skyBlue.95',
          borderColor: 'seaBlue.main',
          borderLeftWidth: 3,
          hoverBg: 'skyBlue.90',
          pl: '13px',
          activeBorderBottomWidth: 0,
          pt: '0px',
        }
      : { borderBottomWidth: 4, pt: '4px' }
    : {}

  const linkMobileProps = isMobile
    ? {
        color: 'darkBlue.main',
        hoverColor: 'darkBlue.main',
        hoverBg: 'skyBlue.90',
        activeColor: 'darkBlue.main',
        activeBg: 'transparent',
        activeBorderColor: 'seaBlue.main',
        activeBorderLeftWidth: 0,
        pt: '0',
        activePl: isActive ? '13px' : '16px',
      }
    : { activeBorderBottomWidth: 0, pt: '0px', activePt: isActive ? '1px' : '0' }

  const itemScreenProps = isMobile ? {} : { display: 'inline-flex', fontWeight: 'medium', h: '100%' }

  return (
    <List.Item
      className={cs('vui-headerLinkItem', className, `${isActive && 'is-active'}`)}
      iconLeft={icon}
      linkProps={{
        href: url,
        ringInset: true,
        transition: 'all 0.1s, border-width 0s, padding 0s',
        w: { xs: '100%', lg: 'max-content' },
        px: { xs: '16px', lg: '10px', xl: '16px' },
        ...styles.link,
        ...linkPropsExtended,
        ...linkMobileProps,
        ...linkActiveProps,
      }}
      onClick={onClick}
      ref={ref}
      {...itemScreenProps}
      {...styles.container}
      {...rest}
    />
  )
})

HeaderLinkItem.displayName = 'HeaderLinkItem'
export default HeaderLinkItem
