// @flow
import React from 'react';
import styled from 'styled-components';
import { DocsContainer } from '@storybook/addon-docs/blocks';
import { addDecorator, addParameters } from '@storybook/react';
import { themeDecorator } from '../utils/storybook/addons/patchwork-theme/theme.decorator';
import { hyperspeedAnimationsDecorator } from '../utils/storybook/addons/hyperspeed-animations/hyperspeed-animations.decorator';
import { deriveStorybookTheme } from '../utils/storybook/addons/patchwork-theme/storybook.theme';
import { themes } from '../src';
import { intlDecorator } from './intl.decorator';
import { DynamicThemeProvider } from '../utils/storybook/addons/patchwork-theme/theme.decorator';
import {
  Head1,
  Head2,
  Head3,
  Head4,
  Head5,
  Link,
  Span,
  Text,
} from '../src/core/typography';
import { getPaletteColor } from '../src/mixins/branding';

const StyledCode = styled.code`
  background: ${getPaletteColor('info-bg')};
  border-radius: 5px;
  color: ${getPaletteColor('info-fg')};
  display: inline-block;
  font-family: monospace;
  font-size: 16px;
  padding: 0 5px;
`;

let theme;
try {
  theme = JSON.parse(window.localStorage.getItem('theme'));
} catch (e) {
  console.error('Failed to load patchwork theme from local storage');
}

addParameters({
  options: {
    // DEFAULT_THEME_NAME is injected by webpack.
    // $FlowFixMe eslint-disable-next-line
    theme: deriveStorybookTheme(theme ?? themes[DEFAULT_THEME_NAME]),
    storySort: {
      method: 'alphabetical',
      order: [
        'Manual',
        'Design System',
        'Utilities',
        'Components',
        'Organisms',
        'Examples',
      ],
    },
  },
  docs: {
    components: {
      a: Link,
      h1: (props) => <Head1 spacing="mv3" {...props} />,
      h2: (props) => <Head2 spacing="mv3" {...props} />,
      h3: (props) => <Head3 spacing="mv3" {...props} />,
      h4: (props) => <Head4 spacing="mv3" {...props} />,
      h5: (props) => <Head5 spacing="mv3" {...props} />,
      p: (props) => <Text spacing="mv1" {...props} />,
      span: Span,
      li: (props) => (
        <li>
          <Text {...props} />
        </li>
      ),
      inlineCode: StyledCode,
    },
    container: ({ context, children }) => (
      <DocsContainer context={context}>
        <DynamicThemeProvider>{children}</DynamicThemeProvider>
      </DocsContainer>
    ),
    inlineStories: true,
  },
});

addDecorator(themeDecorator);
addDecorator(intlDecorator);
addDecorator(hyperspeedAnimationsDecorator);
