import React from 'react';
import withRouter from './withRouter';
import { themes as sbTheme } from '@storybook/theming';
import SplunkThemeProvider from '@splunk/themes/SplunkThemeProvider';

export const parameters = {
    docs: {
        theme: sbTheme.dark,
        inlineStories: false,
        iframeHeight: 500,
    },
    controls: {
        sort: 'requiredFirst',
        expanded: true,
    },
    options: {
        storySort: {
            includeNames: true,
            order: ['Overview', 'Changelog', 'Visualizations', ['Overview', 'Features', 'Scale Tests']],
        },
    },
};

export const globalTypes = {
    theme: {
        name: 'Theme',
        description: 'Global theme for components',
        defaultValue: 'dark',
        toolbar: {
            icon: 'circlehollow',
            // Array of plain string values or MenuItem shape (see below)
            items: ['light', 'dark'],
            // Property that specifies if the name of the item will be displayed
            showName: true,
            // Change title based on selected value
            dynamicTitle: true,
        },
    },
};

// themes for screenshot testing within the ThemesProvider
const themesForScreenshotTests = ['dark', 'light'];

// Only has to respond to colorScheme change and not themeFamily aware as of now.
const themeIdToVariant = {
    light: { colorScheme: 'light' },
    dark: { colorScheme: 'dark' },
};

const ThemesProvider = ({ children }) => {
    // if screenshot testing return the same component wrapped in all the themes in the themesForScreenshotTests array
    const stories = themesForScreenshotTests.map(themeID => {
        return (
            <SplunkThemeProvider key={themeID} {...themeIdToVariant[themeID]}>
                <div style={{ backgroundColor: themeID === 'light' ? 'white' : 'black' }}>{children}</div>
            </SplunkThemeProvider>
        );
    });
    return <>{stories}</>;
};

const withThemeProvider = (Story, context) => {
    if (navigator.webdriver) {
        return <ThemesProvider>{Story()}</ThemesProvider>;
    }
    const theme = context?.globals?.theme;

    return (
        <SplunkThemeProvider colorScheme={theme}>
            <div style={{ backgroundColor: theme === 'light' ? 'white' : 'black' }}>
                <Story {...context} />
            </div>
        </SplunkThemeProvider>
    );
};

export const decorators = [withThemeProvider, withRouter()];
