import React from 'react';
import { act, fireEvent, render as renderDom, screen } from '@testing-library/react';
import SpotifyPlayButton, {
    CLASSNAME,
    Props,
    TERM_PLAY_HINT,
    TEST_CONTENT_ID,
    TEST_ID,
} from '../spotifyPlayButton';
import * as hook from '../useSpotifyPlayer';
import { wait } from './wait';

type HookResult = ReturnType<typeof hook.default>;

describe('<SpotifyPlayButton>', () => {
    const defaultProps: Props = {
        trackIds: ['TRACK_ID'],
    };

    const render = async (props: Partial<Props> = {}) => {
        const wrapper = renderDom(<SpotifyPlayButton {...defaultProps} {...props} />);
        await act(async () => await wait());
        return wrapper;
    };

    const mockHook = (result?: Partial<HookResult>) => {
        jest.spyOn(hook, 'default').mockReturnValue([
            { loaded: true, playing: false, ...result?.[0] },
            result?.[1] || (async () => await Promise.resolve()),
        ]);
    };

    beforeEach(() => {
        mockHook();
    });

    afterEach(() => {
        jest.restoreAllMocks();
    });

    test('renders default component', async () => {
        await render();

        expect(screen.getByTestId(TEST_ID)).toBeInTheDocument();
    });

    test('renders tooltip', async () => {
        await render();

        fireEvent.mouseEnter(screen.getByTestId(TEST_CONTENT_ID));

        expect(await screen.findByText(TERM_PLAY_HINT)).toBeInTheDocument();
    });

    describe('without trackIds', () => {
        test('renders disabled button', async () => {
            const { container } = await render({ trackIds: [] });
            expect(container.querySelector(`.${CLASSNAME}.disabled`)).toBeInTheDocument();
        });
    });
});
