import StyledWrapper from "@insite/client-framework/Common/StyledWrapper";
import { Dictionary } from "@insite/client-framework/Common/Types";
import openPrintDialog from "@insite/client-framework/Common/Utilities/openPrintDialog";
import { makeHandlerChainAwaitable } from "@insite/client-framework/HandlerCreator";
import { API_URL_CURRENT_FRAGMENT } from "@insite/client-framework/Services/ApiService";
import siteMessage from "@insite/client-framework/SiteMessage";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import setShareListModalIsOpen from "@insite/client-framework/Store/Components/ShareListModal/Handlers/SetShareListModalIsOpen";
import { getSettingsCollection } from "@insite/client-framework/Store/Context/ContextSelectors";
import {
    canAddWishListLineToCart,
    getWishListLinesDataView,
} from "@insite/client-framework/Store/Data/WishListLines/WishListLinesSelectors";
import updateWishList from "@insite/client-framework/Store/Data/WishLists/Handlers/UpdateWishList";
import { getWishListState } from "@insite/client-framework/Store/Data/WishLists/WishListsSelectors";
import { getPageLinkByPageType } from "@insite/client-framework/Store/Links/LinksSelectors";
import addLinesToCart from "@insite/client-framework/Store/Pages/Cart/Handlers/AddLinesToCart";
import addWishListToCart from "@insite/client-framework/Store/Pages/Cart/Handlers/AddWishListToCart";
import deleteWishList from "@insite/client-framework/Store/Pages/MyListDetails/Handlers/DeleteWishList";
import deleteWishListLines from "@insite/client-framework/Store/Pages/MyListDetails/Handlers/DeleteWishListLines";
import exportWishList from "@insite/client-framework/Store/Pages/MyListDetails/Handlers/ExportWishList";
import loadWishListIfNeeded from "@insite/client-framework/Store/Pages/MyListDetails/Handlers/LoadWishListIfNeeded";
import loadWishListLines from "@insite/client-framework/Store/Pages/MyListDetails/Handlers/LoadWishListLines";
import loadWishLists from "@insite/client-framework/Store/Pages/MyListDetails/Handlers/LoadWishLists";
import setAllWishListLinesIsSelected from "@insite/client-framework/Store/Pages/MyListDetails/Handlers/SetAllWishListLinesIsSelected";
import setWishListTags from "@insite/client-framework/Store/Pages/MyListDetails/Handlers/SetWishListTags";
import updateLoadWishListLinesParameter from "@insite/client-framework/Store/Pages/MyListDetails/Handlers/UpdateLoadWishListLinesParameter";
import translate from "@insite/client-framework/Translate";
import {
    CartLineCollectionModel,
    CartLineModel,
    WishListLineModel,
    WishListModel,
} from "@insite/client-framework/Types/ApiModels";
import WidgetModule from "@insite/client-framework/Types/WidgetModule";
import WidgetProps from "@insite/client-framework/Types/WidgetProps";
import ScheduleReminderModal, {
    ScheduleReminderModalStyles,
} from "@insite/content-library/Components/ScheduleReminderModal";
import TwoButtonModal, { TwoButtonModalStyles } from "@insite/content-library/Components/TwoButtonModal";
import WishListPrintModal, { WishListPrintModalStyles } from "@insite/content-library/Components/WishListPrintModal";
import MyListsEditListForm from "@insite/content-library/Widgets/MyLists/MyListsEditListForm";
import AddTagsModal from "@insite/content-library/Widgets/MyListsDetails/AddTagsModal";
import MyListsDetailsCopyListForm from "@insite/content-library/Widgets/MyListsDetails/MyListsDetailsCopyListForm";
import Button, { ButtonPresentationProps } from "@insite/mobius/Button";
import Clickable, { ClickablePresentationProps } from "@insite/mobius/Clickable";
import Hidden, { HiddenProps } from "@insite/mobius/Hidden";
import Icon, { IconPresentationProps } from "@insite/mobius/Icon";
import Star from "@insite/mobius/Icons/Star";
import StarX from "@insite/mobius/Icons/StarX";
import Modal, { ModalPresentationProps } from "@insite/mobius/Modal";
import OverflowMenu, { OverflowMenuPresentationProps } from "@insite/mobius/OverflowMenu";
import { markForFocusLater } from "@insite/mobius/Overlay/helpers/focusManager";
import ToasterContext from "@insite/mobius/Toast/ToasterContext";
import Typography, { TypographyProps } from "@insite/mobius/Typography";
import { HasHistory, withHistory } from "@insite/mobius/utilities/HistoryContext";
import InjectableCss from "@insite/mobius/utilities/InjectableCss";
import * as React from "react";
import { connect, ResolveThunks } from "react-redux";
import { css } from "styled-components";

interface State {
    updateListModalIsOpen: boolean;
    deleteListModalIsOpen: boolean;
    deleteListItemsModalIsOpen: boolean;
    copyListModalIsOpen: boolean;
    printAllModalIsOpen: boolean;
    addTagsModalIsOpen: boolean;
    scheduleReminderModalIsOpen: boolean;
    closeCopyListModalOnEsc: boolean;
}

