import { getCookie } from "@insite/client-framework/Common/Cookies";
import StyledWrapper from "@insite/client-framework/Common/StyledWrapper";
import { API_URL_CURRENT_FRAGMENT } from "@insite/client-framework/Services/ApiService";
import { addCart, AddCartApiParameter } from "@insite/client-framework/Services/CartService";
import { GetVmiLocationsApiParameter } from "@insite/client-framework/Services/VmiLocationService";
import siteMessage from "@insite/client-framework/SiteMessage";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import { getSession, getSettingsCollection } from "@insite/client-framework/Store/Context/ContextSelectors";
import { getCurrentCartState, isCartEmpty } from "@insite/client-framework/Store/Data/Carts/CartsSelector";
import loadCurrentCart from "@insite/client-framework/Store/Data/Carts/Handlers/LoadCurrentCart";
import removeCart from "@insite/client-framework/Store/Data/Carts/Handlers/RemoveCart";
import loadVmiLocations from "@insite/client-framework/Store/Data/VmiLocations/Handlers/LoadVmiLocations";
import { getVmiLocationsDataView } from "@insite/client-framework/Store/Data/VmiLocations/VmiLocationsSelectors";
import { getPageLinkByPageType } from "@insite/client-framework/Store/Links/LinksSelectors";
import setIsReorderConfirmationModalOpen from "@insite/client-framework/Store/Pages/VmiBins/Handlers/SetIsReorderConfirmationModalOpen";
import setNextAction from "@insite/client-framework/Store/Pages/VmiBins/Handlers/SetNextAction";
import translate from "@insite/client-framework/Translate";
import { useMergeStyles } from "@insite/content-library/additionalStyles";
import TwoButtonModal, { TwoButtonModalStyles } from "@insite/content-library/Components/TwoButtonModal";
import { BaseTheme } from "@insite/mobius/globals/baseTheme";
import Select, { SelectPresentationProps } from "@insite/mobius/Select";
import Typography, { TypographyProps } from "@insite/mobius/Typography";
import { breakpointMediaQueries } from "@insite/mobius/utilities";
import { setCookie } from "@insite/mobius/utilities/cookies";
import { HasHistory, withHistory } from "@insite/mobius/utilities/HistoryContext";
import InjectableCss from "@insite/mobius/utilities/InjectableCss";
import VisuallyHidden from "@insite/mobius/VisuallyHidden";
import React, { useEffect, useState } from "react";
import { connect, ResolveThunks } from "react-redux";
import { css } from "styled-components";

export const NavigationModeCookieName = "NavigationMode";
export const NavigationModeState = "NavigationModeState";

interface OwnProps {
    extendedStyles?: NavigationModeMenuStyles;
}

const mapStateToProps = (state: ApplicationState) => {
    const session = getSession(state);
    const isAuthenticated = session.isAuthenticated && !session.isGuest;
    const vmiEnabled = getSettingsCollection(state).orderSettings.vmiEnabled;
    const cart = getCurrentCartState(state).value;
    const getVmiLocationsParameter = {
        filter: "",
        sort: "Name",
        page: 1,
        pageSize: 1, // get first location
    } as GetVmiLocationsApiParameter;
    return {
        currentMode: getCookie(NavigationModeCookieName) || "Storefront",
        displayModeSwitch:
            isAuthenticated &&
            vmiEnabled &&
            session.userRoles &&
            (session.userRoles.toLowerCase().indexOf("vmi_admin") !== -1 ||
                session.userRoles.toLowerCase().indexOf("vmi_user") !== -1),
        vmiDashboardPageUrl: getPageLinkByPageType(state, "VmiDashboardPage")?.url,
        homePageUrl: getPageLinkByPageType(state, "HomePage")?.url,
        cartPageLink: getPageLinkByPageType(state, "CartPage")?.url,
        cart,
        isCartEmpty: isCartEmpty(cart),
        vmiLocationsDataView: getVmiLocationsDataView(state, getVmiLocationsParameter),
        getVmiLocationsParameter,
        selectedLocationId: state.pages.vmiBins.getVmiBinsParameter.vmiLocationId,
        cartRequestInProcess: state.pages.vmiBins.cartRequestInProcess,
        isReorderConfirmationModalOpen: state.pages.vmiBins.isReorderConfirmationModalOpen,
        hasChangeLastQty:
            state.pages.vmiBins.selectVmiBinsChangedQty &&
            Object.keys(state.pages.vmiBins.selectVmiBinsChangedQty).length > 0,
    };
};

