// @flow
import React, { useState, useEffect, type Node } from 'react';
import type { StoryDecorator } from '@storybook/react';
import { addons } from '@storybook/addons';
import { THEME_CHANGED } from './constants';
import { PatchworkThemeProvider, themes } from '../../../..';

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

  useEffect(() => {
    const channel = addons.getChannel();
    channel.on(THEME_CHANGED, setTheme);
    return () => channel.removeListener(THEME_CHANGED, setTheme);
  }, []);

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

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