import useAppDispatch from "@insite/client-framework/Common/Hooks/useAppDispatch";
import { API_URL_CURRENT_FRAGMENT } from "@insite/client-framework/Services/ApiService";
import {
    addCart,
    AddCartApiParameter,
    getCart,
    GetCartApiParameter,
} from "@insite/client-framework/Services/CartService";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import { getVmiBinState } from "@insite/client-framework/Store/Data/VmiBins/VmiBinsSelectors";
import { getVmiLocationState } from "@insite/client-framework/Store/Data/VmiLocations/VmiLocationsSelectors";
import addToCart from "@insite/client-framework/Store/Pages/Cart/Handlers/AddToCart";
import translate from "@insite/client-framework/Translate";
import addCartLineCollectionFromVmiBins from "@insite/client-framework/Store/Pages/OrderUpload/Handlers/AddCartLineCollectionFromVmiBins";
import {
    ProductDto,
    AttributeTypeDto,
    AvailabilityDto,
    BrandDto,
    LegacyConfigurationDto,
    DocumentDto,
    ProductPriceDto,
    ProductImageDto,
    ProductLineDto,
    ProductSubscriptionDto,
    ProductUnitOfMeasureDto,
    RelatedProductDto,
    ScoreExplanationDto,
    SpecificationDto,
    StyledProductDto,
    StyleTraitDto,
    WarehouseDto,
} from "@insite/client-framework/Types/ApiModels";
import Button, { ButtonProps } from "@insite/mobius/Button";
import GridContainer, { GridContainerProps } from "@insite/mobius/GridContainer";
import GridItem, { GridItemProps } from "@insite/mobius/GridItem";
import Modal from "@insite/mobius/Modal";
import TextField, { TextFieldProps } from "@insite/mobius/TextField";
import { HasToasterContext, withToaster } from "@insite/mobius/Toast/ToasterContext";
import Typography, { TypographyProps } from "@insite/mobius/Typography";
import React, { useState } from "react";
import { connect, ResolveThunks } from "react-redux";
import { css } from "styled-components";

interface OwnProps {
    isOpen?: boolean;
    vmiBinId?: string;
    onSuccess: () => void;
    onClose: () => void;
}
const mapStateToProps = (state: ApplicationState, props: OwnProps) => {
    const vmiBin = props.vmiBinId ? getVmiBinState(state, props.vmiBinId).value : null;
    const vmiLocation = vmiBin?.vmiLocationId ? getVmiLocationState(state, vmiBin.vmiLocationId).value : null;

    return {
        vmiBin,
        vmiLocation,
    };
};

const mapDispatchToProps = {
    addToCart,
};

export interface VmiAddToCartModalStyles {
    gridContainer: GridContainerProps;
    mainContentGridItem: GridItemProps;
    buttonsGridItem: GridItemProps;
    errorMessageGridItem: GridItemProps;
    qtyOrderedTextField: TextFieldProps;
    quantityConfirmationTypography?: TypographyProps;
    errorMessageTypography?: TypographyProps;
    cancelButton: ButtonProps;
    addToCartButton?: ButtonProps;
}

export const vmiAddToCartModalStyles: VmiAddToCartModalStyles = {
    gridContainer: {
        gap: 15,
    },
    mainContentGridItem: {
        width: 12,
    },
    buttonsGridItem: {
        width: 12,
        css: css`
            gap: 15px;
            justify-content: flex-end;
        `,
    },
    qtyOrderedTextField: {
        cssOverrides: {
            formField: css`
                width: auto;
            `,
        },
    },
    errorMessageGridItem: {
        width: 12,
    },
    errorMessageTypography: {
        color: "danger",
    },
    cancelButton: {
        variant: "secondary",
    },
};

const styles = vmiAddToCartModalStyles;

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

