import React, { Fragment } from 'react'

import Avatar from '../avatar'
import { useStyleConfig } from '../core'
import List from '../list'
import Popover from '../popover'
import { isJsx, isObject } from '../utils'
import { useHeaderContext } from './context'
import { HeaderAccountProps, HeaderAccountUserInfoData } from './headerAccount.types'
import HeaderAccountUserInfo from './headerAccountUserInfo'

/** Disables popper's dynamic re-positioning */

/** Displays user account information and helpful links, like settings or logout. */
export function HeaderAccount(props: HeaderAccountProps) {
  const { contentProps, options = {}, sections, triggerProps, userInfo, ...rest } = props
  const { isMobile } = useHeaderContext()
  const styles = useStyleConfig('Header', useHeaderContext()).account
  const name = isObject<HeaderAccountUserInfoData>(userInfo) ? userInfo.displayName : ''
  const variant = styles?.trigger?.variant ?? 'solidDarkBlue'
  const offsetX = isMobile ? 64 : 39

  return (
    <Popover isLazy={false} offset={[offsetX, 16]} placement="bottom-end" {...rest}>
      <Popover.Trigger
        as={Avatar}
        className="vui-headerAccountTrigger"
        isInteractive
        ml={1}
        name={name}
        role="button"
        size="lg"
        title="Account"
        variant={variant}
        {...styles.trigger}
        {...triggerProps}
      />

      <Popover.Content
        borderRadius={0}
        className="vui-headerAccountContent"
        column
        {...styles.content}
        w={isMobile ? 280 : 320}
        {...contentProps}
      >
        {isJsx(userInfo) ? userInfo : userInfo && <HeaderAccountUserInfo {...userInfo} />}

        {isJsx(sections)
          ? sections
          : sections && (
              <List className="vui-headerAccountList" mb={2}>
                {sections.map(({ heading, links }, index) => (
                  <Fragment key={index}>
                    <List.Divider />

                    {heading && <List.Heading text={heading} />}

                    {links?.map(({ icon, url, ...rest }, index) => (
                      <List.Item iconLeft={icon} key={index} linkProps={{ href: url }} {...rest} />
                    ))}
                  </Fragment>
                ))}
              </List>
            )}
      </Popover.Content>
    </Popover>
  )
}

HeaderAccount.displayName = 'HeaderAccount'

export default HeaderAccount
