import React, { useContext } from 'react';
import { fireEvent, render, waitFor } from '@testing-library/react';
import { BRAND_ORCHARD } from '@theorchard/constants';
import { themeAwal } from '../../themes/themeAwal';
import ThemeContext from '../themeContext';
import ThemeProvider from '../themeProvider';

describe('<ThemeProvider>', () => {
    const ChildComponent = () => {
        const { theme, setTheme } = useContext(ThemeContext);

        return (
            <button type="button" onClick={() => setTheme('awal')}>
                theme-{theme}
            </button>
        );
    };

    const envConfig = {
        appName: 'frontend-example',
        brand: BRAND_ORCHARD,
        cdnUrl: 'https://qa-cdn.theorchard.io',
    };

    const renderComponent = (env = envConfig) =>
        render(
            <ThemeProvider config={env}>
                <ChildComponent />
            </ThemeProvider>
        );

    test('renders children with theme context', () => {
        const { getByText } = renderComponent();

        const buttonElement = getByText('theme-orchard');

        expect(buttonElement).toBeInTheDocument();
    });

    test('updates context when "setTheme" is called', () => {
        const { getByText } = renderComponent();

        let buttonElement = getByText('theme-orchard');

        fireEvent.click(buttonElement);

        buttonElement = getByText('theme-awal');

        expect(buttonElement).toBeInTheDocument();
    });

    test('updates :root style when "theme" changes', async () => {
        const { getByText } = renderComponent();

        const rootElement = document.querySelector<HTMLElement>(':root')!;
        const buttonElement = getByText('theme-orchard');

        const orchardIconColor = rootElement.style.getPropertyValue('--app-icon-gradient-color-0');

        expect(orchardIconColor).not.toEqual(themeAwal.colors['app-icon-gradient-color-0']);

        fireEvent.click(buttonElement);

        await waitFor(() => {
            const awalIconColor = rootElement.style.getPropertyValue('--app-icon-gradient-color-0');

            expect(awalIconColor).toEqual(themeAwal.colors['app-icon-gradient-color-0']);
        });
    });
});