const VmiAddToCartModal = ({ vmiBin, vmiLocation, onClose, isOpen, addToCart, toaster }: Props) => {
    const dispatch = useAppDispatch();
    const [qtyOrderedValue, setQtyOrderedValue] = useState("1");
    const [errorMessage, setErrorMessage] = useState("");
    const [showQuantityConfirmation, setShowQuantityConfirmation] = useState(false);
    const [isMakingRequest, setIsMakingRequest] = useState(false);
    if (!vmiBin || !vmiLocation) {
        return null;
    }

    const resetForm = () => {
        setQtyOrderedValue("1");
        setErrorMessage("");
        setShowQuantityConfirmation(false);
    };

    const closeModalHandler = () => {
        resetForm();
        onClose();
    };

    const qtyOrderedValueChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
        setQtyOrderedValue(event.target.value);
    };

    const addToCartButtonClickHandler = async () => {
        const qtyOrderedValueAsNumber = Number(qtyOrderedValue);
        const quantityAfterOrdering = qtyOrderedValueAsNumber + vmiBin.lastCountQty;
        if (Number.isNaN(qtyOrderedValueAsNumber)) {
            setErrorMessage(translate("Order quantity must be numeric"));
            return;
        }

        if (vmiLocation.enforceMaxQuantityInOrders && quantityAfterOrdering > vmiBin.maximumQty) {
            setErrorMessage(
                translate(
                    "Max order quantity reached. Ordering over the max quantity is not permitted for this location.",
                ),
            );
            return;
        }
        if (quantityAfterOrdering >= vmiBin.maximumQty && !showQuantityConfirmation) {
            setShowQuantityConfirmation(true);
            return;
        }

        setIsMakingRequest(true);
        const product = {
            ...vmiBin.product,
            qtyOrdered: qtyOrderedValueAsNumber,
        };

        const vmiBinParameter = {
            ...vmiBin,
            product,
        };

        const onSuccess = () => {
            setIsMakingRequest(false);
            toaster.addToast({
                body: translate("Items added to cart"),
                messageType: "success",
            });
            closeModalHandler();
        };

        getCart({ cartId: API_URL_CURRENT_FRAGMENT } as GetCartApiParameter).then(result => {
            if (result.cart.status === "AlternateCart") {
                dispatch(
                    addCartLineCollectionFromVmiBins({
                        vmiBins: [vmiBinParameter],
                        onSuccess,
                    }),
                );
            } else {
                addCart({ vmiLocationId: vmiLocation.id } as AddCartApiParameter).then(() => {
                    dispatch(
                        addCartLineCollectionFromVmiBins({
                            vmiBins: [vmiBinParameter],
                            onSuccess,
                        }),
                    );
                });
            }
        });
    };

    var mainContent = (
        <>
            <TextField
                {...styles.qtyOrderedTextField}
                type="number"
                min={1}
                max={999999}
                label={translate("QTY")}
                value={qtyOrderedValue}
                onChange={qtyOrderedValueChangeHandler}
            />
        </>
    );
    if (showQuantityConfirmation) {
        mainContent = (
            <>
                <Typography {...styles.quantityConfirmationTypography}>
                    {translate("This item is at or above max quantity. Do you still want to add to cart?")}
                </Typography>
            </>
        );
    }

    return (
        <Modal
            handleClose={closeModalHandler}
            isOpen={isOpen}
            headline={showQuantityConfirmation ? translate("Max quantity reached") : translate("Select Quantity")}
        >
            <GridContainer {...styles.gridContainer}>
                <GridItem {...styles.mainContentGridItem}>{mainContent}</GridItem>
                {errorMessage && (
                    <GridItem {...styles.errorMessageGridItem}>
                        <Typography {...styles.errorMessageTypography}>{errorMessage}</Typography>
                    </GridItem>
                )}
                <GridItem {...styles.buttonsGridItem}>
                    <Button {...styles.cancelButton} type="button" onClick={closeModalHandler}>
                        {translate("Cancel")}
                    </Button>
                    <Button
                        disabled={isMakingRequest}
                        {...styles.addToCartButton}
                        onClick={addToCartButtonClickHandler}
                    >
                        {translate("Add to Cart")}
                    </Button>
                </GridItem>
            </GridContainer>
        </Modal>
    );
};

export default connect(mapStateToProps, mapDispatchToProps)(withToaster(VmiAddToCartModal));
