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

export const getOption = (label: string) => {
    const element = screen.getByText(label!, {
        selector: '.SuiteListView .SuiteListView-option-label',
    });

    return element.closest('.SuiteListView-option')!;
};

export const queryOption = (label: string): HTMLElement | null => {
    const element = screen.queryByText(label, {
        selector: '.SuiteListView .SuiteListView-option-label',
    });

    return element?.closest('.SuiteListView-option') || null;
};

export const getInput = (testId = 'SuiteSelect') => {
    const suiteSelect = screen.getByTestId(testId);
    return within(suiteSelect).getByRole('combobox', {
        hidden: true,
    }) as HTMLInputElement;
};

export const openSelect = async (testId = 'SuiteSelect') => {
    const select = screen.getByTestId(testId);
    const input = getInput(testId);
    userEvent.click(input);
    await screen.findByTestId('SuiteListView');
    return select;
};

export const selectOption = (label: string) => {
    const row = getOption(label);
    userEvent.click(row);
    return row;
};

export const getInputDisplayValue = (testId = 'SuiteSelect') => {
    const suiteSelect = screen.getByTestId(testId);
    return within(suiteSelect)
        .getByTestId('SuiteSelectInput')
        .querySelector('.TruncatedText-inner')?.textContent;
};

export const clearSelectedValue = (testId = 'SuiteSelect') => {
    const suiteSelect = screen.getByTestId(testId);
    const clearButton = within(suiteSelect).getByTestId(
        'SuiteListViewClearButton'
    );
    userEvent.click(clearButton);
};

export const searchSelectOptions = async (
    searchTerm: string,
    firstLabel: string,
    testId = 'SuiteSelect'
) => {
    const suiteSelect = screen.getByTestId(testId);
    const filterInput = within(suiteSelect).getByTestId(
        'SuiteListViewFilterInput'
    );

    if (filterInput) userEvent.type(filterInput, searchTerm);

    await waitFor(
        () => {
            const newOption = screen.getByText(firstLabel, {
                selector: '.SuiteListView-option-label',
            });
            expect(newOption).toBeInTheDocument();
        },
        { timeout: 1000 }
    );
};