const mapStateToProps = (state: ApplicationState) => ({
    wishList: getWishListState(state, state.pages.myListDetails.wishListId).value,
    wishListLinesDataView: getWishListLinesDataView(state, state.pages.myListDetails.loadWishListLinesParameter),
    wishListSettings: getSettingsCollection(state).wishListSettings,
    selectedWishListLineIds: state.pages.myListDetails.selectedWishListLineIds,
    myListsPageLink: getPageLinkByPageType(state, "MyListsPage"),
    allowEditingOfWishLists: getSettingsCollection(state).wishListSettings.allowEditingOfWishLists,
    productInfosByWishListLineId: state.pages.myListDetails.productInfosByWishListLineId,
    isUpdatingCart: state.context.isUpdatingCart,
    isLoading: !!(
        state.pages.myListDetails.wishListId && state.data.wishLists.isLoading[state.pages.myListDetails.wishListId]
    ),
});

const mapDispatchToProps = {
    addWishListToCart,
    addLinesToCart,
    deleteWishList,
    deleteWishListLines,
    loadWishLists,
    loadWishListLines: makeHandlerChainAwaitable(loadWishListLines),
    updateLoadWishListLinesParameter,
    setShareListModalIsOpen,
    setAllWishListLinesIsSelected,
    exportWishList,
    updateWishList,
    loadWishListIfNeeded,
    setWishListTags,
};

const enum fields {
    copyButton = "copyButton",
    exportButton = "exportButton",
    printButton = "printButton",
    deleteListButton = "deleteListButton",
    removeSelectedButton = "removeSelectedButton",
    addTagsButton = "addTagsButton",
    editReminderButton = "editReminderButton",
    editListButton = "editListButton",
    addListToCartButton = "addListToCartButton",
    hideButton = "hideButton",
    shareButton = "shareButton",
}

interface OwnProps extends WidgetProps {
    fields: {
        [fields.copyButton]: boolean;
        [fields.exportButton]: boolean;
        [fields.printButton]: boolean;
        [fields.deleteListButton]: boolean;
        [fields.removeSelectedButton]: boolean;
        [fields.addTagsButton]: boolean;
        [fields.editReminderButton]: boolean;
        [fields.editListButton]: boolean;
        [fields.addListToCartButton]: boolean;
        [fields.hideButton]: boolean;
        [fields.shareButton]: boolean;
    };
}

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

export interface MyListsDetailsActionStyles {
    wrapper?: InjectableCss;
    buttonWrapper?: InjectableCss;
    wideHidden?: HiddenProps;
    nameText?: TypographyProps;
    overflowMenu?: OverflowMenuPresentationProps;
    narrowHidden?: HiddenProps;
    printButton?: ButtonPresentationProps;
    addTagsButton?: ButtonPresentationProps;
    scheduleButton?: ButtonPresentationProps;
    editButton?: ButtonPresentationProps;
    shareButton?: ButtonPresentationProps;
    hideButton?: ButtonPresentationProps;
    addItemButton?: ButtonPresentationProps;
    removeSelectedButton?: ButtonPresentationProps;
    addListButton?: ButtonPresentationProps;
    editListModal?: ModalPresentationProps;
    deleteListModal?: TwoButtonModalStyles;
    deleteListItemsModal?: TwoButtonModalStyles;
    printListModal?: WishListPrintModalStyles;
    copyListModal?: ModalPresentationProps;
    scheduleReminderModal?: ScheduleReminderModalStyles;
    iconContainer?: InjectableCss;
    actionFavoriteClickable?: ClickablePresentationProps;
    starIcon?: IconPresentationProps;
    starXIcon?: IconPresentationProps;
    copyButton?: ButtonPresentationProps;
    exportButton?: ButtonPresentationProps;
    deleteButton?: ButtonPresentationProps;
}

