// @flow
import React, { type Node } from 'react';
import type { StoryDecorator } from '@storybook/react';
import { PatchworkThemeProvider, themes } from '../../../../src';
import { useLocalStorage } from './use-local-storage';

type DynamicThemeProviderProps = { children: Node };
export const DynamicThemeProvider = ({
  children,
}: DynamicThemeProviderProps) => {
  // DEFAULT_THEME_NAME is injected by webpack.
  /* eslint-disable no-undef */
  // $FlowFixMe
  const [theme] = useLocalStorage('theme', themes[DEFAULT_THEME_NAME]);
  /* eslint-enable no-undef */

  return (
    <PatchworkThemeProvider theme={theme}>{children}</PatchworkThemeProvider>
  );
};

export const themeDecorator: StoryDecorator = (story, context) => (
  <DynamicThemeProvider>{story(context)}</DynamicThemeProvider>
);
