import { getCookie } from "@insite/client-framework/Common/Cookies";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import loadOrders from "@insite/client-framework/Store/Data/Orders/Handlers/LoadOrders";
import { getOrdersDataView } from "@insite/client-framework/Store/Data/Orders/OrdersSelectors";
import loadVmiBins from "@insite/client-framework/Store/Data/VmiBins/Handlers/LoadVmiBins";
import { getVmiBinsDataView } from "@insite/client-framework/Store/Data/VmiBins/VmiBinsSelectors";
import { VmiLocationStateContext } from "@insite/client-framework/Store/Data/VmiLocations/VmiLocationsSelectors";
import resetVmiItemsSelection from "@insite/client-framework/Store/Pages/VmiLocationDetails/Handlers/ResetVmiItemsSelection";
import updateOrderSearchFields from "@insite/client-framework/Store/Pages/VmiLocationDetails/Handlers/UpdateOrderSearchFields";
import updateProductSearchFields from "@insite/client-framework/Store/Pages/VmiLocationDetails/Handlers/UpdateProductSearchFields";
import { TableTabKeys } from "@insite/client-framework/Store/Pages/VmiLocationDetails/VmiLocationDetailsReducer";
import translate from "@insite/client-framework/Translate";
import WidgetModule from "@insite/client-framework/Types/WidgetModule";
import WidgetProps from "@insite/client-framework/Types/WidgetProps";
import VmiLocationOrdersTab from "@insite/content-library/Components/VmiLocationOrdersTab";
import VmiLocationProductsTab from "@insite/content-library/Components/VmiLocationProductsTab";
import Tab, { TabPresentationProps } from "@insite/mobius/Tab";
import TabGroup from "@insite/mobius/TabGroup";
import { HasToasterContext, withToaster } from "@insite/mobius/Toast/ToasterContext";
import { HasHistory, withHistory } from "@insite/mobius/utilities/HistoryContext";
import * as React from "react";
import { useContext, useEffect, useState } 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",
    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.showPreviousCountDate]: boolean;
        [fields.showPreviousCountQty]: boolean;
        [fields.showLastOrderLineId]: boolean;
    };
}

const mapStateToProps = (state: ApplicationState) => {
    return {
        getVmiBinsParameter: state.pages.vmiLocationDetails.getVmiBinsParameter,
        vmiBinsDataView: getVmiBinsDataView(state, state.pages.vmiLocationDetails.getVmiBinsParameter),
        getVmiOrdersParameter: state.pages.vmiLocationDetails.getVmiOrdersParameter,
        vmiOrdersDataView: getOrdersDataView(state, state.pages.vmiLocationDetails.getVmiOrdersParameter),
    };
};

const mapDispatchToProps = {
    updateProductSearchFields,
    loadVmiBins,
    updateOrderSearchFields,
    loadOrders,
    resetVmiItemsSelection,
};

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

export interface VmiLocationDetailsTabbedTableStyles {
    tabContainer?: TabPresentationProps;
}

export const vmiLocationDetailsTabbedTableStyles: VmiLocationDetailsTabbedTableStyles = {
    tabContainer: {
        css: css`
            text-transform: capitalize;
        `,
    },
};

const styles = vmiLocationDetailsTabbedTableStyles;

