import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import { VmiBinStateContext } from "@insite/client-framework/Store/Data/VmiBins/VmiBinsSelectors";
import addVmiCount from "@insite/client-framework/Store/Data/VmiCounts/Handlers/AddVmiCount";
import loadVmiCounts from "@insite/client-framework/Store/Data/VmiCounts/Handlers/LoadVmiCounts";
import { getVmiCountsDataView } from "@insite/client-framework/Store/Data/VmiCounts/VmiCountsSelectors";
import translate from "@insite/client-framework/Translate";
import WidgetModule from "@insite/client-framework/Types/WidgetModule";
import { BaseTheme } from "@insite/mobius/globals/baseTheme";
import GridContainer, { GridContainerProps } from "@insite/mobius/GridContainer";
import GridItem, { GridItemProps } from "@insite/mobius/GridItem";
import RefreshCw from "@insite/mobius/Icons/RefreshCw";
import Img, { ImgProps } from "@insite/mobius/Img";
import Link, { LinkPresentationProps } from "@insite/mobius/Link";
import TextField, { TextFieldPresentationProps } from "@insite/mobius/TextField";
import { HasToasterContext, withToaster } from "@insite/mobius/Toast/ToasterContext";
import Typography, { TypographyProps } from "@insite/mobius/Typography";
import breakpointMediaQueries from "@insite/mobius/utilities/breakpointMediaQueries";
import React, { useContext, useEffect, useState } from "react";
import { connect, ResolveThunks } from "react-redux";
import { css } from "styled-components";

const mapStateToProps = (state: ApplicationState) => {
    return {
        vmiCountsState: getVmiCountsDataView(state, state.pages.vmiBinDetails.getVmiCountsParameter),
        parameter: state.pages.vmiBinDetails.getVmiCountsParameter,
    };
};

const mapDispatchToProps = {
    loadVmiCounts,
    addVmiCount,
};

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

export interface VmiBinDetailsProductInfoStyles {
    container?: GridContainerProps;
    productImageGridItem?: GridItemProps;
    productImage?: ImgProps;
    productInfoGridItem?: GridItemProps;
    productInfoGroupContainer?: GridContainerProps;
    productInfoGroupGridItem?: GridItemProps;
    productInfoContainer?: GridContainerProps;
    productDetailsGridItem?: GridItemProps;
    productDetailsGridItemQty?: GridItemProps;
    productDetailsGridItemLink?: GridItemProps;
    productTitleText?: TypographyProps;
    productText?: TypographyProps;
    lastCountQtyTextField?: TextFieldPresentationProps;
    updateQtyLink?: LinkPresentationProps;
}

export const vmiBinDetailsProductInfoStyles: VmiBinDetailsProductInfoStyles = {
    container: {
        gap: 20,
        css: css`
            padding: 1rem 0;
        `,
    },
    productImageGridItem: {
        width: 2,
        css: css`
            ${({ theme }: { theme: BaseTheme }) =>
                breakpointMediaQueries(theme, [
                    css`
                        font-size: 10px;
                    `,
                    css`
                        font-size: 10px;
                    `,
                    css`
                        font-size: 10px;
                    `,
                    css`
                        font-size: 10px;
                    `,
                    null,
                ])}
        `,
    },
    productImage: {
        css: css`
            max-width: 145px;
            max-height: 145px;
        `,
    },
    productInfoGridItem: { width: [12, 12, 12, 10, 10] },
    productInfoGroupGridItem: { width: [12, 12, 12, 10, 10] },
    productInfoContainer: {
        offsetCss: css`
            flex-direction: row;
        `,
    },
    productDetailsGridItem: {
        width: [12, 6, 6, 3, 3],
        css: css`
            flex-direction: column;
        `,
    },
    productDetailsGridItemQty: {
        width: [6, 6, 6, 6, 2],
        css: css`
            flex-direction: row;
        `,
    },
    productDetailsGridItemLink: {
        width: [6, 6, 6, 6, 6],
        css: css`
            flex-direction: row;
            align-items: flex-end;
            margin-bottom: 10px !important;
        `,
    },
    updateQtyLink: {
        typographyProps: { size: 14 },
        icon: {
            iconProps: {
                src: RefreshCw,
                size: 14,
            },
        },
        css: css`
            margin: 1px 1px !important;
            white-space: nowrap;
        `,
    },
    productTitleText: {
        css: css`
            font-weight: 600;
        `,
    },
    productText: {
        css: css`
            width: 100%;
            word-wrap: break-word;
        `,
    },
};

const styles = vmiBinDetailsProductInfoStyles;

