import React, { ReactElement } from 'react';
import { fireEvent, waitFor } from '@testing-library/react';
import { act } from 'react-dom/test-utils';
import renderWithTheme from '../../../testUtils/renderWithTheme';

import Dropdown from '..';
import Menu from '../../Menu';
import Button from '../../Button';

const DropdownButton = (): ReactElement => {
  const [open, setOpen] = React.useState<boolean>(false);
  const content = (
    <Menu>
      <Menu.Item text="Item 1" />
      <Menu.Item text="Item 2" disabled />
    </Menu>
  );
  return (
    <Dropdown
      open={open}
      content={content}
      target={<Button text="Click me!" onClick={(): void => setOpen(!open)} />}
      onClose={(): void => setOpen(false)}
    />
  );
};

describe('rendering', () => {
  it('hide dropdown content at first', async () => {
    const { queryByText } = renderWithTheme(<DropdownButton />);

    await waitFor(() => {
      expect(queryByText('Click me!')).toBeInTheDocument();
      expect(queryByText('Item 1')).not.toBeInTheDocument();
      expect(queryByText('Item 2')).not.toBeInTheDocument();
    });
  });
});

describe('interaction', () => {
  it('allows to toggle dropdown content', async () => {
    const { queryByText, getByText } = renderWithTheme(<DropdownButton />);

    expect(queryByText('Item 1')).not.toBeInTheDocument();
    expect(queryByText('Item 2')).not.toBeInTheDocument();

    await act(async () => {
      fireEvent.click(getByText('Click me!'));
    });

    expect(queryByText('Item 1')).toBeInTheDocument();
    expect(queryByText('Item 2')).toBeInTheDocument();

    await act(async () => {
      fireEvent.click(getByText('Click me!'));
    });

    expect(queryByText('Item 1')).not.toBeInTheDocument();
    expect(queryByText('Item 2')).not.toBeInTheDocument();
  });
});
