import React, {useState, useRef, createContext, ReactNode} from 'react';
import {ModalManager, ModalRef} from '@core0/modal';
import {PopoverManager, PopoverRef} from '@core0/popover';
import {PortalManager} from './portal-manager';
import {SnackbarManager, SnackbarRef, Snackbar} from '@core0/snackbar';

interface PortalProps {
    children: ReactNode;
}

export const PortalContext = createContext<PortalManager | null>(null);

export const PortalContextProvider = (props: PortalProps) => {
    const {children} = props;

    const [modalRefList, setModalRefList] = useState<ModalRef[]>([]);
    const [popoverRefList, setPopoverRefList] = useState<PopoverRef[]>([]);
    const [snackbarRefList, setSnackbarRefList] = useState<SnackbarRef[]>([]);

    const portalManager = useRef<PortalManager>({
        modalManager: new ModalManager(modalRefList, setModalRefList),
        popoverManager: new PopoverManager(popoverRefList, setPopoverRefList),
        snackbarManager: new SnackbarManager(snackbarRefList, setSnackbarRefList)
    });

    return (
        <PortalContext.Provider value={portalManager.current}>
            {children}

            {/* Modal  */}
            {modalRefList.map((elm) => (
                <elm.ModalComponent key={elm.reactKey} />
            ))}

            {/* Popover */}
            {popoverRefList.map((elm) => (
                <elm.PopoverComponent key={elm.reactKey} />
            ))}

            {/* Snackbar */}
            <Snackbar refList={snackbarRefList} />
        </PortalContext.Provider>
    );
};
