import StyledWrapper from "@insite/client-framework/Common/StyledWrapper";
import { makeHandlerChainAwaitable } from "@insite/client-framework/HandlerCreator";
import { API_URL_CURRENT_FRAGMENT } from "@insite/client-framework/Services/ApiService";
import {
    addCart,
    AddCartApiParameter,
    getCart,
    GetCartApiParameter,
} from "@insite/client-framework/Services/CartService";
import siteMessage from "@insite/client-framework/SiteMessage";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import { getSettingsCollection } from "@insite/client-framework/Store/Context/ContextSelectors";
import { getCurrentPage } from "@insite/client-framework/Store/Data/Pages/PageSelectors";
import { VmiBinsDataViewContext } from "@insite/client-framework/Store/Data/VmiBins/VmiBinsSelectors";
import addVmiCount from "@insite/client-framework/Store/Data/VmiCounts/Handlers/AddVmiCount";
import { getPageLinkByPageType } from "@insite/client-framework/Store/Links/LinksSelectors";
import addCartLineCollectionFromVmiBins from "@insite/client-framework/Store/Pages/OrderUpload/Handlers/AddCartLineCollectionFromVmiBins";
import selectVmiBinsChangedQty from "@insite/client-framework/Store/Pages/VmiBins/Handlers/HandleVmiBinsChangedQty";
import selectVmiBins from "@insite/client-framework/Store/Pages/VmiBins/Handlers/SelectVmiBins";
import setIsReorderConfirmationModalOpen from "@insite/client-framework/Store/Pages/VmiBins/Handlers/SetIsReorderConfirmationModalOpen";
import setNextPageUrl from "@insite/client-framework/Store/Pages/VmiBins/Handlers/SetNextPageUrl";
import updateSearchFields from "@insite/client-framework/Store/Pages/VmiBins/Handlers/UpdateSearchFields";
import { Actions } from "@insite/client-framework/Store/Pages/VmiBins/VmiBinsReducer";
import translate from "@insite/client-framework/Translate";
import { VmiBinModel } from "@insite/client-framework/Types/ApiModels";
import WidgetModule from "@insite/client-framework/Types/WidgetModule";
import WidgetProps from "@insite/client-framework/Types/WidgetProps";
import LocalizedDateTime from "@insite/content-library/Components/LocalizedDateTime";
import OrderDetailPageTypeLink from "@insite/content-library/Components/OrderDetailPageTypeLink";
import ProductAddedToCartMessage from "@insite/content-library/Components/ProductAddedToCartMessage";
import VmiAddProductModal from "@insite/content-library/Components/VmiAddProductModal";
import VmiBinDetailTypeLink from "@insite/content-library/Components/VmiBinDetailTypeLink";
import { BinsPageContext } from "@insite/content-library/Pages/VmiBinsPage";
import Checkbox, { CheckboxPresentationProps } from "@insite/mobius/Checkbox";
import DataTable, { DataTableProps, SortOrderOptions } from "@insite/mobius/DataTable";
import DataTableBody from "@insite/mobius/DataTable/DataTableBody";
import DataTableCell, { DataTableCellProps } from "@insite/mobius/DataTable/DataTableCell";
import DataTableHead from "@insite/mobius/DataTable/DataTableHead";
import DataTableHeader, { DataTableHeaderProps } from "@insite/mobius/DataTable/DataTableHeader";
import DataTableRow from "@insite/mobius/DataTable/DataTableRow";
import Link from "@insite/mobius/Link";
import LoadingSpinner, { LoadingSpinnerProps } from "@insite/mobius/LoadingSpinner";
import TextField, { TextFieldPresentationProps } from "@insite/mobius/TextField";
import { HasToasterContext, withToaster } from "@insite/mobius/Toast/ToasterContext";
import Tooltip, { TooltipPresentationProps } from "@insite/mobius/Tooltip";
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";