const mapDispatchToProps = {
    removeCart,
    loadVmiLocations,
    loadCurrentCart,
    setIsReorderConfirmationModalOpen,
    setNextAction,
};

export interface NavigationModeMenuStyles {
    currencyWrapper?: InjectableCss;
    navigationModeSelect?: SelectPresentationProps;
    navigationConfirmModal?: TwoButtonModalStyles;
    navigationConfirmMessage?: TypographyProps;
    navigationConfirmQuestion?: TypographyProps;
}

export const navigationModeMenuStyles: NavigationModeMenuStyles = {
    currencyWrapper: {
        css: css`
            display: flex;
        `,
    },
    navigationModeSelect: {
        backgroundColor: "common.accent",
        cssOverrides: {
            formInputWrapper: css`
                ${({ theme }: { theme: BaseTheme }) =>
                    breakpointMediaQueries(theme, [
                        null,
                        null,
                        null,
                        css`
                            width: 118px;
                        `,
                        css`
                            width: 271px;
                        `,
                    ])}
            `,
            inputSelect: css`
                border: none;
                text-transform: uppercase;
            `,
        },
    },
    navigationConfirmMessage: {
        as: "p",
        css: css`
            padding-top: 5px;
        `,
    },
    navigationConfirmQuestion: {
        as: "p",
        css: css`
            padding-top: 20px;
        `,
    },
};

type Props = OwnProps & ReturnType<typeof mapStateToProps> & ResolveThunks<typeof mapDispatchToProps> & HasHistory;

