import * as React from "react";
import {
  createContext,
  useContext,
  useEffect,
  useState,
} from "@theia/core/shared/react";
import {
  IStorjWidgetContext,
  IStorjWidgetProvider,
} from "./StorjWidget.interface";
import { EScreenView, LocalStorageKey, RCloneActions } from "../../constants";

const StorjWidgetContext = createContext({} as IStorjWidgetContext);

export function StorjWidgetProvider({ children }: IStorjWidgetProvider) {
  const [currentScreen, setCurrentScreen] = useState<EScreenView>(
    EScreenView.ACCESS_GRANT_SCREEN
  );
  const [selectedAction, setSelectedAction] = useState<
    RCloneActions | undefined
  >();
  useEffect(() => {
    localStorage.removeItem(LocalStorageKey.SCREEN_HISTORY);
  }, []);
  useEffect(() => {
    saveScreenHistoryToStorage(currentScreen);
  }, [currentScreen]);

  const saveScreenHistoryToStorage = (screen: EScreenView) => {
    let screenHistory = localStorage.getItem(LocalStorageKey.SCREEN_HISTORY);
    if (screenHistory) {
      const screenHistoryParsed = JSON.parse(screenHistory);
      screenHistoryParsed.push(screen);
      screenHistory = JSON.stringify(screenHistoryParsed);
    } else {
      screenHistory = JSON.stringify([screen]);
    }
    localStorage.setItem(LocalStorageKey.SCREEN_HISTORY, screenHistory);
  };

  const setPreviousScreen = () => {
    const screenHistory = localStorage.getItem(LocalStorageKey.SCREEN_HISTORY);
    let screenHistoryArr = [];
    if (screenHistory) {
      screenHistoryArr = JSON.parse(screenHistory);
    }
    screenHistoryArr.pop();
    const lastScreenIndex: number = screenHistoryArr.pop();
    // @ts-ignore
    const prevScreen = EScreenView[EScreenView[lastScreenIndex]];
    localStorage.setItem(
      LocalStorageKey.SCREEN_HISTORY,
      JSON.stringify(screenHistoryArr)
    );
    setCurrentScreen(prevScreen);
  };

  const initialState: IStorjWidgetContext = {
    currentScreen,
    setCurrentScreen,
    setPreviousScreen,
    selectedAction,
    setSelectedAction,
  };

  return (
    <StorjWidgetContext.Provider value={initialState}>
      {children}
    </StorjWidgetContext.Provider>
  );
}

export const useStorjWidgetContext = () => useContext(StorjWidgetContext);
