import React, { useCallback } from "react";

type HookModalState = {
  path: string;
  screenData: HookPluginProps;
};

export type HookModalContextT = {
  isHooksExecutionInProgress: boolean;
  setIsHooksExecutionInProgress: (hookExecutionState?: boolean) => void;
  isRunningInBackground: boolean;
  isPresentationFullScreen: boolean;
  setIsRunningInBackground: (hookBackgroundProcessState?: boolean) => void;
  setIsPresentingFullScreen: (hookBackgroundProcessState?: boolean) => void;
  state: HookModalState;
  setState: (state: HookModalState) => void;
  resetState: () => void;
};

const initialState = {
  path: null,
  screenData: null,
};

type HookPresentationMode = "background" | "fullScreen";

const ReactContext = React.createContext<HookModalContextT>({
  isHooksExecutionInProgress: false,
  setIsHooksExecutionInProgress: () => {},
  isRunningInBackground: null,
  setIsRunningInBackground: () => {},
  setIsPresentingFullScreen: () => {},
  isPresentationFullScreen: null,
  state: initialState,
  setState: () => null,
  resetState: () => null,
});

const Provider = ({ children }: { children: React.ReactNode }) => {
  const [state, setState] = React.useState<HookModalState>(initialState);

  const [hookPresentationMode, setHookPresentationMode] =
    React.useState<HookPresentationMode>(null);

  const resetState = useCallback(() => {
    setState(initialState);
  }, [setState]);

  const [isHooksExecutionInProgress, setIsHooksExecutionInProgress] =
    React.useState(false);

  const setIsRunningInBackground = () => {
    setHookPresentationMode("background");
  };

  const setIsPresentingFullScreen = () => {
    setHookPresentationMode("fullScreen");
  };

  return (
    <ReactContext.Provider
      value={{
        isRunningInBackground: hookPresentationMode === "background",
        setIsRunningInBackground,
        setIsPresentingFullScreen,
        isPresentationFullScreen: hookPresentationMode === "fullScreen",
        isHooksExecutionInProgress,
        setIsHooksExecutionInProgress,
        state,
        setState,
        resetState,
      }}
    >
      {children}
    </ReactContext.Provider>
  );
};

const withProvider = (Component) => {
  const WithProvider = (props) => {
    return (
      <Provider>
        <Component {...props} />
      </Provider>
    );
  };

  return WithProvider;
};

export const ZappHookModalContext = { withProvider, ReactContext };
