import { IdType } from 'react-table';
import React, { ReactElement, useState } from 'react';
import css from '../../../utils/css';

import { CommonProps } from '../../common';
import { IconName } from '../../Icon';
import { Wrapper } from './Styled';
import Badge from '../../Badge';
import Button from '../../Button';
import Divider from '../../Divider';
import Dropdown from '../../Dropdown';
import Menu from '../../Menu';
import theme from '../../../theme';

interface BulkActionsProps<D extends Record<string, unknown>>
  extends CommonProps {
  /**
   * List of actions
   */
  actions: {
    divider?: 'top' | 'bottom';
    icon?: IconName;
    intent?: 'text' | 'danger';
    onClick: (selectedData: D[]) => void;
    text: string;
  }[];
  /**
   * Table data
   */
  data: D[];
  /**
   * Table selected rows
   */
  selectedRows: Record<IdType<D>, boolean>;
}

const BulkActions = <D extends Record<string, unknown>>({
  data,
  selectedRows,
  actions,
  id,
  className,
  style,
  sx = {},
  'data-test-id': dataTestId,
}: BulkActionsProps<D>): ReactElement => {
  const [open, setOpen] = useState(false);
  const selectedData = data.filter((_, index) => selectedRows[index]);

  return (
    <Wrapper
      id={id}
      className={className}
      data-test-id={dataTestId}
      style={{ ...style, ...css(sx) }}
    >
      <Dropdown
        open={open}
        content={
          <Menu>
            {actions.map(({ text, icon, intent, onClick, divider }, index) => (
              <>
                {divider === 'top' && <Divider data-test-id="divider-top" />}
                <Menu.Item
                  key={index} // eslint-disable-line react/no-array-index-key
                  text={text}
                  icon={icon}
                  intent={intent}
                  onClick={() => onClick(selectedData)}
                />
                {divider === 'bottom' && (
                  <Divider data-test-id="divider-bottom" />
                )}
              </>
            ))}
          </Menu>
        }
        placement="bottom-right"
        target={
          <Button
            variant="text"
            intent="primary"
            text={
              <>
                Selected rows
                <Badge
                  intent="primary"
                  content={selectedData.length}
                  style={{ marginLeft: theme.space.small }}
                />
              </>
            }
            rightIcon="single-down-arrow"
            onClick={() => setOpen(!open)}
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              padding: 0,
            }}
          />
        }
        onClose={() => setOpen(false)}
      />
    </Wrapper>
  );
};

export default BulkActions;
