// @flow
import React, { useCallback } from 'react';
import styled from 'styled-components';

import { UnstyledButton } from '../../../behaviors';
import { getPaletteColor } from '../../../../mixins/branding';

import {
  getItemBackgroundColor,
  getItemColor,
  getItemFontSize,
} from './context-menu-list-item.css-rules';
import {
  type ContextMenuListItemProps,
  contextMenuListItemPropTypes,
} from './context-menu-list-item.proptypes';

const StyledButton = styled(UnstyledButton)`
  padding: 10px 20px;
  font-size: ${getItemFontSize};
  color: ${getItemColor};
  outline: none;

  &:active {
    background: ${getItemBackgroundColor('active')};
    color: ${getPaletteColor('white')};
  }

  &:hover {
    background-color: ${getItemBackgroundColor('hover')};
    color: ${getPaletteColor('white')};
  }
`;

const useContextMenuListItemState = ({ onSelect, item, closeMenu }) => {
  const handleOnClick = useCallback(
    event => {
      event.stopPropagation();
      if (typeof onSelect === 'function') {
        onSelect(item);
      }
      closeMenu();
    },
    [onSelect, item, closeMenu],
  );

  return { handleOnClick };
};

export const ContextMenuListItem = ({
  onSelect,
  item,
  closeMenu,
  colorName = 'greyscale-black',
  children,
  danger,
}: ContextMenuListItemProps<*>) => {
  const { handleOnClick } = useContextMenuListItemState({
    onSelect,
    item,
    closeMenu,
  });

  return (
    <StyledButton
      insetFocus
      hasTransition={false}
      onClick={handleOnClick}
      colorName={colorName}
      danger={danger}
    >
      {children}
    </StyledButton>
  );
};

ContextMenuListItem.propTypes = contextMenuListItemPropTypes;
