import React, { memo, useReducer } from 'react';
import type { ReactNode } from 'react';
import { PortalHost } from './PortalHost';
import { reducer } from './reducer';
import { INITIAL_STATE } from './constants';
import { PortalDispatchContext, PortalStateContext } from './contexts';

export interface PortalProviderProps {
  /*
   * The name of the root host
   */
  rootHostName?: string;
  /*
   * The children to render
   */
  children: ReactNode | ReactNode[];
}

const PortalProviderComponent = ({
  rootHostName = 'root',
  children,
}: PortalProviderProps) => {
  const [state, dispatch] = useReducer(reducer, INITIAL_STATE);
  return (
    <PortalDispatchContext.Provider value={dispatch}>
      <PortalStateContext.Provider value={state}>
        {children}
        <PortalHost name={rootHostName} />
      </PortalStateContext.Provider>
    </PortalDispatchContext.Provider>
  );
};

export const PortalProvider = memo(PortalProviderComponent);
PortalProvider.displayName = 'PortalProvider';
