import React, { ReactElement, MouseEvent, useState, useCallback } from 'react';
import css from '../../../utils/css';
import { IconName } from '../../Icon';

import { CommonProps } from '../../common';
import Button from '../../Button';
import Menu from '../../Menu';
import Dropdown from '../../Dropdown';
import assert from '../../../utils/assert';
import Divider from '../../Divider';

interface RowActionProps extends CommonProps {
  /**
   * List of actions to be shown in the action menu, it contains at least 1 actions.
   * */
  actions: {
    divider?: 'top' | 'bottom';
    icon?: IconName;
    intent?: 'text' | 'danger';
    onClick?: (e: MouseEvent) => void;
    text: string;
  }[];
}

const RowAction = ({
  actions,
  id,
  className,
  style,
  sx = {},
  'data-test-id': dataTestId,
}: RowActionProps): ReactElement => {
  assert(actions.length > 0, `[RowAction] Need at least 1 action to render`);

  const [open, setOpen] = useState(false);
  const closeDropdown = useCallback(() => {
    setOpen(false);
  }, [setOpen]);

  if (actions.length === 1 && actions[0] !== undefined) {
    return (
      <Button
        onClick={actions[0].onClick}
        icon={actions[0].icon}
        text={actions[0].text}
        variant="text"
        className={className}
        style={{ ...style, padding: 0 }}
        data-test-id={dataTestId}
        id={id}
      />
    );
  }

  const dropdownContent = (
    <Menu>
      {actions.map((action, index) => {
        return (
          <>
            {action.divider === 'top' && <Divider data-test-id="divider-top" />}
            <Menu.Item
              key={index} // eslint-disable-line react/no-array-index-key
              icon={action.icon}
              text={action.text}
              onClick={action.onClick}
              intent={action.intent}
            />
            {action.divider === 'bottom' && (
              <Divider data-test-id="divider-bottom" />
            )}
          </>
        );
      })}
    </Menu>
  );

  return (
    <Dropdown
      target={
        <Button.Icon
          icon="more-horizontal"
          intent="primary"
          onClick={() => setOpen(!open)}
          data-test-id="three-dot-button"
        />
      }
      content={dropdownContent}
      open={open}
      onClose={closeDropdown}
      className={className}
      style={{ ...style, ...css(sx) }}
      data-test-id={dataTestId}
      id={id}
    />
  );
};

export default RowAction;