const VmiLocationDetailsTabbedTable = ({
    getVmiBinsParameter,
    vmiBinsDataView,
    updateProductSearchFields,
    loadVmiBins,
    getVmiOrdersParameter,
    vmiOrdersDataView,
    fields,
    updateOrderSearchFields,
    loadOrders,
    resetVmiItemsSelection,
}: Props) => {
    const [currentTab, setCurrentTab] = useState(TableTabKeys.Products);

    const { value: vmiLocation } = useContext(VmiLocationStateContext);

    useEffect(() => {
        if (vmiLocation) {
            loadData(currentTab);
        }

        document.body.style.overflowX = "hidden";
        return () => {
            document.body.style.overflowX = "auto";
        };
    });

    if (!vmiLocation) {
        return null;
    }

    const loadData = (currentTab: string) => {
        if (currentTab === TableTabKeys.Products) {
            if (getVmiBinsParameter.vmiLocationId !== vmiLocation.id) {
                updateProductSearchFields({ vmiLocationId: vmiLocation.id });
                return;
            }
            if (!vmiBinsDataView.value && !vmiBinsDataView.isLoading) {
                const pageSizeCookie = getCookie("VmiBins-PageSize");
                const pageSize = pageSizeCookie ? parseInt(pageSizeCookie, 10) : undefined;
                if (pageSize && pageSize !== getVmiBinsParameter.pageSize) {
                    updateProductSearchFields({ pageSize });
                    return;
                }
                loadVmiBins(getVmiBinsParameter);
            }
        } else if (currentTab === TableTabKeys.Users) {
            // not implemented yet
        } else if (currentTab === TableTabKeys.Orders) {
            if (getVmiOrdersParameter.vmiLocationId !== vmiLocation.id) {
                updateOrderSearchFields({ vmiLocationId: vmiLocation.id });
                return;
            }
            if (!vmiOrdersDataView.value && !vmiOrdersDataView.isLoading) {
                const pageSizeCookie = getCookie("VmiOrders-PageSize");
                const pageSize = pageSizeCookie ? parseInt(pageSizeCookie, 10) : undefined;
                if (pageSize && pageSize !== getVmiOrdersParameter.pageSize) {
                    updateOrderSearchFields({ pageSize });
                    return;
                }
                loadOrders({
                    ...getVmiOrdersParameter,
                    onComplete: () => {
                        resetVmiItemsSelection({ tabKey: TableTabKeys.Orders });
                    },
                });
            }
        }
    };

    const onTabChange = (event: React.MouseEvent | React.KeyboardEvent, tabKey?: string) => {
        if (tabKey) {
            loadData(tabKey);
            setCurrentTab(tabKey as TableTabKeys);
        }
    };

    return (
        <TabGroup current={currentTab} onTabChange={onTabChange}>
            <Tab
                {...styles.tabContainer}
                headline={translate("Products")}
                key={TableTabKeys.Products}
                tabKey={TableTabKeys.Products}
            >
                <VmiLocationProductsTab
                    vmiLocationId={vmiLocation.id}
                    showManufacturerItem={fields.showManufacturerItem}
                    showCustomerName={fields.showCustomerName}
                    showUpcCode={fields.showUpcCode}
                    showBinNumber={fields.showBinNumber}
                    showPreviousCountDate={fields.showPreviousCountDate}
                    showPreviousCountQty={fields.showPreviousCountQty}
                    showLastOrderLineId={fields.showLastOrderLineId}
                />
            </Tab>
            <Tab
                {...styles.tabContainer}
                headline={translate("orders")}
                key={TableTabKeys.Orders}
                tabKey={TableTabKeys.Orders}
            >
                <VmiLocationOrdersTab />
            </Tab>
        </TabGroup>
    );
};

const widgetModule: WidgetModule = {
    component: connect(mapStateToProps, mapDispatchToProps)(withToaster(withHistory(VmiLocationDetailsTabbedTable))),
    definition: {
        group: "VMI Location Details",
        displayName: "VMI Location Tabbed Table",
        allowedContexts: ["VmiLocationDetailsPage"],
        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.showPreviousCountDate,
                displayName: "Previous Count Date",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                sortOrder: 8,
            },
            {
                name: fields.showPreviousCountQty,
                displayName: "Previous Count Quantity",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                sortOrder: 9,
            },
            {
                name: fields.showLastOrderLineId,
                displayName: "Previous Order",
                editorTemplate: "CheckboxField",
                defaultValue: true,
                fieldType: "General",
                sortOrder: 10,
            },
        ],
    },
};

export default widgetModule;
