import React from 'react'

import { RenderOnScreen, useStyleConfig } from '../core'
import List from '../list'
import Menu from '../menu'
import { useHeaderContext } from './context'
import { HeaderServicesProps } from './header.types'
import HeaderServicesMessage from './headerServicesMessage'

/** Supporting internal component to avoid code duplication. */
function ListContent({ links = [] }: Pick<HeaderServicesProps, 'links'>) {
  const styles = useStyleConfig('Header', useHeaderContext()).services

  return (
    <>
      {links.length > 0 ? (
        links.map(({ text, url }, index) => (
          <Menu.Item isTruncated key={index} linkProps={{ href: url }} text={text} title={text} {...styles.item} />
        ))
      ) : (
        <HeaderServicesMessage />
      )}
    </>
  )
}

/** Displays a list of services available to the user. */
export function HeaderServices(props: HeaderServicesProps) {
  const { buttonProps, isApplication = false, links = [], showTopBorder = false, ...rest } = props
  const styles = useStyleConfig('Header', useHeaderContext()).services

  const offsetX = isApplication ? 179 : 135

  return (
    <>
      <RenderOnScreen minWidth="lg">
        <Menu isLazy={false} offset={[offsetX, 17]} placement="bottom-end" size="lg" {...rest}>
          <Menu.Button
            className="vui-services-trigger"
            icon="falTh"
            ml={1}
            size="lg"
            title="My services"
            {...styles.button}
            {...buttonProps}
          />

          <Menu.List heading="My Services" maxH={295} right={0} w={320} {...styles.list}>
            <ListContent links={links} />
          </Menu.List>
        </Menu>
      </RenderOnScreen>

      <RenderOnScreen maxWidth="lg">
        <List
          heading="My Services"
          {...styles.list}
          borderTop={showTopBorder ? 1 : 0}
          borderTopColor="sandstone.main"
          maxH={295}
          pt={1}
        >
          <ListContent links={links} />
        </List>
      </RenderOnScreen>
    </>
  )
}

HeaderServices.displayName = 'HeaderServices'

export default HeaderServices