export const actionStyles: MyListsDetailsActionStyles = {
    wrapper: {
        css: css`
            display: flex;
            justify-content: space-between;
        `,
    },
    buttonWrapper: {
        css: css`
            display: flex;
            flex-wrap: nowrap;
            align-items: flex-start;
        `,
    },
    wideHidden: {
        below: "lg",
        css: css`
            display: flex;
            flex-wrap: nowrap;
        `,
    },
    nameText: {
        variant: "h3",
        as: "h1",
        ellipsis: true,
        css: css`
            width: 100%;
            margin-left: 10px;
        `,
    },
    narrowHidden: {
        above: "md",
    },
    printButton: {
        css: css`
            padding: 0 10px;
            margin-right: 10px;
            white-space: nowrap;
        `,
        variant: "secondary",
    },
    addTagsButton: {
        css: css`
            padding: 0 10px;
            margin-right: 10px;
            white-space: nowrap;
        `,
        variant: "secondary",
    },
    scheduleButton: {
        css: css`
            padding: 0 10px;
            margin-right: 10px;
            white-space: nowrap;
        `,
        variant: "secondary",
    },
    editButton: {
        css: css`
            padding: 0 10px;
            margin-right: 10px;
            white-space: nowrap;
        `,
        variant: "secondary",
    },
    shareButton: {
        css: css`
            padding: 0 10px;
            margin-right: 10px;
            white-space: nowrap;
        `,
        variant: "secondary",
    },
    hideButton: {
        typographyProps: {
            weight: "bold",
            css: css`
                white-space: nowrap;
            `,
        },
        css: css`
            padding: 0 10px;
            margin-right: 10px;
            white-space: nowrap;
        `,
        variant: "secondary",
    },
    addItemButton: {
        typographyProps: {
            weight: "bold",
            css: css`
                padding: 0 10px;
                white-space: nowrap;
            `,
        },
        css: css`
            padding: 0 10px;
            margin-right: 10px;
            white-space: nowrap;
        `,
        variant: "secondary",
    },
    removeSelectedButton: {
        typographyProps: {
            weight: "bold",
        },
        css: css`
            padding: 0 10px;
            margin-right: 10px;
            white-space: nowrap;
        `,
        variant: "tertiary",
    },
    addListButton: {
        typographyProps: {
            weight: "bold",
        },
        css: css`
            padding: 0 10px;
            margin-right: 10px;
            min-width: 90px;
            white-space: nowrap;
        `,
    },
    editListModal: {
        sizeVariant: "small",
    },
    copyListModal: {
        sizeVariant: "small",
        cssOverrides: {
            modalBody: css`
                overflow: visible;
            `,
        },
    },
    iconContainer: {
        css: css`
            width: 15px;
            margin-top: 12px;
        `,
    },
    actionFavoriteClickable: {
        css: css`
            width: 15px;
        `,
    },
    starIcon: {
        src: Star,
        size: 15,
    },
    starXIcon: {
        src: StarX,
        size: 15,
    },
    copyButton: {
        css: css`
            padding: 0 15px;
            margin-right: 10px;
            white-space: nowrap;
        `,
        variant: "secondary",
    },
    exportButton: {
        css: css`
            padding: 0 15px;
            margin-right: 10px;
            white-space: nowrap;
        `,
        variant: "secondary",
    },
    deleteButton: {
        css: css`
            padding: 0 15px;
            margin-right: 10px;
            white-space: nowrap;
        `,
        variant: "secondary",
    },
};

const styles = actionStyles;

class MyListsDetailsActions extends React.Component<Props, State> {
    static contextType = ToasterContext;
    declare context: React.ContextType<typeof ToasterContext>;

    constructor(props: Props) {
        super(props);
        this.state = {
            updateListModalIsOpen: false,
            printAllModalIsOpen: false,
            addTagsModalIsOpen: false,
            deleteListModalIsOpen: false,
            deleteListItemsModalIsOpen: false,
            copyListModalIsOpen: false,
            scheduleReminderModalIsOpen: false,
            closeCopyListModalOnEsc: true,
        };
    }

    displayToast(message: React.ReactNode) {
        this.context.addToast({ body: message, messageType: "success" });
    }

    linesSelected() {
        return this.props.selectedWishListLineIds.length > 0;
    }

    enableAddToCart() {
        const lines = this.props.wishListLinesDataView.value;
        return (
            this.props.wishList?.canAddToCart &&
            !this.props.isUpdatingCart &&
            lines?.some(o => canAddWishListLineToCart(o, this.props.productInfosByWishListLineId)) &&
            this.allQuantitiesAreValid(lines)
        );
    }

    allQuantitiesAreValid(wishListLines: WishListLineModel[]): boolean {
        return wishListLines
            .filter(
                o =>
                    this.props.selectedWishListLineIds.length === 0 ||
                    this.props.selectedWishListLineIds.indexOf(o.id) > -1,
            )
            .every(o => o.qtyOrdered && parseFloat(o.qtyOrdered.toString()) > 0);
    }

    editClickHandler = () => {
        this.setState({ updateListModalIsOpen: true });
    };

    shareClickHandler = () => {
        this.props.setShareListModalIsOpen({ modalIsOpen: true, wishListId: this.props.wishList?.id });
    };

    printOrOpenPrintAllModal = () => {
        const { wishListLinesDataView } = this.props;
        if (!wishListLinesDataView.value || !wishListLinesDataView.pagination) {
            return null;
        }

        this.setState({ printAllModalIsOpen: true });
    };

    closePrintModal = () => {
        this.setState({ printAllModalIsOpen: false });
    };

    editCloseHandler = () => {
        this.setState({ updateListModalIsOpen: false });
    };

