import siteMessage from "@insite/client-framework/SiteMessage";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import clearSelectedVmiBinsChangedQty from "@insite/client-framework/Store/Pages/VmiBins/Handlers/ClearSelectedVmiBinsChangedQty";
import setCartRequestInProcess from "@insite/client-framework/Store/Pages/VmiBins/Handlers/SetCartRequestInProcess";
import setIsReorderConfirmationModalOpen from "@insite/client-framework/Store/Pages/VmiBins/Handlers/SetIsReorderConfirmationModalOpen";
import setNextAction from "@insite/client-framework/Store/Pages/VmiBins/Handlers/SetNextAction";
import setNextPageUrl from "@insite/client-framework/Store/Pages/VmiBins/Handlers/SetNextPageUrl";
import updateCart from "@insite/client-framework/Store/Pages/VmiBins/Handlers/UpdateCart";
import translate from "@insite/client-framework/Translate";
import { VmiBinModel } from "@insite/client-framework/Types/ApiModels";
import ProductAddedToCartMessage from "@insite/content-library/Components/ProductAddedToCartMessage";
import TwoButtonModal from "@insite/content-library/Components/TwoButtonModal";
import { HasToasterContext, withToaster } from "@insite/mobius/Toast/ToasterContext";
import { HasHistory, withHistory } from "@insite/mobius/utilities/HistoryContext";
import React from "react";
import { connect, ResolveThunks } from "react-redux";

const mapStateToProps = (state: ApplicationState) => ({
    selectVmiBinsChangedQtyIds: state.pages.vmiBins.selectVmiBinsChangedQty,
    vmiBins: state.data.vmiBins.byId,
    isOpen: !!state.pages.vmiBins.isReorderConfirmationModalOpen,
    nextAction: state.pages.vmiBins.nextAction,
    nextPageUrl: state.pages.vmiBins.nextPageUrl,
});

const mapDispatchToProps = {
    clearSelectedVmiBinsChangedQty,
    setIsReorderConfirmationModalOpen,
    setNextAction,
    setNextPageUrl,
    updateCart,
    setCartRequestInProcess,
};

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

const ReorderConfirmationModal = ({
    selectVmiBinsChangedQtyIds,
    isOpen,
    vmiBins,
    clearSelectedVmiBinsChangedQty,
    setIsReorderConfirmationModalOpen,
    setNextAction,
    setNextPageUrl,
    toaster,
    history,
    nextAction,
    nextPageUrl,
    updateCart,
    setCartRequestInProcess,
}: Props) => {
    const showNotification = (isMultipleProduct: boolean) => {
        toaster.addToast({
            body: <ProductAddedToCartMessage isQtyAdjusted={false} multipleProducts={isMultipleProduct} />,
            messageType: "success",
        });
    };

    const completeUpdateCart = () => {
        setCartRequestInProcess({ cartRequestInProcess: false });
        history.push("/cart");
    };

    const onSubmit = () => {
        const newVmiBins: VmiBinModel[] = [];
        for (const id in selectVmiBinsChangedQtyIds) {
            const vmiBin = vmiBins[id];
            const product = {
                ...vmiBin.product,
                qtyOrdered: vmiBin.maximumQty > vmiBin.lastCountQty ? vmiBin.maximumQty - vmiBin.lastCountQty : 1,
            };

            const newVmiBin = {
                ...vmiBin,
                product,
            };
            newVmiBins.push(newVmiBin);
        }
        if (newVmiBins.length > 0) {
            updateCart({
                vmiBins: newVmiBins,
                vmiLocationId: newVmiBins[0].vmiLocationId,
                showNotification,
                onSuccess: completeUpdateCart,
            });
        }
        clearSelectedVmiBinsChangedQty();
        onCloseModal();
    };

    const onCancelModal = () => {
        if (nextAction) {
            nextAction();
        } else if (nextPageUrl) {
            history.push(nextPageUrl);
        }
        clearSelectedVmiBinsChangedQty();
        onCloseModal();
    };

    const onCloseModal = () => {
        setIsReorderConfirmationModalOpen({ isReorderConfirmationModalOpen: false });
        setNextAction({ nextAction: undefined });
        setNextPageUrl({ nextPageUrl: undefined });
    };

    return (
        <TwoButtonModal
            headlineText={translate("Want to create a reorder?")}
            messageText={siteMessage("Vmi_Navigate_Page_Reorder_Message")}
            cancelButtonText={translate("No Thanks")}
            submitButtonText={translate("Create Reorder")}
            modalIsOpen={isOpen}
            onCancel={onCancelModal}
            onSubmit={onSubmit}
            onClose={onCloseModal}
        ></TwoButtonModal>
    );
};

// eslint-disable-next-line spire/export-styles
export default connect(mapStateToProps, mapDispatchToProps)(withToaster(withHistory(ReorderConfirmationModal)));