const enum fields {
    showShortDescription = "showShortDescription",
    showErpNumber = "showErpNumber",
    showManufacturerItem = "showManufacturerItem",
    showCustomerName = "showCustomerName",
    showUpcCode = "showUpcCode",
    showBinNumber = "showBinNumber",
    showMinimumQty = "showMinimumQty",
    showMaximumQty = "showMaximumQty",
    showLastCountQty = "showLastCountQty",
    showPreviousCountDate = "showPreviousCountDate",
    showPreviousCountQty = "showPreviousCountQty",
    showLastOrderLineId = "showLastOrderLineId",
}

export interface VmiBinsTableProps extends WidgetProps {
    fields: {
        [fields.showShortDescription]: boolean;
        [fields.showErpNumber]: boolean;
        [fields.showManufacturerItem]: boolean;
        [fields.showCustomerName]: boolean;
        [fields.showUpcCode]: boolean;
        [fields.showBinNumber]: boolean;
        [fields.showMinimumQty]: boolean;
        [fields.showMaximumQty]: boolean;
        [fields.showLastCountQty]: boolean;
        [fields.showPreviousCountDate]: boolean;
        [fields.showPreviousCountQty]: boolean;
        [fields.showLastOrderLineId]: boolean;
    };
}

const mapStateToProps = (state: ApplicationState) => {
    return {
        parameter: state.pages.vmiBins.getVmiBinsParameter,
        showAddToCartConfirmationDialog: getSettingsCollection(state).productSettings.showAddToCartConfirmationDialog,
        selectedIds: state.pages.vmiBins.selectedVmiBins,
        selectVmiBinsChangedQtyIds: state.pages.vmiBins.selectVmiBinsChangedQty,
        isRemoving: state.data.vmiBins.isRemoving,
        cartRequestInProcess: state.pages.vmiBins.cartRequestInProcess,
        isReorderConfirmationModalOpen: state.pages.vmiBins.isReorderConfirmationModalOpen,
        pageUrl: getPageLinkByPageType(state, "VmiBinsPage")?.url,
    };
};

const mapDispatchToProps = {
    updateSearchFields,
    selectVmiBins,
    selectVmiBinsChangedQty,
    addVmiCount,
    addCartLineCollectionFromVmiBins: makeHandlerChainAwaitable(addCartLineCollectionFromVmiBins),
    setIsReorderConfirmationModalOpen,
    setNextPageUrl,
};

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

export interface VmiBinsTableStyles {
    container?: InjectableCss;
    headerText?: TypographyProps;
    centeringWrapper?: InjectableCss;
    spinner?: LoadingSpinnerProps;
    noResultsContainer?: InjectableCss;
    noResultsText?: TypographyProps;

    checkboxHeader?: DataTableHeaderProps;
    nameHeader?: DataTableHeaderProps;
    erpNumberHeader?: DataTableHeaderProps;
    manufacturerItemHeader?: DataTableHeaderProps;
    customerNameHeader?: DataTableHeaderProps;
    binNumberHeader?: DataTableHeaderProps;
    minimumQtyHeader?: DataTableHeaderProps;
    maximumQtyHeader?: DataTableHeaderProps;
    lastCountQtyHeader?: DataTableHeaderProps;
    previousCountDateHeader?: DataTableHeaderProps;
    previousCountQtyHeader?: DataTableHeaderProps;
    previousOrderHeader?: DataTableHeaderProps;
    /** @deprecated Not used anywhere */
    actionsHeader?: DataTableHeaderProps;
    tooltipHeader?: DataTableHeaderProps;

    checkboxCells?: DataTableCellProps;
    nameCells?: DataTableCellProps;
    erpNumberCells?: DataTableCellProps;
    manufacturerItemCells?: DataTableCellProps;
    customerNameCells?: DataTableCellProps;
    upcCodeCells?: DataTableCellProps;
    binNumberCells?: DataTableCellProps;
    minimumQtyCells?: DataTableCellProps;
    maximumQtyCells?: DataTableCellProps;
    lastCountQtyCells?: DataTableCellProps;
    lastCountQtyText?: TextFieldPresentationProps;
    previousCountDateCells?: DataTableCellProps;
    previousCountQtyCells?: DataTableCellProps;
    previousOrderCells?: DataTableCellProps;
    actionsCells?: DataTableCellProps;
    vmiBinsTooltip?: TooltipPresentationProps;

