import { PopoverMenu, Button, ButtonProps } from '@wix/design-system';
import React, { ReactNode, useMemo } from 'react';
import { ChevronDown } from '@wix/wix-ui-icons-common';
import { ActionSubItemPrivate } from './ActionSubItemProps';
import { DisabledTooltip } from '../DisabledTooltip';

export function ActionPopover(props: {
  actionItem: ActionSubItemPrivate;
  size?: ButtonProps['size'];
  priority?: ButtonProps['priority'];
  fullWidth?: ButtonProps['fullWidth'];
  onPopoverClick?: () => void;
}) {
  const { actionItem, size, priority, onPopoverClick, fullWidth } = props;
  const { dataHook, subItems, popoverMenuProps } = actionItem;

  const allActions = useMemo(() => {
    return subItems
      ?.filter((subItemGroup) => subItemGroup?.length)
      .reduce<ReactNode[]>((result, group, index, array) => {
        return [
          ...result,
          ...group.map((item) => {
            return (
              <PopoverMenu.MenuItem
                prefixIcon={item.prefixIcon}
                disabled={item.disabled}
                text={item.label}
                key={item.label}
                subtitle={item.subtitle}
                dataHook={item.dataHook}
                onClick={item.onClick}
              />
            );
          }),
          ...(index !== array.length - 1
            ? [<PopoverMenu.Divider key={index} />]
            : []),
        ];
      }, []);
  }, [subItems]);

  return (
    <PopoverMenu
      {...popoverMenuProps}
      dataHook={dataHook ? `${dataHook}-popover` : undefined}
      triggerElement={({ toggle }) => (
        <DisabledTooltip
          content={actionItem.tooltip}
          dataHook={dataHook ? `${dataHook}-tooltip` : undefined}
        >
          <Button
            skin="standard"
            priority={priority}
            size={size}
            fullWidth={fullWidth}
            dataHook={actionItem.dataHook}
            onClick={() => {
              onPopoverClick?.();
              toggle();
            }}
            ellipsis
            prefixIcon={actionItem.prefixIcon}
            disabled={actionItem.disabled}
            suffixIcon={<ChevronDown />}
          >
            {actionItem.label}
          </Button>
        </DisabledTooltip>
      )}
    >
      {allActions}
    </PopoverMenu>
  );
}
