import React from 'react';
import { fireEvent } from '@testing-library/react';

import renderWithTheme from '../../../../testUtils/renderWithTheme';
import BulkActions from '../index';

describe('BulkActions', () => {
  it('renders correctly', () => {
    const { getByText } = renderWithTheme(
      <BulkActions
        data={[
          {
            name: 'Tung',
            age: 20,
          },
          {
            name: 'Teng',
            age: 30,
          },
        ]}
        selectedRows={{ 1: true }}
        actions={[]}
      />
    );

    expect(getByText('Selected rows')).toBeVisible();
    expect(getByText('1')).toBeVisible();
  });

  it('shows actions dropdown when click icon', async () => {
    const { queryByText, findByText, getByRole } = renderWithTheme(
      <BulkActions
        data={[]}
        selectedRows={{}}
        actions={[{ text: 'View', onClick: jest.fn() }]}
      />
    );

    expect(queryByText('View')).not.toBeInTheDocument();
    fireEvent.click(getByRole('button'));
    expect(await findByText('View')).toBeInTheDocument();
  });

  it('passes selected data to action click handler', () => {
    const clickHandler = jest.fn();
    const { getByText, getByRole } = renderWithTheme(
      <BulkActions
        data={[
          {
            name: 'Tung',
            age: 20,
          },
          {
            name: 'Teng',
            age: 30,
          },
        ]}
        selectedRows={{ 1: true }}
        actions={[{ text: 'View', onClick: clickHandler }]}
      />
    );

    fireEvent.click(getByRole('button'));
    fireEvent.click(getByText('View'));
    expect(clickHandler).toHaveBeenCalledWith([{ name: 'Teng', age: 30 }]);
  });

  it('renders divider corectly', () => {
    const { getByTestId, queryByTestId, getByRole } = renderWithTheme(
      <BulkActions
        data={[
          {
            name: 'Tung',
            age: 20,
          },
          {
            name: 'Teng',
            age: 30,
          },
        ]}
        selectedRows={{ 1: true }}
        actions={[
          { text: 'View', onClick: jest.fn(), divider: 'bottom' },
          { text: 'Delete', onClick: jest.fn() },
        ]}
      />
    );

    fireEvent.click(getByRole('button'));
    expect(getByTestId('divider-bottom')).toBeInTheDocument();
    expect(queryByTestId('divider-top')).not.toBeInTheDocument();
  });
});
