import type { UseCallbackStateReturnType, UseCallbackStateSetter } from 'mixlea-hooks-react';
import { useCallbackState } from 'mixlea-hooks-react';
import type { PropsWithChildren } from 'react';
import { createContext, useContext } from 'react';

// State
const StateContext = createContext<UseCallbackStateReturnType<any>>([undefined, () => Promise.resolve(undefined)]);

function StateProvider({ children }: PropsWithChildren) {
  const callbackState = useCallbackState<any>(undefined);

  return <StateContext.Provider value={callbackState}>{children}</StateContext.Provider>;
}

// SetState
const SetStateContext = createContext<UseCallbackStateSetter<any>>(() => Promise.resolve(undefined));

function SetStateProvider({ children }: PropsWithChildren) {
  const [, setState] = useContext(StateContext);

  return <SetStateContext.Provider value={setState}>{children}</SetStateContext.Provider>;
}

// Provider
function LoaderDataProvider({ children }: PropsWithChildren) {
  return (
    <StateProvider>
      <SetStateProvider>{children}</SetStateProvider>
    </StateProvider>
  );
}

// Hooks
const useLoaderDataState = () => {
  const [loaderData] = useContext(StateContext);

  return loaderData;
};

const useSetLoaderData = () => {
  const setLoaderData = useContext(SetStateContext);

  return setLoaderData;
};

export { LoaderDataProvider, useLoaderDataState, useSetLoaderData };
