import React from 'react';
import { LazyQueryResult } from '@apollo/client';
import { fireEvent } from '@testing-library/react';
import * as suiteFrontend from '@theorchard/suite-frontend';
import { renderInAppContext } from '@theorchard/suite-testing';
import SoundRecordingSearch, { getOptionName } from '../soundRecordingSearch';

jest.mock('@theorchard/suite-frontend', () => ({
    ...jest.requireActual('@theorchard/suite-frontend'),
    useAbortableQuery: jest.fn()
}));

describe('<SoundRecordingSearch>', () => {
    const onChange = jest.fn();
    const renderComponent = () => renderInAppContext(
        <SoundRecordingSearch
            onChange={onChange}
        />
    );

    const optionOne = {
        id: '1234',
        imprint: 'Label1',
        isrc: 'ISRC1',
        name: 'SoundRecording1',
        participants: [{ id: '1', name: 'Artist A' }]
    };
    const optionTwo = {
        id: '4321',
        imprint: 'Label2',
        isrc: 'ISRC2',
        name: 'SoundRecording2',
        participants: []
    };
    const queryData = {
        items: [{ item: optionOne }, { item: optionTwo }]
    };

    const spotifyData = {
        items: [{ id: '123', name: 'Name', artists: [], externalIds: { isrc: '4u2185y925' } }]
    };

    const mockQuery = () =>
        jest.spyOn(suiteFrontend, 'useAbortableQuery').mockReturnValue([
            jest.fn(),
            {
                data: { globalSoundRecordingSearchES: queryData, spotifyTrackSearch: spotifyData },
                loading: false
            } as LazyQueryResult<unknown, unknown>,
        ]);

    test('calls onChange if item changed', () => {
        mockQuery();
        const { container, getByText } = renderComponent();
        const input = container.querySelector('input');

        if (input)
            fireEvent.change(input, { target: { value: 'SoundRecording2' } });
        fireEvent.click(getByText(getOptionName(optionTwo)));

        expect(onChange).toHaveBeenCalledWith({
            id: '4321',
            imprint: 'Label2',
            isrc: 'ISRC2',
            name: 'SoundRecording2',
            participants: [],
            source: 'The Orchard'
        });
    });

    test('filters items based on search term', () => {
        mockQuery();
        const { container, queryByText } = renderComponent();
        const input = container.querySelector('input');

        if (input)
            fireEvent.change(input, { target: { value: 'SoundRecording2' } });

        const firstOption = queryByText(getOptionName(optionOne));
        const secondOption = queryByText(getOptionName(optionTwo));

        expect(firstOption).toBeNull();
        expect(secondOption).toBeVisible();
    });
});