    dataTable?: DataTableProps;
    binCheckbox?: CheckboxPresentationProps;
}

export const vmiBinsTableStyles: VmiBinsTableStyles = {
    container: {
        css: css`
            overflow: auto;
        `,
    },
    centeringWrapper: {
        css: css`
            height: 300px;
            display: flex;
            align-items: center;
        `,
    },
    spinner: {
        css: css`
            margin: auto;
        `,
    },
    noResultsContainer: {
        css: css`
            text-align: center;
            padding: 20px;
        `,
    },
    noResultsText: {
        variant: "h4",
    },
    erpNumberHeader: {
        tight: true,
    },
    checkboxHeader: {
        tight: true,
    },
    tooltipHeader: {
        css: css`
            text-align: right;
        `,
    },
    nameCells: {
        css: css`
            max-width: 330px;
            a {
                text-overflow: ellipsis;
                overflow: hidden;
                display: block;
            }
        `,
    },

    vmiBinsTooltip: {
        cssOverrides: {
            tooltipWrapper: css`
                margin-left: 5px;
            `,
            tooltipContainer: css`
                width: 340px;
                margin-left: -115px;
                bottom: auto;
                left: -65px;
                top: 0;
            `,
            tooltipBody: css`
                width: 100%;
                padding: 5px;
                text-wrap: pretty;
                font-weight: normal;
                text-align: left;
            `,
            tooltipArrow: css`
                top: 15%;
                left: 100%;
                -webkit-transform: rotate(-90deg);
            `,
        },
        typographyProps: {
            lineHeight: "16px",
        },
    },

    lastCountQtyText: {
        css: css`
            border: 2px solid blue !important;
        `,
    },
};

const styles = vmiBinsTableStyles;

class VmiBinsTable extends React.Component<
    Props,
    {
        isAddBinModalOpen: boolean;
        vmiBinId?: string;
    }