const VmiBinDetailsProductInfo = ({ parameter, vmiCountsState, toaster, addVmiCount, loadVmiCounts }: Props) => {
    const { value: vmiBin } = useContext(VmiBinStateContext);
    if (!vmiBin?.product) {
        return null;
    }

    const product = vmiBin.product;
    const [lastCountQtyValue, setLastCountQtyValue] = useState("0");
    const [updateLastCountLinkDisable, setUpdateLastCountLinkDisable] = useState(true);

    useEffect(() => {
        setLastCountQtyValue(vmiBin.lastCountQty.toString());
        if (!vmiCountsState.isLoading) {
            if (!parameter.vmiLocationId || !parameter.vmiBinId) {
                return;
            }

            loadVmiCounts(parameter);
        }
    }, [vmiBin.id]);

    const lastCountQtyValueChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
        setLastCountQtyValue(event.target.value);
        setUpdateLastCountLinkDisable(false);
    };

    const updateQty = () => {
        setUpdateLastCountLinkDisable(true);

        if (vmiBin) {
            addVmiCount({
                vmiLocationId: vmiBin.vmiLocationId,
                vmiBinId: vmiBin.id,
                binCount: {
                    count: +lastCountQtyValue || 0,
                    productId: vmiBin.productId,
                    vmiBinId: vmiBin.id,
                },
                onComplete: result => {
                    if (result.apiResult?.successful) {
                        toaster.addToast({
                            body: translate("Count QTY has been updated"),
                            messageType: "success",
                        });
                    } else if (result.apiResult?.errorMessage) {
                        toaster.addToast({ body: result.apiResult?.errorMessage, messageType: "danger" });
                    }
                },
            });
        }
    };

    return (
        <GridContainer {...styles.container}>
            <GridItem {...styles.productImageGridItem}>
                <Img {...styles.productImage} src={product.smallImagePath} altText={product.altText} />
            </GridItem>
            <GridItem {...styles.productInfoGridItem}>
                <GridContainer {...styles.productInfoGroupContainer}>
                    <GridItem {...styles.productInfoGroupGridItem}>
                        <GridContainer {...styles.productInfoContainer}>
                            <GridItem {...styles.productDetailsGridItemQty}>
                                <TextField
                                    {...styles.lastCountQtyTextField}
                                    type="number"
                                    min={0}
                                    max={999999}
                                    label={translate("QTY")}
                                    value={lastCountQtyValue}
                                    onChange={lastCountQtyValueChangeHandler}
                                />
                            </GridItem>
                            <GridItem {...styles.productDetailsGridItemLink}>
                                <Link
                                    {...styles.updateQtyLink}
                                    disabled={updateLastCountLinkDisable}
                                    onClick={() => updateQty()}
                                >
                                    {translate("Update QTY")}
                                </Link>
                            </GridItem>
                        </GridContainer>
                    </GridItem>
                    <GridItem {...styles.productInfoGroupGridItem}>
                        <GridContainer {...styles.productInfoContainer}>
                            <GridItem {...styles.productDetailsGridItem}>
                                <Typography {...styles.productTitleText}>{translate("Part #")}</Typography>
                                <Typography {...styles.productText}>{product.erpNumber}</Typography>
                            </GridItem>
                            <GridItem {...styles.productDetailsGridItem}>
                                <Typography {...styles.productTitleText}>{translate("My Part #")}</Typography>
                                <Typography {...styles.productText}>{product.customerName}</Typography>
                            </GridItem>
                            <GridItem {...styles.productDetailsGridItem}>
                                <Typography {...styles.productTitleText}>{translate("Manufacture Part #")}</Typography>
                                <Typography {...styles.productText}>{product.manufacturerItem}</Typography>
                            </GridItem>
                            {vmiBin.unitOfMeasure && (
                                <GridItem {...styles.productDetailsGridItem}>
                                    <Typography {...styles.productTitleText}>{translate("U/M")}</Typography>
                                    <Typography {...styles.productText}>{vmiBin.unitOfMeasureDisplay}</Typography>
                                </GridItem>
                            )}
                        </GridContainer>
                    </GridItem>
                    <GridItem {...styles.productInfoGroupGridItem}>
                        <GridContainer {...styles.productInfoContainer}>
                            <GridItem {...styles.productDetailsGridItem}>
                                <Typography {...styles.productTitleText}>{translate("Bin #")}</Typography>
                                <Typography {...styles.productText}>{vmiBin.binNumber}</Typography>
                            </GridItem>
                            <GridItem {...styles.productDetailsGridItem}>
                                <Typography {...styles.productTitleText}>{translate("Minimum Quantity")}</Typography>
                                <Typography {...styles.productText}>{vmiBin.minimumQty}</Typography>
                            </GridItem>
                            <GridItem {...styles.productDetailsGridItem}>
                                <Typography {...styles.productTitleText}>{translate("Maximum Quantity")}</Typography>
                                <Typography {...styles.productText}>{vmiBin.maximumQty}</Typography>
                            </GridItem>
                        </GridContainer>
                    </GridItem>
                </GridContainer>
            </GridItem>
        </GridContainer>
    );
};

const widgetModule: WidgetModule = {
    component: connect(mapStateToProps, mapDispatchToProps)(withToaster(VmiBinDetailsProductInfo)),
    definition: {
        allowedContexts: ["VmiBinDetailsPage"],
        group: "VMI Bin Details",
    },
};

export default widgetModule;
