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

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

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

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

export default withIsInShell(SignInOverlay);
