import { useEffect } from 'react';
import { Global, css } from '@emotion/react';
import { CssBaseline, Breakpoint, type PaletteMode, type PaletteOptions } from '@mui/material';
import { TypographyStyleOptions } from '@mui/material/styles/createTypography';

import { createTheme, ThemeProvider } from '../Theme';

function withTheme<P extends object>(
  Component: React.ComponentType<P>,
  {
    mode = 'light',
    pageWidth = 'md',
    palette,
    typography,
  }: { mode?: PaletteMode; pageWidth?: Breakpoint; palette?: PaletteOptions; typography?: TypographyStyleOptions } = {}
) {
  // @ts-expect-error
  const theme = createTheme({ mode, pageWidth, palette, typography });

  const color = theme.typography.color.main;
  const globalStyles = css`
    font-family: ${theme.typography.fontFamily};
    color: ${color};

    a,
    a:hover,
    a:active {
      text-decoration: none;
      color: ${theme.palette.primary.dark};
    }

    a:hover {
      color: ${theme.palette.primary.main};
    }

    .section--latest-post {
      p:last-of-type {
        margin: 0;
      }
    }

    .has-scrolled {
      .section--footnotes {
        position: static !important;
        transition-property: background-color;
        transition-duration: 600ms;
        transition-timing-function: ease;
        .footnote__title {
          color: #fff;
        }
      }
    }
  `;

  return function WithTheme(props: P) {
    useEffect(() => {
      const jssStyles = document.querySelector('#jss-server-side');
      if (jssStyles && jssStyles.parentNode) {
        jssStyles.parentNode.removeChild(jssStyles);
      }
    }, []);
    return (
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <Global styles={globalStyles} />
        <Component {...props} />
      </ThemeProvider>
    );
  };
}

export default withTheme;
