import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import { ActionMenu } from './index';

describe('ActionMenu', () => {
  it('renders correctly', () => {
    render(
      <ActionMenu>
        <ActionMenu.Item onSelect={() => {}}>Delete</ActionMenu.Item>
      </ActionMenu>,
    );

    expect(screen.getByLabelText(/more options/i)).toBeInTheDocument();
  });

  it('opens the menu and selects an option when clicking on an action item', async () => {
    const onSelectOption = vi.fn();
    const callbackThatShouldNotBeExecuted = vi.fn();
    const user = userEvent.setup();

    const touchableProps = { onSelect: onSelectOption };
    const touchablePropsThatShouldNotBeCalled = {
      onSelect: callbackThatShouldNotBeExecuted,
      onClick: callbackThatShouldNotBeExecuted,
    };

    render(
      <ActionMenu>
        <ActionMenu.Item {...touchableProps}>Add</ActionMenu.Item>
        <ActionMenu.Item {...touchablePropsThatShouldNotBeCalled}>Delete</ActionMenu.Item>
      </ActionMenu>,
    );

    const triggerButton = screen.getByTestId('action-menu-button') as HTMLButtonElement;
    await user.click(triggerButton);

    // The user should be able to see the dropdown menu
    const dropdownMenu = screen.getByRole('menu');
    expect(dropdownMenu).toBeInTheDocument();

    // The user should be able to see the list of options
    const addOption = screen.getByText(/add/i);
    expect(addOption).toBeInTheDocument();

    // The user can interact with any of the options
    await user.click(addOption);

    // The following expect is failing
    expect(onSelectOption).toBeCalledTimes(1);
    expect(callbackThatShouldNotBeExecuted).toBeCalledTimes(0);
  });
});
