import React, { createContext, useContext, useRef } from 'react';

interface PortalProviderProps {
  children: React.ReactNode;
}

interface PortalState {
  dialogContainerRef: React.RefObject<HTMLDivElement | null>;
  drawerContainerRef: React.RefObject<HTMLDivElement | null>;
}

const PortalContext = createContext<PortalState>(
  null as unknown as PortalState
);

export function PortalProvider({
  children,
}: PortalProviderProps): React.ReactNode {
  const dialogContainerRef = useRef<HTMLDivElement | null>(null);
  const drawerContainerRef = useRef<HTMLDivElement | null>(null);

  return (
    <PortalContext.Provider value={{ dialogContainerRef, drawerContainerRef }}>
      {children}
      <div className="drawer-portal-container" ref={drawerContainerRef} />
      <div className="dialog-portal-container" ref={dialogContainerRef} />
    </PortalContext.Provider>
  );
}

export const usePortalContainer = (): PortalState => {
  try {
    const state = useContext(PortalContext);
    return state;
  } catch (error) {
    throw new Error('PortalProvider not found');
  }
};

export default PortalProvider;
