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 AddressBookOverlay = ({ shellContext: { isInShell } }: Props) => {
    const dispatch = useAppDispatch();
    const addressBookOverlayState = useAppSelector(state => getPageStateByType(state, "AddressBookOverlay"));
    const addressBookOverlay = addressBookOverlayState.value || nullPage;
    const isLoading = addressBookOverlayState.isLoading;

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

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

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

export default withIsInShell(AddressBookOverlay);
