import React, { useReducer, useMemo } from "react";
import PropTypes from "prop-types";
import { ThemeProvider as MuiThemeProvider } from "@mui/material/styles";
import { localStorage } from "@flare/utiliyo";
import { getThemes } from "../units/themes";
import { ApplicationThemeContext } from "./contexts";
import { COLOR_SCHEME } from "../constants";

const LOCAL_STORAGE_COLOR_SCHEME_KEY = "network-resurrector-color-scheme";

const colorScheme = localStorage.getItem(LOCAL_STORAGE_COLOR_SCHEME_KEY);
const prefersDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches;

const initialState = {
  scheme: colorScheme ?? (prefersDarkMode ? COLOR_SCHEME.DARK : COLOR_SCHEME.LIGHT)
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "onColorSchemeChanged": {
      return {
        ...state,
        scheme: action.scheme
      };
    }
    default: {
      return state;
    }
  }
};

const dispatchActions = dispatch => ({
  onColorSchemeChanged: scheme => {
    dispatch({ type: "onColorSchemeChanged", scheme });
    localStorage.setItem(LOCAL_STORAGE_COLOR_SCHEME_KEY, scheme);
  }
});

const ThemeProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  const actions = useMemo(() => dispatchActions(dispatch), [dispatch]);
  const themes = useMemo(() => getThemes(state.scheme === COLOR_SCHEME.DARK), [state.scheme]);

  return (
    <ApplicationThemeContext.Provider
      value={{
        state,
        actions
      }}
    >
      <MuiThemeProvider theme={themes.default}>{children}</MuiThemeProvider>
    </ApplicationThemeContext.Provider>
  );
};

ThemeProvider.propTypes = {
  children: PropTypes.node.isRequired
};

export { ThemeProvider };
export default ThemeProvider;
