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 { ShellContext } from "@insite/client-framework/Components/IsInShell";
import closeErrorModal from "@insite/client-framework/Store/Context/Handlers/CloseErrorModal";
import { loadPageByType } from "@insite/client-framework/Store/Data/Pages/PagesActionCreators";
import { getPageStateByType } from "@insite/client-framework/Store/Data/Pages/PageSelectors";
import translate from "@insite/client-framework/Translate";
import Modal from "@insite/mobius/Modal";
import * as React from "react";
import { FC, useContext, useEffect } from "react";

const ErrorModal: FC = () => {
    const modalIsOpen = useAppSelector(o => !!o.context.isErrorModalOpen);
    const apiError = useAppSelector(o => o.context.apiError);
    const isUnauthorizedError = useAppSelector(o => !!o.context.isUnauthorizedError);
    const errorPage = useAppSelector(o => getPageStateByType(o, "UnhandledErrorModal"));
    const dispatch = useAppDispatch();
    const { isInShell } = useContext(ShellContext);
    useEffect(() => {
        if (!errorPage.value && !errorPage.isLoading) {
            dispatch(loadPageByType("UnhandledErrorModal"));
        }
    }, [errorPage.isLoading, errorPage.value, loadPageByType]);

    const modalCloseHandler = () => {
        dispatch(closeErrorModal());
    };

    if (!errorPage.value || isInShell) {
        return null;
    }

    if (apiError?.detailsPath) {
        return (
            <Modal
                isOpen={modalIsOpen}
                handleClose={modalCloseHandler}
                headline={`Exception thrown calling ${apiError.url}`}
                sizeVariant="large"
            >
                <iframe src={apiError.detailsPath} height={window.innerHeight - 250} width="100%" />
            </Modal>
        );
    }

    const headline = isUnauthorizedError ? translate("Authorization Required") : errorPage.value.fields["modalTitle"];
    return (
        <Modal headline={headline} isOpen={modalIsOpen} handleClose={modalCloseHandler}>
            {isUnauthorizedError ? (
                <>{translate("Please sign in with a website user to view this page.")}</>
            ) : (
                <div data-test-selector="unhandledErrorModal">
                    <ShellContext.Provider value={{ isInShell, pageId: errorPage.id }}>
                        {createPageElement(errorPage.value.type, errorPage.value)}
                    </ShellContext.Provider>
                </div>
            )}
        </Modal>
    );
};

export default ErrorModal;