    addToCartClickHandler = (e: any) => {
        e.preventDefault();
        if (!this.props.wishList || !this.props.wishListLinesDataView.value) {
            return;
        }

        const changedSharedListLinesQuantities: Dictionary<number> = {};
        for (const wishListLineId in this.props.productInfosByWishListLineId) {
            changedSharedListLinesQuantities[wishListLineId] =
                this.props.productInfosByWishListLineId[wishListLineId]!.qtyOrdered;
        }
        if (this.linesSelected()) {
            const selectedLines = this.props.wishListLinesDataView.value.filter(
                o => this.props.selectedWishListLineIds.indexOf(o.id) > -1,
            );
            const linesToAdd = selectedLines.filter(
                o =>
                    o.quoteRequired ||
                    o.allowZeroPricing ||
                    this.props.productInfosByWishListLineId[o.id]?.pricing?.unitNetPrice !== 0,
            );

            if (linesToAdd.length === 0) {
                this.context.addToast({ body: siteMessage("Cart_InvalidPrice"), messageType: "danger" });
                return;
            }

            this.props.addLinesToCart({
                apiParameter: {
                    cartId: API_URL_CURRENT_FRAGMENT,
                    cartLineCollection: {
                        cartLines: linesToAdd.map(o => {
                            return { ...o, qtyOrdered: changedSharedListLinesQuantities[o.id] } as any as CartLineModel;
                        }),
                    } as CartLineCollectionModel,
                },
                onSuccess: () => {
                    this.onAddToCartSuccess({
                        notAllAddedToCart: linesToAdd.length !== selectedLines.length,
                    } as CartLineCollectionModel);
                },
                onComplete(resultProps) {
                    if (resultProps.apiResult) {
                        this.onSuccess?.();
                    }
                },
            });
        } else {
            this.props.addWishListToCart({
                apiParameter: {
                    wishListId: this.props.wishList.id,
                    changedSharedListLinesQuantities,
                },
                onSuccess: this.onAddToCartSuccess,
                onComplete(resultProps) {
                    if (resultProps.apiResult) {
                        this.onSuccess?.(resultProps.apiResult);
                    }
                },
            });
        }
    };

    onAddToCartSuccess = (apiResult?: CartLineCollectionModel) => {
        this.displayToast(
            apiResult?.notAllAddedToCart
                ? siteMessage("Lists_Items_Not_All_Added_To_Cart")
                : siteMessage("Cart_AllProductsAddedToCart"),
        );
    };

    removeSelectedClickHandler = () => {
        this.setState({ deleteListItemsModalIsOpen: true });
    };

    removeSelectedCancelHandler = () => {
        this.setState({ deleteListItemsModalIsOpen: false });
    };

    removeSelectedSubmitHandler = () => {
        if (!this.props.wishList || !this.props.wishListLinesDataView.value) {
            return;
        }

        this.setState({ deleteListItemsModalIsOpen: false });
        const wishListLineIds = this.props.wishListLinesDataView.value
            .filter(o => this.props.selectedWishListLineIds.indexOf(o.id) > -1)
            .map(o => o.id);
        this.props.deleteWishListLines({
            wishListId: this.props.wishList.id,
            wishListLineIds,
            onSuccess: this.onRemoveSelectedSuccess,
            onComplete() {
                this.onSuccess?.();
            },
        });
    };

    onRemoveSelectedSuccess = () => {
        this.displayToast(translate(`Item${this.props.selectedWishListLineIds.length > 1 ? "s" : ""} Deleted`));
        this.props.setAllWishListLinesIsSelected({ isSelected: false });
    };

    deleteClickHandler = () => {
        this.setState({ deleteListModalIsOpen: true });
    };

    deleteCancelHandler = () => {
        this.setState({ deleteListModalIsOpen: false });
    };

    deleteSubmitHandler = () => {
        if (!this.props.wishList) {
            return;
        }

        this.setState({ deleteListModalIsOpen: false });
        this.props.myListsPageLink && this.props.history.push(this.props.myListsPageLink.url);
        this.props.deleteWishList({
            wishListId: this.props.wishList.id,
            onSuccess: this.onDeleteSuccess,
            onComplete() {
                this.onSuccess?.();
            },
        });
    };

    onDeleteSuccess = () => {
        this.displayToast(translate("List Deleted"));
    };

    copyClickHandler = () => {
        this.props.loadWishLists();
        this.setState({ copyListModalIsOpen: true });
    };

    exportClickHandler = () => {
        if (!this.props.wishList) {
            return;
        }

        this.props.exportWishList({
            wishListId: this.props.wishList.id,
        });
    };

    copyCancelHandler = () => {
        this.setState({ copyListModalIsOpen: false });
    };

    copySubmitHandler = () => {
        this.setState({ copyListModalIsOpen: false });
    };

    disableCloseCopyListModalOnEsc = () => {
        this.setState({ closeCopyListModalOnEsc: false });
    };

    enableCloseCopyListModalOnEsc = () => {
        this.setState({ closeCopyListModalOnEsc: true });
    };

    scheduleReminderClickHandler = () => {
        this.setState({ scheduleReminderModalIsOpen: true });
    };

    closeScheduleReminderModalHandler = () => {
        this.setState({ scheduleReminderModalIsOpen: false });
    };

