import mergeToNew from "@insite/client-framework/Common/mergeToNew";
import StyledWrapper from "@insite/client-framework/Common/StyledWrapper";
import siteMessage from "@insite/client-framework/SiteMessage";
import Typography, { TypographyPresentationProps } from "@insite/mobius/Typography";
import getColor from "@insite/mobius/utilities/getColor";
import InjectableCss from "@insite/mobius/utilities/InjectableCss";
import React from "react";
import { css } from "styled-components";

export interface HasErrorStatusCode {
    errorStatusCode: number | undefined;
}

export interface PageErrorWrapperProps {
    value: HasErrorStatusCode;
    badRequestMessage?: React.ReactNode;
    notFoundMessage?: React.ReactNode;
    notAuthorizedMessage?: React.ReactNode;
    customErrorMessage?: React.ReactNode;
    extendedStyles?: PageErrorWrapperStyles;
    loadFailedWrapperTestSelector?: string;
    loadFailedTextTestSelector?: string;
}

export interface PageErrorWrapperStyles {
    loadFailedWrapper?: InjectableCss;
    loadFailedText?: TypographyPresentationProps;
}

export const pageErrorWrapperStyles: PageErrorWrapperStyles = {
    loadFailedWrapper: {
        css: css`
            display: flex;
            height: 200px;
            justify-content: center;
            align-items: center;
            background-color: ${getColor("common.accent")};
        `,
    },
    loadFailedText: { weight: "bold" },
};

export function PageErrorWrapper<P extends PageErrorWrapperProps>(props: React.PropsWithChildren<P>) {
    const [styles] = React.useState(() => mergeToNew(pageErrorWrapperStyles, props.extendedStyles));
    let errorMessage;

    if (props?.value?.errorStatusCode === 400) {
        errorMessage = `${props?.badRequestMessage || siteMessage("Page_BadRequest")}👿`;
    }

    if (props?.value?.errorStatusCode === 404) {
        errorMessage = `${props.notFoundMessage || siteMessage("Page_NotFound")}🤷‍♂️`;
    }

    if (props?.value?.errorStatusCode === 403) {
        errorMessage = `${props.notAuthorizedMessage || siteMessage("Page_NotAuthorized")}🙅‍♀️`;
    }

    if (props?.customErrorMessage) {
        errorMessage = `${props.customErrorMessage}🐶`;
    }

    return errorMessage ? (
        <StyledWrapper {...styles.loadFailedWrapper} data-test-selector={props.loadFailedWrapperTestSelector}>
            <Typography {...styles.loadFailedText} data-test-selector={props.loadFailedTextTestSelector}>
                {errorMessage}
            </Typography>
        </StyledWrapper>
    ) : (
        <>{props.children}</>
    );
}
