import { createHandlerChainRunner, HandlerWithResult } from "@insite/client-framework/HandlerCreator";
import { API_URL_CURRENT_FRAGMENT, ServiceResult } from "@insite/client-framework/Services/ApiService";
import { getBillTo } from "@insite/client-framework/Services/CustomersService";
import {
    batchCreateVmiLocations,
    BatchCreateVmiLocationsApiParameter,
    getVmiLocations,
    GetVmiLocationsApiParameter,
} from "@insite/client-framework/Services/VmiLocationService";
import {
    ParsedItem,
    VmiLocationUploadRowError,
} from "@insite/client-framework/Store/Components/VmiLocationsImportModal/VmiLocationsImportModalState";
import { BillToModel, VmiLocationCollectionModel, VmiLocationModel } from "@insite/client-framework/Types/ApiModels";

export const enum VmiLocationUploadError {
    None,
    NoBillTo,
    BillToNotFound,
    NoShipTo,
    ShipToNotFound,
    NoLocationName,
    DuplicateLocationName,
    DuplicateLocationNameSameFile,
    LocationNameTooLong,
}

export interface BatchCreateVmiLocationsParameter {
    firstRowHeading: boolean;
    validationOnly: boolean;
}

export interface BatchCreateVmiLocationsResult {
    apiParameter: BatchCreateVmiLocationsApiParameter;
    apiResult: ServiceResult<VmiLocationCollectionModel>;
    vmiLocations: VmiLocationModel[];
    errorEntries: VmiLocationUploadRowError[];
    importedItems: VmiLocationModel[];
    currentBillTo: BillToModel | undefined;
    getVmiLocationsParameter: GetVmiLocationsApiParameter;
}

type HandlerType = HandlerWithResult<BatchCreateVmiLocationsParameter, BatchCreateVmiLocationsResult>;

export const DispatchBeginBatchLoadProducts: HandlerType = props => {
    props.dispatch({
        type: "Components/VmiLocationsImportModal/BeginValidateVmiLocations",
    });
};

export const InitializeResult: HandlerType = props => {
    props.result = {
        apiParameter: { validationOnly: false, vmiLocations: [] },
        apiResult: { successful: false, errorMessage: "" },
        vmiLocations: [],
        errorEntries: [],
        importedItems: [],
        currentBillTo: undefined,
        getVmiLocationsParameter: {
            page: 1,
            pageSize: 9999,
            expand: ["customerlabel"],
        },
    };
};

export const LoadBillTo: HandlerType = async props => {
    const state = props.getState();
    if (state.components.vmiLocationsImportModal.uploadCancelled) {
        return false;
    }

    props.result.currentBillTo = await getBillTo({
        billToId: API_URL_CURRENT_FRAGMENT,
        expand: ["shipTos", "excludeOneTime", "excludeCreateNew"],
    });
};

export const ProcessLocations: HandlerType = async props => {
    const {
        parameter: { firstRowHeading },
        result: { currentBillTo, errorEntries, importedItems },
    } = props;
    const state = props.getState();
    if (state.components.vmiLocationsImportModal.uploadCancelled) {
        return false;
    }

    const parsedItems = state?.components.vmiLocationsImportModal.parsedItems;
    if (parsedItems.length === 0) {
        props.dispatch({
            type: "Components/VmiLocationsImportModal/SetIsBadFile",
            parameter: { isBadFile: true },
        });
        return false;
    }

    const apiVmiLocationResult = await getVmiLocations(props.result.getVmiLocationsParameter);
    for (let i = 0; i < parsedItems.length; i++) {
        const index = firstRowHeading ? i + 2 : i + 1;
        const parsedItem = parsedItems[i];
        const error = validateLocationData(parsedItem, apiVmiLocationResult.vmiLocations, currentBillTo, importedItems);
        if (error === VmiLocationUploadError.None) {
            importedItems.push({
                name: parsedItem.name,
                billToId: currentBillTo?.id,
                shipToId: currentBillTo?.shipTos?.find(
                    x => x.customerSequence.toLowerCase() === parsedItem.customerSequence?.toLowerCase(),
                )?.id,
                isPrimaryLocation: parsedItem.isPrimaryLocation,
                useBins: parsedItem.useBins,
                enforceMaxQuantityInOrders: parsedItem.enforceMaxQuantityInOrders,
            } as VmiLocationModel);
        } else {
            errorEntries.push(
                mapLocationErrorInfo(
                    index,
                    error,
                    parsedItem.customerNumber,
                    parsedItem.customerSequence,
                    parsedItem.name,
                ),
            );
        }
    }
};

