import React from 'react';
import { fireEvent } from '@testing-library/react';
import { renderInAppContext } from '@theorchard/suite-testing';
import Dropdown, { CLASSNAME, DropdownProps } from '../dropdown';

describe('<Dropdown>', () => {
    const name = 'dropdown';
    const item = { label: 'Option1', value: '1' };
    const options = [
        item,
        { label: 'Option2', value: '2' },
    ];
    const render = (props?: Partial<DropdownProps<object>>) =>
        renderInAppContext(<Dropdown name={name} options={options} {...props} />);

    test('renders dropdown with items', () => {
        const { container, getByText } = render();
        const input = container.getElementsByTagName('input').item(0);

        if (input)
            fireEvent.mouseDown(input);

        options.forEach(option => expect(getByText(option.label)).toBeVisible());
    });

    test('renders placeholder', () => {
        const placeholder = 'PLACEHOLDER TEXT';
        const { getByText } = render({ placeholder, options: [] });

        expect(getByText(placeholder)).toBeVisible();
    });

    test('renders classname', () => {
        const { container } = render({ className: CLASSNAME, options: [] });

        expect(container.getElementsByClassName(CLASSNAME).item(0)).toBeVisible();
    });

    test('renders dropdown with plain value set', () => {
        const { getByText } = render({ value: item.value });

        expect(getByText(item.label)).toBeVisible();
    });

    test('renders dropdown with complex value set', () => {
        const { getByText } = render({ value: item, isPlainValue: false });

        expect(getByText(item.label)).toBeVisible();
    });

    test('invokes callback when item selected', () => {
        const onChange = jest.fn();

        const { container, getByText } = render({ onChange, options: [item] });
        const input = container.getElementsByTagName('input').item(0);

        if (input)
            fireEvent.mouseDown(input);
        getByText(item.label).click();

        expect(onChange).toHaveBeenCalledWith(name, item.value, undefined);
    });

    test('cannot select item if DropdownOption.disabled is true', () => {
        const onChange = jest.fn();
        const itemDisabled = {
            label: 'Option1', value: '1', disabled: true
        };

        const { container, getByText } = render({ onChange, options: [itemDisabled] });
        const input = container.getElementsByTagName('input').item(0);

        if (input)
            fireEvent.mouseDown(input);
        getByText(item.label).click();

        expect(getByText('Option1')).toBeVisible();
        expect(onChange).not.toHaveBeenCalledWith(name, item.value, undefined);
    });
});
