// @flow
import React, { useState, useCallback } from 'react';
import styled from 'styled-components';
import { ClickOutside } from '../../behaviors';
import { LoadingIndicator } from '../../feedback-ui';
import { ContextMenuListContainer } from './context-menu-list-container/index';
import { ContextMenuListItem } from './context-menu-list-item/index';
import { EllipsisButton } from './ellipsis-button/index';
import { type ContextMenuProps } from './context-menu.proptypes';

const StyledContextMenu = styled.div`
  position: relative;
  display: flex;
`;

const useContextMenuState = () => {
  const [isExpanded, setIsExpanded] = useState(false);

  const handleCloseMenu = useCallback(() => {
    setIsExpanded(false);
  }, []);

  const handleTriggerButtonClick = useCallback(
    event => {
      event.stopPropagation();
      setIsExpanded(!isExpanded);
    },
    [isExpanded],
  );

  return { isExpanded, handleCloseMenu, handleTriggerButtonClick };
};

export const ContextMenu = ({
  TriggerButton = EllipsisButton,
  justify = 'right',
  items,
  isLoading = false,
}: ContextMenuProps) => {
  const {
    isExpanded,
    handleCloseMenu,
    handleTriggerButtonClick,
  } = useContextMenuState();
  const loadingIndicator = isLoading ? (
    <LoadingIndicator minHeight="16px" spacing="mt1" ready={!isLoading} />
  ) : null;

  const listContainer = isExpanded ? (
    <ContextMenuListContainer justify={justify}>
      {items.map(item => (
        <ContextMenuListItem
          key={item.id}
          item={item}
          onSelect={item.onSelect}
          closeMenu={handleCloseMenu}
          colorName={item.textColorName}
          danger={item.danger}
        >
          {item.label}
        </ContextMenuListItem>
      ))}
      {loadingIndicator}
    </ContextMenuListContainer>
  ) : null;

  return (
    <StyledContextMenu>
      <ClickOutside onClickOutside={handleCloseMenu}>
        <TriggerButton onClick={handleTriggerButtonClick} />
        {listContainer}
      </ClickOutside>
    </StyledContextMenu>
  );
};

ContextMenu.displayName = 'ContextMenu';
