import { Theme, createTheme } from '@mui/material';
import { FC, PropsWithChildren, createContext, useContext, useMemo, useState } from 'react';

interface IThemeContext {
  theme?: Theme;
  title?: string;
  setTheme?: (theme: 'Default') => void;
}

export const ThemeContext = createContext<IThemeContext>({});

export const useTheme = () => {
  const { theme, title, setTheme } = useContext(ThemeContext);

  if (theme !== undefined && title !== undefined && setTheme) return { theme, title, setTheme };
  else throw new Error("Couldn't find context. Is your component inside a ThemeProvider?");
};

const ThemeProvider: FC<PropsWithChildren> = ({ children }) => {
  const theme_default = useMemo(
    () =>
      createTheme({
        palette: {
          primary: {
            main: getComputedStyle(document.documentElement).getPropertyValue('--enabledBackGroundColor').trim(),
            contrastText: '#fff',
          },
          secondary: {
            main: getComputedStyle(document.documentElement)
              .getPropertyValue('--backgroundColorContrastedPanel')
              .trim(),
          },
        },
        screenHeight: Number(getComputedStyle(document.documentElement).getPropertyValue('--screenHeight').trim()),
      }),
    []
  );

  const [title, setTitle] = useState('MSFS');
  const [theme, setTheme] = useState<IThemeContext['theme']>(theme_default);

  const _setTheme: IThemeContext['setTheme'] = (_theme) => {
    switch (_theme) {
      case 'Default':
        setTitle('Default');
        setTheme(theme_default);
        break;
    }
  };

  return <ThemeContext.Provider value={{ theme, title, setTheme: _setTheme }}>{children}</ThemeContext.Provider>;
};

export default ThemeProvider;