export const NavigationModeMenu = ({
    currentMode,
    displayModeSwitch,
    vmiDashboardPageUrl,
    homePageUrl,
    cartPageLink,
    cart,
    isCartEmpty,
    history,
    removeCart,
    extendedStyles,
    loadVmiLocations,
    vmiLocationsDataView,
    getVmiLocationsParameter,
    loadCurrentCart,
    selectedLocationId,
    cartRequestInProcess,
    isReorderConfirmationModalOpen,
    hasChangeLastQty,
    setIsReorderConfirmationModalOpen,
    setNextAction,
}: Props) => {
    if (!displayModeSwitch) {
        return null;
    }

    const styles = useMergeStyles("navigationModeMenu", navigationModeMenuStyles, extendedStyles);
    const [navigationHeaderText, setNavigationHeaderText] = useState<string>("");
    const [navigationMessage, setNavigationMessage] = useState<JSX.Element>();
    const [navigationCurrentMode, setNavigationCurrentMode] = useState<string>(currentMode);
    const [navigationNewMode, setNavigationNewMode] = useState<string>(currentMode);
    const [confirmModalIsOpen, setConfirmModalIsOpen] = useState<boolean>(false);

    useEffect(() => {
        if (!vmiLocationsDataView.value && !vmiLocationsDataView.isLoading) {
            loadVmiLocations(getVmiLocationsParameter);
        }
    });

    const navigationModeChangeHandler = (event: React.ChangeEvent<HTMLSelectElement>) => {
        const value = event.currentTarget.value;

        if (!isReorderConfirmationModalOpen && hasChangeLastQty && value !== "Vmi") {
            setIsReorderConfirmationModalOpen({ isReorderConfirmationModalOpen: true });
            setNextAction({ nextAction: () => switchNavigationMode(value) });
            return;
        }

        switchNavigationMode(value);
    };

    const switchNavigationMode = (mode: string) => {
        if (isCartEmpty) {
            setCookie(NavigationModeCookieName, mode);
            setNavigationCurrentMode(mode);

            if (mode === "Vmi") {
                vmiDashboardPageUrl && history.push(vmiDashboardPageUrl);
            } else if (cart?.status === "AlternateCart") {
                deleteAlternateCart();
            } else {
                homePageUrl && history.push(homePageUrl);
            }

            return;
        }

        if (mode === "Vmi") {
            setCookie(NavigationModeCookieName, currentMode);
            setConfirmModalIsOpen(true);
            setNavigationHeaderText(translate("Continue to VMI"));
            setNavigationMessage(
                <>
                    <Typography {...styles.navigationConfirmMessage}>{siteMessage("Cart_Change_To_Vmi")}</Typography>
                    <Typography {...styles.navigationConfirmQuestion}>
                        {translate("Would you like to continue?")}
                    </Typography>
                </>,
            );
        } else {
            setCookie(NavigationModeCookieName, mode);
            setNavigationCurrentMode(mode);
            if (cart?.status === "AlternateCart") {
                deleteAlternateCart();
            }
            homePageUrl && history.push(homePageUrl);
        }

        setNavigationNewMode(mode);
    };

    const deleteAlternateCart = () => {
        removeCart({
            cartId: API_URL_CURRENT_FRAGMENT,
            isAlternateCart: true,
            onSuccess: () => {
                homePageUrl && history.push(homePageUrl);
                loadCurrentCart();
            },
        });
    };

    const createAlternateCart = () => {
        if (vmiLocationsDataView.value && vmiLocationsDataView.value.length > 0) {
            const locationId = selectedLocationId ?? vmiLocationsDataView.value[0].id;
            addCart({ vmiLocationId: locationId } as AddCartApiParameter).then(() => {
                loadCurrentCart();
            });
        }
    };

    const changeNavigationModeHandler = () => {
        setCookie(NavigationModeCookieName, navigationNewMode);
        setNavigationCurrentMode(navigationNewMode);

        if (navigationNewMode === "Vmi") {
            createAlternateCart();
            vmiDashboardPageUrl && history.push(vmiDashboardPageUrl);
        } else {
            homePageUrl && history.push(homePageUrl);
        }

        setConfirmModalIsOpen(false);
    };

    const cancelNavigationModeHandler = () => {
        if (!isCartEmpty && navigationCurrentMode === "Storefront") {
            cartPageLink && history.push(cartPageLink);
        }
        setConfirmModalIsOpen(false);
    };

    const closeNavigationModeHandler = () => {
        setConfirmModalIsOpen(false);
    };

    const menuId = "navigationModeMenu";

    return (
        <StyledWrapper {...styles.currencyWrapper}>
            <VisuallyHidden as="label" id={`${menuId}-label`} htmlFor={menuId}>
                {translate("Navigation Mode")}
            </VisuallyHidden>
            <Select
                {...styles.navigationModeSelect}
                disabled={cartRequestInProcess}
                uid={menuId}
                onChange={navigationModeChangeHandler}
                value={navigationCurrentMode}
                autoComplete="off"
                hasLabel
            >
                <option value="Storefront" key="Storefront">
                    {translate("Storefront")}
                </option>
                <option value="Vmi" key="Vendor Managed Inventory">
                    {translate("Vendor Managed Inventory")}
                </option>
            </Select>
            <TwoButtonModal
                headlineText={`${navigationHeaderText}`}
                {...styles.navigationConfirmModal}
                modalIsOpen={confirmModalIsOpen}
                messageText={navigationMessage}
                cancelButtonText={translate("Back to Cart")}
                submitButtonText={translate("Continue")}
                onCancel={cancelNavigationModeHandler}
                onSubmit={changeNavigationModeHandler}
                onClose={closeNavigationModeHandler}
                submitTestSelector="submitNavigationMode"
            ></TwoButtonModal>
        </StyledWrapper>
    );
};

export default withHistory(connect(mapStateToProps, mapDispatchToProps)(NavigationModeMenu));
