import type { UseCallbackStateReturnType, UseCallbackStateSetter } from 'mixlea-hooks-react';
import { useCallbackState, useMemoFn } from 'mixlea-hooks-react';
import type { PropsWithChildren } from 'react';
import { createContext, useContext } from 'react';
import type { MlModalStatusEnum } from '../types';

// State
const StateContext = createContext<UseCallbackStateReturnType<MlModalStatusEnum>>([
  'inactive',
  () => Promise.resolve('inactive'),
]);

function StateProvider({ children }: PropsWithChildren) {
  const callbackState = useCallbackState<MlModalStatusEnum>('inactive');

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

// SetState
const SetStateContext = createContext<UseCallbackStateSetter<MlModalStatusEnum>>(() => Promise.resolve('inactive'));

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

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

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

// Hooks
const useStatusState = () => {
  const [animationStatus] = useContext<UseCallbackStateReturnType<MlModalStatusEnum>>(StateContext);

  return animationStatus;
};

const useSetStatus = () => {
  const setStatus = useContext(SetStateContext);

  return setStatus;
};

const useSetStatusInactivating = () => {
  const setState = useContext(SetStateContext);

  const setStatusOut = useMemoFn(() => {
    setState('inactivating');
  });

  return setStatusOut;
};

export { StatusProvider, useStatusState, useSetStatus, useSetStatusInactivating };
