import useAppDispatch from "@insite/client-framework/Common/Hooks/useAppDispatch";
import useAppSelector from "@insite/client-framework/Common/Hooks/useAppSelector";
import { createPageElement } from "@insite/client-framework/Components/ContentItemStore";
import { HasShellContext, ShellContext, withIsInShell } from "@insite/client-framework/Components/IsInShell";
import { loadPageByType } from "@insite/client-framework/Store/Data/Pages/PagesActionCreators";
import { getPageStateByType } from "@insite/client-framework/Store/Data/Pages/PageSelectors";
import { nullPage } from "@insite/client-framework/Store/Data/Pages/PagesState";
import React, { useEffect } from "react";

type Props = HasShellContext;

const StorePickupOverlay = ({ shellContext: { isInShell } }: Props) => {
    const dispatch = useAppDispatch();
    const storePickupOverlayState = useAppSelector(state => getPageStateByType(state, "StorePickupOverlay"));
    const storePickupOverlay = storePickupOverlayState.value || nullPage;
    const isLoading = storePickupOverlayState.isLoading;

    useEffect(() => {
        if (storePickupOverlay === nullPage && !isLoading) {
            dispatch(loadPageByType("StorePickupOverlay"));
        }
    }, []);

    if (storePickupOverlay === nullPage) {
        return null;
    }

    return (
        <ShellContext.Provider value={{ isInShell, pageId: storePickupOverlay.id }}>
            {createPageElement(storePickupOverlay.type, storePickupOverlay)}
        </ShellContext.Provider>
    );
};

export default withIsInShell(StorePickupOverlay);
