import { SafeDictionary } from "@insite/client-framework/Common/Types";
import getLocalizedDateTime from "@insite/client-framework/Common/Utilities/getLocalizedDateTime";
import { createHandlerChainRunner, Handler } from "@insite/client-framework/HandlerCreator";
import { getVmiBins } from "@insite/client-framework/Services/VmiBinsService";
import { getVmiBinsDataView } from "@insite/client-framework/Store/Data/VmiBins/VmiBinsSelectors";
import { getPageLinkByPageType } from "@insite/client-framework/Store/Links/LinksSelectors";
import translate from "@insite/client-framework/Translate";
import { VmiBinModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = Handler<{
    ids: SafeDictionary<boolean>;
}>;

export const DispatchBeginExportVmiProducts: HandlerType = props => {
    props.dispatch({
        type: "Pages/VmiBins/BeginExportVmiProducts",
    });
};

export const ExportData: HandlerType = async props => {
    const { unparse } = await import(/* webpackChunkName: "papaparse" */ "papaparse");

    const data = [];
    const state = props.getState();
    const language = state.context.session.language;
    const url: { protocol: string; host: string } = window.location;
    const authority = `${url.protocol}//${url.host}`;
    const orderDetailsPageLink = getPageLinkByPageType(state, "OrderDetailsPage");

    const prepareData = (row: VmiBinModel) => {
        const orderNumber = row.lastOrderErpOrderNumber || row.lastOrderWebOrderNumber;
        const data: (string | number | null | undefined)[] = [
            row.product.shortDescription,
            row.product.erpNumber,
            row.product.manufacturerItem,
            row.product.customerName,
            row.product.upcCode,
            row.binNumber,
            row.minimumQty,
            row.maximumQty,
            row.previousCountDate &&
                getLocalizedDateTime({
                    dateTime: new Date(row.previousCountDate),
                    language,
                }),
            row.previousCountQty,
            orderDetailsPageLink && orderNumber && `${authority}${orderDetailsPageLink.url}?orderNumber=${orderNumber}`,
            row.product.largeImagePath || "",
        ];

        return data;
    };

    if (Object.keys(props.parameter.ids).length) {
        const vmiBinsDataView = getVmiBinsDataView(state, state.pages.vmiBins.getVmiBinsParameter);
        if (vmiBinsDataView.value) {
            for (const row of vmiBinsDataView.value) {
                if (props.parameter.ids[row.id]) {
                    data.push(prepareData(row));
                }
            }
        }
    } else {
        const result = await getVmiBins({
            ...state.pages.vmiBins.getVmiBinsParameter,
            page: 1,
            pageSize: 9999,
            expand: ["product"],
        });
        if (result.vmiBins) {
            for (const row of result.vmiBins) {
                data.push(prepareData(row));
            }
        }
    }

    const documentData = {
        fields: [
            translate("Product Name"),
            translate("Part #"),
            translate("Manufacture #"),
            translate("My Part #"),
            translate("UPC Code"),
            translate("Bin #"),
            translate("Min"),
            translate("Max"),
            translate("Previous Count Date"),
            translate("Previous Count Quantity"),
            translate("Previous Order"),
            translate("Image Source URL"),
        ].filter(o => o),
        data,
    };

    const csv = unparse(documentData);
    const csvBlob = new Blob([`\uFEFF${csv}`], { type: "text/csv;charset=utf-8;" });

    const fileName = `products_table.csv`;
    const downloadLink = document.createElement("a");
    downloadLink.href = window.URL.createObjectURL(csvBlob);
    downloadLink.setAttribute("download", fileName);
    downloadLink.click();
};

export const DispatchCompleteExportVmiProducts: HandlerType = props => {
    props.dispatch({
        type: "Pages/VmiBins/CompleteExportVmiProducts",
    });
};

export const chain = [DispatchBeginExportVmiProducts, ExportData, DispatchCompleteExportVmiProducts];

const exportVmiProducts = createHandlerChainRunner(chain, "ExportVmiProducts");
export default exportVmiProducts;
