import { render, userEvent, screen, within, mockMatchMedia } from '../test-utils';
import { composeStories } from '@storybook/react';
import * as stories from './SelectOption.story';
import { Breakpoint } from '../common';
import { wait } from '../test-utils/wait';

const { Basic: SelectOptionExample } = composeStories(stories);

mockMatchMedia();

describe('Select Option', () => {
  it('opens dropdown on desktop view', async () => {
    render(<SelectOptionExample />);

    let dialog = screen.queryByRole('dialog');
    expect(dialog).not.toBeInTheDocument();

    const button = screen.getByRole('button');

    await userEvent.click(button);

    dialog = screen.queryByRole('dialog');
    expect(dialog).toBeInTheDocument();
  });

  it('opens bottom sheet on mobile view', async () => {
    // mock mobile view
    window.innerWidth = Breakpoint.EXTRA_SMALL;

    render(<SelectOptionExample />);

    let dialog = screen.queryByRole('dialog');
    expect(dialog).not.toBeInTheDocument();

    const button = screen.getByRole('button');

    await userEvent.click(button);

    dialog = screen.queryByRole('dialog');
    expect(dialog).toBeInTheDocument();
  });

  it('shows options', async () => {
    render(<SelectOptionExample />);

    const button = screen.getByRole('button');

    await userEvent.click(button);

    const dialog = screen.getByRole('dialog');
    const sectionHeaders = within(dialog).getAllByRole('heading', { name: /balances|jars/i });
    expect(sectionHeaders).toHaveLength(2);

    const options = within(dialog).getAllByRole('heading', { level: 4 });
    expect(options).toHaveLength(5);
  });

  it('choose option', async () => {
    // mock mobile view
    window.innerWidth = Breakpoint.EXTRA_SMALL;

    render(
      <SelectOptionExample placeholder={{ title: 'Please choose balance', actionLabel: 'Pick' }} />,
    );

    const button = screen.getByRole('button');

    expect(button).toHaveTextContent('Pick');
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
    await userEvent.click(button);
    expect(screen.getByRole('dialog')).toBeInTheDocument();

    const pickedOption = within(screen.getByRole('dialog')).getByText('Trip to Mars');

    await userEvent.click(pickedOption);

    // wait for dialog to close
    await wait(500);
    expect(screen.getByText('Trip to Mars')).toBeInTheDocument();
    expect(screen.queryAllByTestId('chevron-down-icon')).toHaveLength(1);
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
  });
});