    toggleFavorite = (wishList: WishListModel) => {
        if (!wishList) {
            return;
        }

        const that = this;
        this.props.updateWishList({
            apiParameter: {
                wishList: {
                    ...wishList,
                    isFavorite: !wishList.isFavorite,
                    wishListLineCollection: null,
                },
            },
            onComplete(resultProps) {
                if (resultProps.result?.wishList) {
                    that.props.loadWishListIfNeeded({ wishListId: resultProps.result?.wishList.id });
                } else if (resultProps.result?.errorMessage) {
                    this.onError?.(resultProps.result.errorMessage);
                }
            },
        });
    };

    addTagsClickHandler = () => {
        this.setState({ addTagsModalIsOpen: true });
    };

    closeAddTagsModalHandler = () => {
        this.setState({ addTagsModalIsOpen: false });
        const tags = this.props.wishList?.wishListTags?.map(o => o.tag);
        if (tags) {
            this.props.setWishListTags({ wishListTags: tags });
        }
    };

    toggleHide = (wishList: WishListModel) => {
        if (!wishList) {
            return;
        }

        const that = this;
        this.props.updateWishList({
            apiParameter: {
                wishList: {
                    ...wishList,
                    isHidden: !wishList.isHidden,
                    wishListLineCollection: null,
                },
            },
            onComplete(resultProps) {
                if (resultProps.result?.wishList) {
                    that.props.loadWishListIfNeeded({ wishListId: resultProps.result?.wishList.id });
                } else if (resultProps.result?.errorMessage) {
                    this.onError?.(resultProps.result.errorMessage);
                }
            },
        });
    };

