import React, { useState } from 'react';
import { MantineProvider } from 'tidbcloud-uikit/components';
import { useMutationObserver } from 'ahooks';
import {
  Colors,
  DarkColors,
  darkThemeColors,
  themeColors,
} from 'tidbcloud-uikit/theme';
import { WidgetModelContext } from './model';

export function withModelContext(Component: (props: any) => JSX.Element) {
  return (props: any) => {
    const [dark, setDark] = useState(
      () => document.body.dataset.jpThemeLight === 'false'
    );
    useMutationObserver(
      (mutationsList) => {
        mutationsList.forEach((i) => {
          if (i.attributeName === 'data-jp-theme-light') {
            setDark(document.body.dataset.jpThemeLight === 'false');
          }
        });
      },
      document.body,
      {
        attributes: true,
        subtree: false,
      }
    );

    return (
      <WidgetModelContext.Provider value={props.model}>
        <MantineProvider
          theme={{
            colorScheme: dark ? 'dark' : 'light',
            colors: dark ? darkThemeColors : themeColors,
            other: dark ? DarkColors : Colors,
          }}
          withGlobalStyles={false}
          withNormalizeCSS={false}
        >
          <Component {...props} />
        </MantineProvider>
      </WidgetModelContext.Provider>
    );
  };
}
