import StyledWrapper from "@insite/client-framework/Common/StyledWrapper";
import logger from "@insite/client-framework/Logger";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import setSignInOverlayIsOpen from "@insite/client-framework/Store/Components/SignInOverlay/Handlers/SetSignInOverlayIsOpen";
import { getCurrentUserIsGuest } from "@insite/client-framework/Store/Context/ContextSelectors";
import { getCurrentPage, getLocation } from "@insite/client-framework/Store/Data/Pages/PageSelectors";
import { getPageLinkByPageType } from "@insite/client-framework/Store/Links/LinksSelectors";
import translate from "@insite/client-framework/Translate";
import WidgetModule from "@insite/client-framework/Types/WidgetModule";
import WidgetProps from "@insite/client-framework/Types/WidgetProps";
import { BaseTheme } from "@insite/mobius/globals/baseTheme";
import Icon, { IconPresentationProps } from "@insite/mobius/Icon/Icon";
import Link, { LinkPresentationProps } from "@insite/mobius/Link";
import Typography from "@insite/mobius/Typography/Typography";
import { HasHistory, withHistory } from "@insite/mobius/utilities/HistoryContext";
import InjectableCss from "@insite/mobius/utilities/InjectableCss";
import React from "react";
import { connect, ResolveThunks } from "react-redux";
import { css, ThemeProps, withTheme } from "styled-components";

const mapStateToProps = (state: ApplicationState) => ({
    userName: state.context.session.userName,
    currentUserIsGuest: getCurrentUserIsGuest(state),
    isSignInPage: getCurrentPage(state).type === "SignInPage",
    signInUrl: getPageLinkByPageType(state, "SignInPage")?.url,
    currentLocation: getLocation(state),
});

const mapDispatchToProps = {
    setSignInOverlayIsOpen,
};

export interface SignInStyles {
    signInWrapper?: InjectableCss;
    userIcon?: IconPresentationProps;
    signInLink?: LinkPresentationProps;
}

export const signInStyles: SignInStyles = {
    signInWrapper: {
        css: css`
            display: flex;
            gap: 6px;
            padding: 10px 0 10px 0;
        `,
    },
    userIcon: {
        src: "User",
    },
};

type Props = WidgetProps &
    ReturnType<typeof mapStateToProps> &
    ResolveThunks<typeof mapDispatchToProps> &
    HasHistory &
    ThemeProps<BaseTheme>;

export const SignIn = ({
    userName,
    currentUserIsGuest,
    isSignInPage,
    signInUrl,
    currentLocation,
    history,
    theme,
    setSignInOverlayIsOpen,
}: Props) => {
    if (userName && !currentUserIsGuest) {
        return null;
    }

    const styles = signInStyles;

    const onSignInHandler = (e: React.MouseEvent) => {
        if ((!userName || currentUserIsGuest) && !isSignInPage) {
            e.preventDefault();

            if (theme.signIn?.useOverlay) {
                setSignInOverlayIsOpen({ isOpen: true });
                return;
            }

            if (!signInUrl) {
                logger.warn("No url was found for SignInPage, defaulting to /SignIn");
                history.push("/MyAccount/SignIn");
            } else {
                const returnUrl = currentLocation.pathname + currentLocation.search;
                if (returnUrl === "/") {
                    history.push(`${signInUrl}`);
                } else {
                    history.push(`${signInUrl}?returnUrl=${encodeURIComponent(returnUrl)}&clientRedirect=true`);
                }
            }
        }
    };

    return (
        <StyledWrapper {...styles.signInWrapper}>
            <Icon {...styles.userIcon} />
            <Typography>{translate("Already have an account?")}</Typography>
            <Link {...styles.signInLink} onClick={onSignInHandler}>
                {translate("Sign in.")}
            </Link>
        </StyledWrapper>
    );
};

const widgetModule: WidgetModule = {
    component: connect(mapStateToProps, mapDispatchToProps)(withHistory(withTheme(SignIn))),
    definition: {
        displayName: "Sign In",
        icon: "arrow-right-to-bracket",
        group: "Common",
    },
};

export default widgetModule;
