// @flow
import React, { type ComponentType } from 'react';
import styled from 'styled-components';
import type { MenuProps, TriggerProps } from './menu.proptypes';
import { Box } from '../../../primitives';
import { Text, type TextProps } from '../../typography/text';
import { UnstyledButton } from '../../behaviors/unstyled-button';
import { getPaletteColor } from '../../../mixins/branding';
import { ExpandMoreIcon } from '../../icon/expand-more-icon';
import { MenuItemList } from './menu-item-list';

const HoverText: ComponentType<TextProps> = styled(Text)`
  color: ${getPaletteColor('greyscale-dark')};

  &:hover {
    color: ${getPaletteColor('greyscale-black')};
  }
`;

const DefaultTrigger = ({ label, isOpen }: TriggerProps) => (
  <Box spacing="p1" stacked="row" justify="space-between" align="center">
    <HoverText spacing={['mb0', 'mr1']} fontSize="f1" bold>
      {label}
    </HoverText>

    <ExpandMoreIcon isOpen={isOpen} />
  </Box>
);

export const Menu = ({
  className,
  spacing,
  children,
  grow,
  shrink,
  basis,
  'data-qa': dataQa,
  'data-cy': dataCy,
  id,
  label,
  TriggerComponent = DefaultTrigger,
  isOpen,
  onToggle,
  flatTopCorners = false,
  dropdownSpacing,
  direction = 'right',
  targetElement,
}: MenuProps) => {
  const handleKeyDown = (event) => {
    if (event.key === 'ArrowDown') {
      onToggle();
      event.stopPropagation();
    }
  };

  return (
    <Box
      role="menu"
      spacing={spacing}
      grow={grow}
      shrink={shrink}
      basis={basis}
    >
      <UnstyledButton
        className={className}
        data-cy={dataCy}
        data-qa={dataQa}
        id={id}
        stacked="row"
        align="center"
        justify="space-between"
        onClick={(e) => {
          onToggle();
          e.stopPropagation();
        }}
        role="menuitem"
        aria-haspopup
        aria-expanded={isOpen}
        onKeyDown={handleKeyDown}
      >
        <TriggerComponent label={label} isOpen={isOpen} />
      </UnstyledButton>
      {isOpen && (
        <MenuItemList
          flatTopCorners={flatTopCorners}
          onToggle={onToggle}
          spacing={dropdownSpacing}
          direction={direction}
          targetElement={targetElement}
        >
          {children}
        </MenuItemList>
      )}
    </Box>
  );
};

Menu.displayName = 'Menu';