> {
    static contextType = VmiBinsDataViewContext;
    context!: React.ContextType<typeof VmiBinsDataViewContext>;

    state = {
        isAddBinModalOpen: false,
        vmiBinId: undefined,
    };

    componentDidMount() {
        document.addEventListener("mousedown", this.handleMouseDown);
    }

    componentWillUnmount() {
        document.removeEventListener("mousedown", this.handleMouseDown);
    }

    handleMouseDown = (event: any) => {
        if (event.button !== 0) {
            return;
        }

        // handle if click on a tag to redirect to other page
        const nextPageUrl = event.target.closest("a")?.href?.replace(window.location.origin, "");
        if (
            !this.props.isReorderConfirmationModalOpen &&
            this.props.selectVmiBinsChangedQtyIds &&
            Object.keys(this.props.selectVmiBinsChangedQtyIds).length > 0 &&
            nextPageUrl &&
            nextPageUrl !== this.props.pageUrl
        ) {
            event.preventDefault();
            this.props.setIsReorderConfirmationModalOpen({
                isReorderConfirmationModalOpen: true,
            });
            this.props.setNextPageUrl({
                nextPageUrl,
            });
        }
    };

    headerClick(sortField: string) {
        const sort = this.props.parameter.sort === sortField ? `${sortField} DESC` : sortField;
        this.props.updateSearchFields({ sort, page: 1 });
    }

    sorted = (sortField: string) => {
        let sorted: boolean | string = false;
        if (this.props.parameter.sort === sortField) {
            sorted = "ascending";
        } else if (this.props.parameter.sort === `${sortField} DESC`) {
            sorted = "descending";
        }
        return sorted as SortOrderOptions;
    };

    binChangeHandler = (value: boolean, id?: string) => {
        if (id) {
            this.props.selectVmiBins({ ids: [id] });
        } else {
            let ids = [];
            if (value) {
                const vmiBinsDataView = this.context;
                if (!vmiBinsDataView.value) {
                    return;
                }
                for (const row of vmiBinsDataView.value) {
                    if (!this.props.selectedIds[row.id]) {
                        ids.push(row.id);
                    }
                }
            } else {
                ids = Object.keys(this.props.selectedIds);
            }

            this.props.selectVmiBins({ ids });
        }
    };

    addBinClickHandler = (vmiBinId: string) => {
        this.setState({ isAddBinModalOpen: true, vmiBinId });
    };

    reorderClickHandler = (vmiLocationId: string, vmiBin: VmiBinModel) => {
        const product = {
            ...vmiBin.product,
            qtyOrdered: vmiBin.maximumQty > vmiBin.lastCountQty ? vmiBin.maximumQty - vmiBin.lastCountQty : 1,
        };

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

        this.updateCart(vmiLocationId, newVmiBin);
        this.props.selectVmiBinsChangedQty({ ids: [vmiBin.id], action: Actions[Actions.Remove] });
    };

    updateCart = (locationId: string, vmiBin: VmiBinModel) => {
        getCart({ cartId: API_URL_CURRENT_FRAGMENT } as GetCartApiParameter).then(result => {
            if (result.cart.status === "AlternateCart") {
                this.props.addCartLineCollectionFromVmiBins({ vmiBins: [vmiBin] }).then(() => {
                    this.showNotification();
                });
            } else {
                addCart({ vmiLocationId: locationId } as AddCartApiParameter).then(() => {
                    getCart({ cartId: API_URL_CURRENT_FRAGMENT } as GetCartApiParameter).then(() => {
                        this.props.addCartLineCollectionFromVmiBins({ vmiBins: [vmiBin] }).then(() => {
                            this.showNotification();
                        });
                    });
                });
            }
        });
    };

    showNotification = () => {
        this.props.toaster.addToast({
            body: <ProductAddedToCartMessage isQtyAdjusted={false} multipleProducts={false} />,
            messageType: "success",
        });
    };

    onSuccessAddProductModal = () => {
        this.setState({ isAddBinModalOpen: false });
    };

    onCloseAddProductModal = () => {
        this.setState({ isAddBinModalOpen: false });
    };

    handleLastCountQtyOnBlur = (
        event: React.ChangeEvent<HTMLInputElement>,
        vmiBinId?: string,
        vmiLocationid?: string,
        productId?: string,
        defaultValue?: string,
    ) => {
        if (event.currentTarget.value === "") {
            event.currentTarget.value = defaultValue ?? "";
        } else if (event.currentTarget.value !== defaultValue) {
            const newLastCountQty = Number(event.currentTarget.value);
            if (newLastCountQty < 0 || newLastCountQty > 999999) {
                event.currentTarget.value = defaultValue ?? "";
                return;
            }

            this.props.addVmiCount({
                vmiLocationId: vmiLocationid,
                vmiBinId: vmiBinId!,
                binCount: {
                    count: newLastCountQty,
                    productId: productId!,
                    vmiBinId: vmiBinId!,
                },
                onComplete: result => {
                    if (result.apiResult?.successful) {
                        this.setState({ vmiBinId: vmiBinId! });
                    } else if (result.apiResult?.errorMessage) {
                        this.props.selectVmiBinsChangedQty({ ids: [vmiBinId!], action: Actions[Actions.Remove] });
                        this.props.toaster.addToast({ body: result.apiResult?.errorMessage, messageType: "danger" });
                    }
                },
            });
        }
    };

    onChangeLastCountQty = (value: string, lastCountQty: number, vmiBinId: string) => {
        if (value !== lastCountQty.toString()) {
            this.props.selectVmiBinsChangedQty({ ids: [vmiBinId], action: Actions[Actions.Add] });
        }
    };

    render() {
        const vmiBinsDataView = this.context;

        if (vmiBinsDataView.isLoading || this.props.isRemoving || this.props.cartRequestInProcess) {
            return (
                <StyledWrapper {...styles.centeringWrapper}>
                    <LoadingSpinner {...styles.spinner} />
                </StyledWrapper>
            );
        }

        if (!vmiBinsDataView.value) {
            return null;
        }

        if (vmiBinsDataView.value.length === 0) {
            if (this.props.parameter.page && this.props.parameter.page > 1) {
                this.props.updateSearchFields({ page: this.props.parameter.page - 1 });
                return null;
            }

            return (
                <StyledWrapper {...styles.noResultsContainer}>
                    <Typography as="p" {...styles.noResultsText}>
                        {translate("No products found")}
                    </Typography>
                </StyledWrapper>
            );
        }

        const rows = vmiBinsDataView.value;

        return (
            <>
                <StyledWrapper {...styles.container}>
                    <DataTable {...styles.dataTable}>
                        <DataTableHead>
                            <DataTableHeader {...styles.checkboxHeader}>
                                <Checkbox
                                    {...styles.binCheckbox}
                                    checked={Object.keys(this.props.selectedIds).length === rows.length}
                                    onChange={(e, value) => this.binChangeHandler(value)}
                                />
                            </DataTableHeader>
                            {this.props.fields.showLastCountQty && (
                                <DataTableHeader
                                    {...styles.lastCountQtyHeader}
                                    sorted={this.sorted("lastCountQty")}
                                    onSortClick={() => this.headerClick("lastCountQty")}
                                >
                                    {translate("Current QTY")}
                                </DataTableHeader>
                            )}
                            <DataTableHeader
                                {...styles.nameHeader}
                                title={translate("Product Name")}
                                sorted={this.sorted("product.shortDescription")}
                                onSortClick={() => this.headerClick("product.shortDescription")}
                            >
                                {translate("Product Name")}
                            </DataTableHeader>
                            <DataTableHeader
                                {...styles.erpNumberHeader}
                                sorted={this.sorted("product.erpNumber")}
                                onSortClick={() => this.headerClick("product.erpNumber")}
                            >
                                {translate("Part #")}
                            </DataTableHeader>
                            {this.props.fields.showManufacturerItem && (
                                <DataTableHeader
                                    {...styles.manufacturerItemHeader}
                                    sorted={this.sorted("product.manufacturerItem")}
                                    onSortClick={() => this.headerClick("product.manufacturerItem")}
                                >
                                    {translate("Manufacture #")}
                                </DataTableHeader>
                            )}
                            {this.props.fields.showCustomerName && (
                                <DataTableHeader
                                    {...styles.customerNameHeader}
                                    sorted={this.sorted("product.customerName")}
                                    onSortClick={() => this.headerClick("product.customerName")}
                                >
                                    {translate("My Part #")}
                                </DataTableHeader>
                            )}
                            {this.props.fields.showUpcCode && (
                                <DataTableHeader
                                    {...styles.customerNameHeader}
                                    sorted={this.sorted("product.upcCode")}
                                    onSortClick={() => this.headerClick("product.upcCode")}
                                >
                                    {translate("UPC Code")}
                                </DataTableHeader>
                            )}
                            {this.props.fields.showBinNumber && (
                                <DataTableHeader
                                    {...styles.binNumberHeader}
                                    sorted={this.sorted("binNumber")}
                                    onSortClick={() => this.headerClick("binNumber")}
                                >
                                    {translate("Bin #")}
                                </DataTableHeader>
                            )}
                            <DataTableHeader
                                {...styles.minimumQtyHeader}
                                sorted={this.sorted("minimumQty")}
                                onSortClick={() => this.headerClick("minimumQty")}
                            >
                                {translate("Min")}
                            </DataTableHeader>
                            <DataTableHeader
                                {...styles.maximumQtyHeader}
                                sorted={this.sorted("maximumQty")}
                                onSortClick={() => this.headerClick("maximumQty")}
                            >
                                {translate("Max")}
                            </DataTableHeader>
                            {this.props.fields.showPreviousCountDate && (
                                <DataTableHeader
                                    {...styles.previousCountDateHeader}
                                    sorted={this.sorted("previousCountDate")}
                                    onSortClick={() => this.headerClick("previousCountDate")}
                                >
                                    {translate("Prev. Count Date")}
                                </DataTableHeader>
                            )}
                            {this.props.fields.showPreviousCountQty && (
                                <DataTableHeader
                                    {...styles.previousCountQtyHeader}
                                    sorted={this.sorted("previousCountQty")}
                                    onSortClick={() => this.headerClick("previousCountQty")}
                                >
                                    {translate("Prev. Count QTY")}
                                </DataTableHeader>
                            )}
                            {this.props.fields.showLastOrderLineId && (
                                <DataTableHeader
                                    {...styles.previousOrderHeader}
                                    sorted={this.sorted("lastOrderLineId")}
                                    onSortClick={() => this.headerClick("lastOrderLineId")}
                                >
                                    {translate("Previous Order")}
                                </DataTableHeader>
                            )}
                            <DataTableHeader {...styles.tooltipHeader}>
                                <Tooltip
                                    {...styles.vmiBinsTooltip}
                                    text={siteMessage("Vmi_Product_Reorder_Tooltip") as string}
                                />
                            </DataTableHeader>
                        </DataTableHead>
                        <DataTableBody>
                            {rows.map(
                                (
                                    {
                                        id,
                                        vmiLocationId,
                                        product,
                                        binNumber,
                                        minimumQty,
                                        maximumQty,
                                        lastCountQty,
                                        previousCountDate,
                                        previousCountQty,
                                        lastOrderErpOrderNumber,
                                        lastOrderWebOrderNumber,
                                        productId,
                                    },
                                    index,
                                ) => (
                                    <DataTableRow key={id}>
                                        <DataTableCell {...styles.checkboxCells}>
                                            <Checkbox
                                                {...styles.binCheckbox}
                                                checked={this.props.selectedIds[id]}
                                                onChange={(e, value) => this.binChangeHandler(value, id)}
                                            />
                                        </DataTableCell>
                                        {this.props.fields.showLastCountQty && (
                                            <DataTableCell {...styles.lastCountQtyCells}>
                                                <TextField
                                                    {...(this.props.selectVmiBinsChangedQtyIds &&
                                                    this.props.selectVmiBinsChangedQtyIds[id] &&
                                                    this.props.isReorderConfirmationModalOpen
                                                        ? styles.lastCountQtyText
                                                        : "")}
                                                    type="number"
                                                    min={0}
                                                    max={999999}
                                                    maxLength={6}
                                                    defaultValue={lastCountQty}
                                                    onBlur={event =>
                                                        this.handleLastCountQtyOnBlur(
                                                            event,
                                                            id,
                                                            vmiLocationId,
                                                            productId,
                                                            lastCountQty.toString(),
                                                        )
                                                    }
                                                    onChange={event =>
                                                        this.onChangeLastCountQty(
                                                            event.currentTarget.value,
                                                            lastCountQty,
                                                            id,
                                                        )
                                                    }
                                                />
                                            </DataTableCell>
                                        )}
                                        <DataTableCell {...styles.nameCells}>
                                            <VmiBinDetailTypeLink
                                                title={product.shortDescription}
                                                locationId={vmiLocationId}
                                                id={id}
                                            />
                                        </DataTableCell>
                                        <DataTableCell {...styles.erpNumberCells}>{product.erpNumber}</DataTableCell>
                                        {this.props.fields.showManufacturerItem && (
                                            <DataTableCell {...styles.manufacturerItemCells}>
                                                {product.manufacturerItem}
                                            </DataTableCell>
                                        )}
                                        {this.props.fields.showCustomerName && (
                                            <DataTableCell {...styles.customerNameCells}>
                                                {product.customerName}
                                            </DataTableCell>
                                        )}
                                        {this.props.fields.showUpcCode && (
                                            <DataTableCell {...styles.upcCodeCells}>{product.upcCode}</DataTableCell>
                                        )}
                                        {this.props.fields.showBinNumber && (
                                            <DataTableCell {...styles.binNumberCells}>{binNumber}</DataTableCell>
                                        )}
                                        <DataTableCell {...styles.minimumQtyCells}>{minimumQty}</DataTableCell>
                                        <DataTableCell {...styles.maximumQtyCells}>{maximumQty}</DataTableCell>
                                        {this.props.fields.showPreviousCountDate && (
                                            <DataTableCell {...styles.previousCountDateCells}>
                                                <LocalizedDateTime dateTime={previousCountDate} />
                                            </DataTableCell>
                                        )}
                                        {this.props.fields.showPreviousCountQty && (
                                            <DataTableCell {...styles.previousCountQtyCells}>
                                                {previousCountQty}
                                            </DataTableCell>
                                        )}
                                        {this.props.fields.showLastOrderLineId && (
                                            <DataTableCell {...styles.previousOrderCells}>
                                                {(lastOrderErpOrderNumber || lastOrderWebOrderNumber) && (
                                                    <OrderDetailPageTypeLink
                                                        title={lastOrderErpOrderNumber || lastOrderWebOrderNumber}
                                                        orderNumber={lastOrderErpOrderNumber || lastOrderWebOrderNumber}
                                                    />
                                                )}
                                            </DataTableCell>
                                        )}
                                        <DataTableCell {...styles.actionsCells}>
                                            <Link onClick={() => this.reorderClickHandler(vmiLocationId, rows[index])}>
                                                {translate("Reorder")}
                                            </Link>
                                        </DataTableCell>
                                    </DataTableRow>
                                ),
                            )}
                        </DataTableBody>
                    </DataTable>
                </StyledWrapper>
                <VmiAddProductModal
                    isOpen={this.state.isAddBinModalOpen}
                    vmiBinId={this.state.vmiBinId}
                    onSuccess={this.onSuccessAddProductModal}
                    onClose={this.onCloseAddProductModal}
                />
            </>
        );
    }
}

