import { useMemo } from 'react';
import classnames from 'classnames';

import type { ClickableOnClick } from '~/src/components/Clickable';
import type { FC } from 'react';
import type { SideNavItem, SideNavItemPrimary } from '../types';

import Box from '~/src/components/Box';
import Clickable from '~/src/components/Clickable';
import Text from '~/src/components/Text';
import getItemCss from './getItemCss';

const ITEM_HEIGHT = '4.5em';

interface PrimaryItemsProps {
  items: SideNavItemPrimary[];
  activeItem?: SideNavItem;
  onItemClick: ClickableOnClick;
}

const PrimaryItems: FC<PrimaryItemsProps> = ({
  items,
  activeItem,
  onItemClick,
}) => {
  const itemCss = getItemCss();

  return useMemo(
    () => (
      <Box tag="ul" positionRelative>
        {items.map((item) => {
          const { text, href, Icon, after } = item;
          const isActive = item === activeItem;

          return (
            <Box key={href} tag="li" isBlock padding="0 1em">
              <Clickable
                href={href}
                fullWidth
                padding="0 1em"
                // the active item is the one that gets focus when the SideNav opened
                autoFocus={isActive}
                withFocusStyle={false}
                style={{ position: 'relative' }}
                onClick={onItemClick}
                testId={`sideNavItem:${href}`}
                height={ITEM_HEIGHT}
                className={classnames(itemCss.className, 'item', { isActive })}
                flexRow
                alignCenter
                positionRelative
              >
                <Icon size="2.6em" />
                <Box
                  flexGrow
                  flexRow
                  alignCenter
                  padding="0 0 0 0.43em"
                  style={{ fontSize: '2.4em' }}
                >
                  <Text
                    size="1em"
                    lineHeight="1.4em"
                    letterSpacing={0.05}
                    withEllipsis
                  >
                    {text}
                  </Text>
                  {after}
                </Box>
              </Clickable>
            </Box>
          );
        })}
        {itemCss.styles}
      </Box>
    ),
    [activeItem, items]
  );
};

export default PrimaryItems;
