import React, { MouseEvent, ReactElement } from 'react';
import css from '../../../utils/css';

import { CommonProps } from '../../common';
import { IconName } from '../../Icon';
import { Wrapper } from './Styled';
import Button from '../../Button';
import assert from '../../../utils/assert';
import theme from '../../../theme';

type ButtonConfig = {
  icon?: IconName;
  onClick?: (e: MouseEvent) => void;
  role?: 'primary' | 'secondary';
  text: string;
};

interface ActionButtonsProps extends CommonProps {
  /**
   * List of action buttons to be shown, default role is secondary.
   * */
  buttons: {
    icon?: IconName;
    onClick?: (e: MouseEvent) => void;
    role?: 'primary' | 'secondary';
    text: string;
  }[];
}

export const variantByRole = (
  role: 'primary' | 'secondary'
): 'filled' | 'outlined' => {
  return ({
    primary: 'filled',
    secondary: 'outlined',
  } as const)[role];
};

const isPrimary = (button: ButtonConfig): boolean => button.role === 'primary';

const ActionButtons = ({
  buttons,
  id,
  className,
  style,
  sx = {},
  'data-test-id': dataTestId,
}: ActionButtonsProps): ReactElement => {
  assert(
    buttons.length > 0,
    `[ActionButtons] Need at least 1 button to render`
  );
  assert(
    buttons.length <= 4,
    `[ActionButtons] Maximum 4 buttons could be rendered`
  );
  assert(
    buttons.filter(isPrimary).length === 1,
    `[ActionButtons] Need to have exactly 1 primary button`
  );

  return (
    <Wrapper
      id={id}
      className={className}
      style={{ ...style, ...css(sx) }}
      data-test-id={dataTestId}
    >
      {buttons.map(({ role = 'secondary', icon, text, onClick }, index) => (
        <Button
          key={index} // eslint-disable-line react/no-array-index-key
          icon={icon}
          text={text}
          onClick={onClick}
          variant={variantByRole(role)}
          style={{ marginRight: theme.space.medium }}
        />
      ))}
    </Wrapper>
  );
};

export default ActionButtons;
