import { useSingleStatePersist } from "@deuna/checkout-core/packages/helpers/useSingleState";
import { PropsWithChildren, createContext, useContext, useMemo } from "react";

import { AppContextProps, AppProviderProps, AppState } from "./interfaces";
import { defaultContextValue, defaultState } from "./defaultState";

export const AppContext = createContext<AppContextProps>(defaultContextValue);

export const AppProvider = (props: PropsWithChildren<AppProviderProps>) => {
  const { state, setState, purgeStorage } = useSingleStatePersist<AppState>(
    defaultState,
    "VaultWidget",
    []
  );

  const store = useMemo<AppContextProps>(
    () => ({
      isModuleActive: true,
      state,
      setState,
      purgeStorage,
    }),
    [state, setState, purgeStorage]
  );

  return (
    <AppContext.Provider value={store}>{props.children}</AppContext.Provider>
  );
};

export const useAppContext = () => useContext(AppContext);