    render() {
        const { wishList, wishListSettings, wishListLinesDataView, allowEditingOfWishLists, isLoading } = this.props;
        if (!wishList) {
            return null;
        }
        const showEdit = !wishList.isSharedList && !wishList.isAutogenerated;
        const showShare =
            !wishList.isSharedList &&
            wishListSettings.allowMultipleWishLists &&
            wishListSettings.allowListSharing &&
            !wishList.isAutogenerated;
        const showRemoveSelected =
            (wishList.allowEdit || !wishList.isSharedList) && this.linesSelected() && !wishList.isAutogenerated;
        const showSchedule = wishListSettings.enableWishListReminders && !wishList.isAutogenerated;
        const showAddToCart = (wishListLinesDataView.value?.length || 0) > 0;
        const showCopy = wishListSettings.allowMultipleWishLists && showAddToCart;
        const addListToCartButtonText = this.linesSelected()
            ? translate("Add Selected to Cart")
            : translate("Add List to Cart");
        const scheduleButtonText = wishList.schedule ? translate("Edit Reminder") : translate("Schedule Reminder");
        const showDelete = allowEditingOfWishLists && !wishList.isSharedList && !wishList.isAutogenerated;
        const toggleHideButtonText = wishList.isHidden ? translate("Unhide List") : translate("Hide List");
        const toggleFavoriteLabel = wishList.isFavorite
            ? translate("Remove from favorites")
            : translate("Add to favorites");

        const overflowItems = [];
        const wideHiddenOverflowMenu = [];
        const wideHiddenButtons = [];

        if (showCopy) {
            if (this.props.fields.copyButton === false) {
                wideHiddenButtons.push(
                    <Button
                        {...styles.copyButton}
                        key="copy"
                        onClick={this.copyClickHandler}
                        data-test-selector="copyList"
                    >
                        {translate("Copy")}
                    </Button>,
                );
            } else {
                overflowItems.push(
                    <Clickable key="copy" onClick={this.copyClickHandler} data-test-selector="copyList">
                        {translate("Copy")}
                    </Clickable>,
                );
            }
        }

        if (this.props.fields.printButton === false) {
            wideHiddenButtons.push(
                <Button
                    {...styles.printButton}
                    key="print"
                    onClick={this.printOrOpenPrintAllModal}
                    data-test-selector="printList"
                    disabled={(wishListLinesDataView.value?.length ?? 0) <= 0}
                >
                    {translate("Print")}
                </Button>,
            );
        } else {
            overflowItems.push(
                <Clickable
                    key="print"
                    onClick={this.printOrOpenPrintAllModal}
                    data-test-selector="myListsDetails_printButton"
                    disabled={(wishListLinesDataView.value?.length ?? 0) <= 0}
                >
                    {translate("Print")}
                </Clickable>,
            );
        }

        if (!wishList.isAutogenerated) {
            if (this.props.fields.addTagsButton) {
                overflowItems.push(
                    <Clickable key="addTags" onClick={this.addTagsClickHandler} data-test-selector="addTags">
                        {translate("Add Tags")}
                    </Clickable>,
                );
            } else {
                wideHiddenButtons.push(
                    <Button
                        {...styles.addTagsButton}
                        key="addTags"
                        onClick={this.addTagsClickHandler}
                        data-test-selector="addTags"
                    >
                        {translate("Add Tags")}
                    </Button>,
                );
            }
        }

        if (showSchedule) {
            if (this.props.fields.editReminderButton === false) {
                wideHiddenButtons.push(
                    <Button
                        {...styles.scheduleButton}
                        key="scheduleReminder"
                        onClick={this.scheduleReminderClickHandler}
                        data-test-selector="scheduleReminderList"
                    >
                        {scheduleButtonText}
                    </Button>,
                );
            } else {
                overflowItems.push(
                    <Clickable
                        key="scheduleReminder"
                        onClick={this.scheduleReminderClickHandler}
                        data-test-selector="scheduleReminderList"
                    >
                        {scheduleButtonText}
                    </Clickable>,
                );
            }
        }

        if (!wishList.isAutogenerated) {
            if (this.props.fields.hideButton === false) {
                wideHiddenButtons.push(
                    <Button
                        {...styles.hideButton}
                        key="hide"
                        onClick={() => this.toggleHide(wishList)}
                        data-test-selector="myListsDetailsHide"
                        disabled={isLoading}
                    >
                        {toggleHideButtonText}
                    </Button>,
                );
            } else {
                overflowItems.push(
                    <Clickable
                        key="hide"
                        onClick={() => this.toggleHide(wishList)}
                        data-test-selector="myListsDetailsHide"
                        disabled={isLoading}
                    >
                        {toggleHideButtonText}
                    </Clickable>,
                );
            }
        }

        if (showEdit) {
            if (this.props.fields.editListButton === false) {
                wideHiddenButtons.push(
                    <Button
                        {...styles.editButton}
                        key="edit"
                        onClick={this.editClickHandler}
                        data-test-selector="editList"
                    >
                        {translate("Edit")}
                    </Button>,
                );
            } else {
                overflowItems.push(
                    <Clickable key="edit" onClick={this.editClickHandler} data-test-selector="editList">
                        {translate("Edit")}
                    </Clickable>,
                );
            }
        }

        if (showShare) {
            if (this.props.fields.shareButton) {
                overflowItems.push(
                    <Clickable
                        key="share"
                        onClick={this.shareClickHandler}
                        data-test-selector="myListDetails_shareList"
                    >
                        {translate("Share")}
                    </Clickable>,
                );
            } else {
                wideHiddenButtons.push(
                    <Button
                        {...styles.shareButton}
                        key="share"
                        onClick={this.shareClickHandler}
                        data-test-selector="myListDetails_shareList"
                    >
                        {translate("Share")}
                    </Button>,
                );
            }
        }

        if (showRemoveSelected) {
            if (this.props.fields.removeSelectedButton === false) {
                wideHiddenButtons.push(
                    <Button
                        {...styles.removeSelectedButton}
                        key="removeSelected"
                        onClick={this.removeSelectedClickHandler}
                        data-test-selector="myListDetails_removeSelected"
                    >
                        {translate("Remove Selected")}
                    </Button>,
                );
            } else {
                overflowItems.push(
                    <Clickable
                        key="removeSelected"
                        onClick={this.removeSelectedClickHandler}
                        data-test-selector="myListDetails_removeSelected"
                    >
                        {translate("Remove Selected")}
                    </Clickable>,
                );
            }
        }

        if (this.props.fields.addListToCartButton) {
            overflowItems.push(
                <Clickable
                    key="addToCart"
                    disabled={!this.enableAddToCart() || !showAddToCart}
                    onClick={this.addToCartClickHandler}
                    data-test-selector="myListDetails_addListToCart"
                >
                    {addListToCartButtonText}
                </Clickable>,
            );
        } else {
            wideHiddenButtons.push(
                <Button
                    key="addToCart"
                    disabled={!this.enableAddToCart() || !showAddToCart}
                    {...styles.addListButton}
                    onClick={this.addToCartClickHandler}
                    data-test-selector="myListDetails_addListToCart"
                >
                    {addListToCartButtonText}
                </Button>,
            );
        }

        if (wishList.wishListLinesCount > 0) {
            if (this.props.fields.exportButton === false) {
                wideHiddenButtons.push(
                    <Button
                        {...styles.exportButton}
                        key="export"
                        onClick={this.exportClickHandler}
                        data-test-selector="exportList"
                    >
                        {translate("Export")}
                    </Button>,
                );
            } else {
                overflowItems.push(
                    <Clickable key="export" onClick={this.exportClickHandler} data-test-selector="exportList">
                        {translate("Export")}
                    </Clickable>,
                );
            }
        }

        if (showDelete) {
            if (this.props.fields.deleteListButton === false) {
                wideHiddenButtons.push(
                    <Button
                        {...styles.deleteButton}
                        key="delete"
                        onClick={this.deleteClickHandler}
                        data-test-selector="deleteList"
                    >
                        {translate("Delete")}
                    </Button>,
                );
            } else {
                overflowItems.push(
                    <Clickable key="delete" onClick={this.deleteClickHandler} data-test-selector="deleteList">
                        {translate("Delete")}
                    </Clickable>,
                );
            }
        }

        if (overflowItems.length > 0) {
            wideHiddenOverflowMenu.push(
                <OverflowMenu key="overflowMenu" onOpen={markForFocusLater} {...styles.overflowMenu}>
                    {overflowItems}
                </OverflowMenu>,
            );
        }

        return (
            <StyledWrapper {...styles.wrapper}>
                {!wishList.isAutogenerated && (
                    <StyledWrapper {...styles.iconContainer}>
                        <Clickable
                            {...styles.actionFavoriteClickable}
                            onClick={() => this.toggleFavorite(wishList)}
                            aria-label={toggleFavoriteLabel}
                            data-test-selector="myListsDetailsFavorite"
                            disabled={isLoading}
                        >
                            {wishList.isFavorite && (
                                <Icon {...styles.starXIcon} data-test-selector="myListsDetailsFavoriteStarXIcon" />
                            )}
                            {!wishList.isFavorite && (
                                <Icon {...styles.starIcon} data-test-selector="myListsDetailsFavoriteStarIcon" />
                            )}
                        </Clickable>
                    </StyledWrapper>
                )}
                <Typography {...styles.nameText} data-test-selector="listName">
                    {wishList.name}
                </Typography>
                <StyledWrapper {...styles.buttonWrapper} data-test-selector="menuWrapper">
                    <Hidden {...styles.narrowHidden}>
                        <OverflowMenu position="end" onOpen={markForFocusLater} {...styles.overflowMenu}>
                            {showAddToCart ? (
                                <Clickable onClick={this.addToCartClickHandler}>{addListToCartButtonText}</Clickable>
                            ) : null}
                            {showRemoveSelected ? (
                                <Clickable onClick={this.removeSelectedClickHandler}>
                                    {translate("Remove Selected")}
                                </Clickable>
                            ) : null}
                            {showShare ? (
                                <Clickable onClick={this.shareClickHandler}>{translate("Share")}</Clickable>
                            ) : null}
                            {showEdit ? (
                                <Clickable onClick={this.editClickHandler}>{translate("Edit")}</Clickable>
                            ) : null}
                            {!wishList.isAutogenerated && (
                                <Clickable onClick={() => this.toggleHide(wishList)} disabled={isLoading}>
                                    {toggleHideButtonText}
                                </Clickable>
                            )}
                            {showSchedule ? (
                                <Clickable onClick={this.scheduleReminderClickHandler}>{scheduleButtonText}</Clickable>
                            ) : null}
                            {!wishList.isAutogenerated && (
                                <Clickable onClick={this.addTagsClickHandler}>{translate("Add Tags")}</Clickable>
                            )}
                            <Clickable onClick={this.printOrOpenPrintAllModal}>{translate("Print")}</Clickable>
                            {showCopy ? (
                                <Clickable onClick={this.copyClickHandler}>{translate("Copy")}</Clickable>
                            ) : null}
                            {wishList.wishListLinesCount > 0 ? (
                                <Clickable onClick={this.exportClickHandler}>{translate("Export")}</Clickable>
                            ) : null}
                            {showDelete ? (
                                <Clickable onClick={this.deleteClickHandler}>{translate("Delete")}</Clickable>
                            ) : null}
                        </OverflowMenu>
                    </Hidden>
                    <Hidden {...styles.wideHidden} data-test-selector="wideHidden">
                        {wideHiddenButtons}
                        {wideHiddenOverflowMenu}
                    </Hidden>
                </StyledWrapper>
                <Modal
                    headline={translate("Edit List Detail")}
                    {...styles.editListModal}
                    isOpen={this.state.updateListModalIsOpen}
                    handleClose={this.editCloseHandler}
                >
                    <MyListsEditListForm
                        wishList={wishList}
                        onCancel={this.editCloseHandler}
                        onSubmit={this.editCloseHandler}
                    ></MyListsEditListForm>
                </Modal>
                <TwoButtonModal
                    headlineText={translate("Delete List")}
                    {...styles.deleteListModal}
                    modalIsOpen={this.state.deleteListModalIsOpen}
                    messageText={`${translate("Are you sure you want to delete")} ${wishList.name}?`}
                    cancelButtonText={translate("Cancel")}
                    submitButtonText={translate("Delete")}
                    onCancel={this.deleteCancelHandler}
                    onSubmit={this.deleteSubmitHandler}
                    submitTestSelector="submitDeleteList"
                ></TwoButtonModal>
                <TwoButtonModal
                    headlineText={translate(`Delete Item${this.props.selectedWishListLineIds.length > 1 ? "s" : ""}`)}
                    {...styles.deleteListItemsModal}
                    modalIsOpen={this.state.deleteListItemsModalIsOpen}
                    messageText={translate(
                        `Are you sure you want to delete ${
                            this.props.selectedWishListLineIds.length > 1 ? "these items" : "this item"
                        }?`,
                    )}
                    cancelButtonText={translate("Cancel")}
                    submitButtonText={translate("Delete")}
                    onCancel={this.removeSelectedCancelHandler}
                    onSubmit={this.removeSelectedSubmitHandler}
                    submitTestSelector="submitDeleteListItems"
                ></TwoButtonModal>
                {wishListLinesDataView.value && (
                    <WishListPrintModal
                        isOpen={this.state.printAllModalIsOpen}
                        handleClose={this.closePrintModal}
                        updateParameterFunction={(pageSize: number) => {
                            if (wishListLinesDataView.pagination?.pageSize === pageSize) {
                                return;
                            }

                            this.props.updateLoadWishListLinesParameter({ wishListId: wishList.id, pageSize });
                        }}
                        awaitableLoader={this.props.loadWishListLines}
                        initialPageSize={
                            wishListLinesDataView.value ? wishListLinesDataView.pagination?.pageSize || 8 : 8
                        }
                        reloading={false}
                        lineCollection={{
                            pagination: wishListLinesDataView.value ? wishListLinesDataView?.pagination || null : null,
                        }}
                        styles={styles.printListModal}
                        selectedIds={this.props.selectedWishListLineIds}
                    />
                )}
                <Modal
                    headline={translate("Copy List")}
                    isOpen={this.state.copyListModalIsOpen}
                    handleClose={this.copyCancelHandler}
                    closeOnEsc={this.state.closeCopyListModalOnEsc}
                    {...styles.copyListModal}
                >
                    <MyListsDetailsCopyListForm
                        onCancel={this.copyCancelHandler}
                        onSubmit={this.copySubmitHandler}
                        enableCloseCopyListModalOnEsc={this.enableCloseCopyListModalOnEsc}
                        disableCloseCopyListModalOnEsc={this.disableCloseCopyListModalOnEsc}
                    ></MyListsDetailsCopyListForm>
                </Modal>
                <ScheduleReminderModal
                    wishList={wishList}
                    isOpen={this.state.scheduleReminderModalIsOpen}
                    handleClose={this.closeScheduleReminderModalHandler}
                    extendedStyles={styles.scheduleReminderModal}
                />
                <AddTagsModal isOpen={this.state.addTagsModalIsOpen} handleClose={this.closeAddTagsModalHandler} />
            </StyledWrapper>
        );
    }
}