const widgetModule: WidgetModule = {
    component: connect(mapStateToProps, mapDispatchToProps)(withToaster(withHistory(VmiBinsTable))),
    definition: {
        group: "VMI Bins",
        displayName: "Search Results Table",
        allowedContexts: [BinsPageContext],
        fieldDefinitions: [
            {
                name: fields.showShortDescription,
                displayName: "Product Name",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                isEnabled: () => false,
                fieldType: "General",
                sortOrder: 0,
            },
            {
                name: fields.showErpNumber,
                displayName: "Part #",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                isEnabled: () => false,
                fieldType: "General",
                sortOrder: 1,
            },
            {
                name: fields.showManufacturerItem,
                displayName: "Manufacture #",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                sortOrder: 2,
            },
            {
                name: fields.showCustomerName,
                displayName: "My Part #",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                sortOrder: 3,
            },
            {
                name: fields.showUpcCode,
                displayName: "UPC Code",
                editorTemplate: "CheckboxField",
                defaultValue: false,
                fieldType: "General",
                sortOrder: 4,
            },
            {
                name: fields.showBinNumber,
                displayName: "Bin #",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                sortOrder: 5,
            },
            {
                name: fields.showMinimumQty,
                displayName: "Min",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                isEnabled: () => false,
                fieldType: "General",
                sortOrder: 6,
            },
            {
                name: fields.showMaximumQty,
                displayName: "Max",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                isEnabled: () => false,
                fieldType: "General",
                sortOrder: 7,
            },
            {
                name: fields.showLastCountQty,
                displayName: "Current QTY",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                sortOrder: 8,
            },
            {
                name: fields.showPreviousCountDate,
                displayName: "Previous Count Date",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                sortOrder: 9,
            },
            {
                name: fields.showPreviousCountQty,
                displayName: "Previous Count Quantity",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                sortOrder: 10,
            },
            {
                name: fields.showLastOrderLineId,
                displayName: "Previous Order",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                sortOrder: 11,
            },
        ],
    },
};

export default widgetModule;
