import { ReactElement } from 'react';

import { GlobalStyles, ThemeProvider, createTheme } from '@mui/material';

import useDarkMode from '../../hooks/useDarkTheme';
import { dark } from '../../themes/dark';
import { light } from '../../themes/light';

const reducePalette =
  prefix =>
  (accu, [key, value]) => {
    if (value instanceof Object) {
      return {
        ...accu,
        ...Object.entries(value).reduce(reducePalette(`${prefix}-${key}`), {})
      };
    } else {
      accu[`${prefix}-${key}`] = value;
    }
    return accu;
  };

export const ThemeListener = (props: { children: ReactElement }) => {
  const { children } = props;
  const darkMode = useDarkMode();
  const theme = createTheme(darkMode ? dark : light);

  const cssVariables = ({ theme: { palette } }) => {
    const muiVariables = Object.entries(palette).reduce(reducePalette('--cfe'), {});
    return {
      '@global': {
        ':root': {
          ...muiVariables
        }
      }
    };
  };
  const globalCssVars = cssVariables({ theme })['@global'];

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyles styles={globalCssVars} />
      <div className="mui-root" style={{ display: 'contents' }}>
        {children}
      </div>
    </ThemeProvider>
  );
};