const widgetModule: WidgetModule = {
    component: connect(mapStateToProps, mapDispatchToProps)(withHistory(MyListsDetailsActions)),
    definition: {
        group: "My Lists Details",
        displayName: "Actions",
        allowedContexts: ["MyListsDetailsPage"],
        fieldDefinitions: [
            {
                name: "overflowButtonsTitle",
                displayName: "Overflow Buttons",
                editorTemplate: "LabelField",
                defaultValue: "",
                fieldType: "General",
                sortOrder: 0,
            },
            {
                name: "overflowButtonsHorizontalRule",
                defaultValue: "",
                editorTemplate: "HorizontalRule",
                fieldType: "General",
                sortOrder: 1,
            },
            {
                name: fields.copyButton,
                displayName: "Copy",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                isRequired: false,
                variant: "toggle",
                sortOrder: 2,
            },
            {
                name: fields.exportButton,
                displayName: "Export",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                isRequired: false,
                variant: "toggle",
                sortOrder: 3,
            },
            {
                name: fields.printButton,
                displayName: "Print",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                isRequired: false,
                variant: "toggle",
                sortOrder: 4,
            },
            {
                name: fields.deleteListButton,
                displayName: "Delete List",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                isRequired: false,
                variant: "toggle",
                sortOrder: 5,
            },
            {
                name: fields.addTagsButton,
                displayName: "Add Tags",
                editorTemplate: "CheckboxField",
                defaultValue: false,
                fieldType: "General",
                isRequired: false,
                variant: "toggle",
                sortOrder: 6,
            },
            {
                name: fields.editReminderButton,
                displayName: "Edit Reminder",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                isRequired: false,
                variant: "toggle",
                sortOrder: 7,
            },
            {
                name: fields.editListButton,
                displayName: "Edit List",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                isRequired: false,
                variant: "toggle",
                sortOrder: 8,
            },
            {
                name: fields.addListToCartButton,
                displayName: "Add List To Cart",
                editorTemplate: "CheckboxField",
                defaultValue: false,
                fieldType: "General",
                isRequired: false,
                variant: "toggle",
                sortOrder: 9,
            },
            {
                name: fields.hideButton,
                displayName: "Hide",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                isRequired: false,
                variant: "toggle",
                sortOrder: 10,
            },
            {
                name: fields.shareButton,
                displayName: "Share",
                editorTemplate: "CheckboxField",
                defaultValue: false,
                fieldType: "General",
                isRequired: false,
                variant: "toggle",
                sortOrder: 11,
            },
            {
                name: fields.removeSelectedButton,
                displayName: "Remove Selected",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                isRequired: false,
                variant: "toggle",
                sortOrder: 12,
            },
        ],
    },
};

export default widgetModule;
