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";
import { useDispatch } from "react-redux";

type Props = HasShellContext;

const SignInOverlay = ({ shellContext: { isInShell } }: Props) => {
    const dispatch = useDispatch();
    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);