const validateLocationData = (
    row: ParsedItem,
    locations: VmiLocationModel[] | null,
    currentBillTo: BillToModel | undefined,
    importedItems: VmiLocationModel[],
) => {
    if (!row.customerNumber) {
        return VmiLocationUploadError.NoBillTo;
    }
    if (row.customerNumber.toLowerCase() !== currentBillTo?.customerNumber.toLowerCase()) {
        return VmiLocationUploadError.BillToNotFound;
    }
    if (row.customerSequence === null) {
        return VmiLocationUploadError.NoShipTo;
    }
    const shipTo = currentBillTo.shipTos?.find(
        x => x.customerSequence.toLowerCase() === row.customerSequence?.toLowerCase(),
    );
    if (!shipTo) {
        return VmiLocationUploadError.ShipToNotFound;
    }
    if (!row.name) {
        return VmiLocationUploadError.NoLocationName;
    }
    if (row.name.length > 255) {
        return VmiLocationUploadError.LocationNameTooLong;
    }

    const existingVmiLocation = locations?.filter(
        l =>
            l?.name?.toLowerCase() === row.name.toLowerCase() &&
            l?.shipToId?.toLowerCase() === shipTo.id?.toLowerCase(),
    );
    if (existingVmiLocation && existingVmiLocation.length > 0) {
        return VmiLocationUploadError.DuplicateLocationName;
    }

    if (
        importedItems.find(
            x =>
                x.name.toLowerCase() === row.name.toLowerCase() &&
                x.shipToId?.toLowerCase() === shipTo.id?.toLowerCase(),
        )
    ) {
        return VmiLocationUploadError.DuplicateLocationNameSameFile;
    }

    return VmiLocationUploadError.None;
};

const mapLocationErrorInfo = (
    index: number,
    error: VmiLocationUploadError,
    customerNumber: string | null,
    customerSequence: string | null,
    name: string,
) => {
    return {
        customerNumber,
        customerSequence,
        name,
        index,
        error,
    };
};

export const PopulateApiParameter: HandlerType = props => {
    const state = props.getState();
    if (state.components.vmiLocationsImportModal.uploadCancelled) {
        return false;
    }

    props.result.apiParameter = {
        vmiLocations: props.result.importedItems.map(
            item =>
                ({
                    name: item.name,
                    billToId: item.billToId || undefined,
                    shipToId: item.shipToId,
                    isPrimaryLocation: item.isPrimaryLocation,
                    useBins: item.useBins,
                    enforceMaxQuantityInOrders: item.enforceMaxQuantityInOrders,
                } as VmiLocationModel),
        ),
        validationOnly: props.parameter.validationOnly,
    };

    props.result.getVmiLocationsParameter.userId = state?.pages.vmiUsers.getVmiLocationsParameter.userId;
};

export const RequestDataFromApi: HandlerType = async props => {
    const state = props.getState();
    if (state.components.vmiLocationsImportModal.uploadCancelled) {
        return false;
    }

    props.result.apiResult = await batchCreateVmiLocations(props.result.apiParameter);
    if (!props.result.apiResult.successful) {
        props.dispatch({
            type: "Components/VmiLocationsImportModal/SetFullFileError",
            fullFileError: false,
        });
        return false;
    }
};

export const DispatchCompleteBatchLoadProducts: HandlerType = props => {
    props.dispatch({
        type: "Components/VmiLocationsImportModal/CompleteValidateVmiLocations",
        result: props.result,
    });
};

export const chain = [
    DispatchBeginBatchLoadProducts,
    InitializeResult,
    LoadBillTo,
    ProcessLocations,
    PopulateApiParameter,
    RequestDataFromApi,
    DispatchCompleteBatchLoadProducts,
];

const validateVmiLocations = createHandlerChainRunner(chain, "ValidateVmiLocations");
export default validateVmiLocations;
