import { ReceiptBox, ReceiptPallet } from "../types/types.tsx";
import { notifications } from "../../../../../shared/lib/notifications.ts";
import { ProductSchema } from "../../../../../client";
import findProductInObject from "../utils/findProductInObject.tsx";
import nextId from "../utils/nextId.ts";
import { modals } from "@mantine/modals";

type Props = {
    pallets: ReceiptPallet[];
    boxes: ReceiptBox[];
    barcodesProductsMap: Map<string, ProductSchema[]>;
    editObject: (
        object: ReceiptBox | ReceiptPallet,
        isBox: boolean,
        parentPallet?: ReceiptPallet,
    ) => void;
}

const useApplyingScannedResult = ({
                                      pallets,
                                      boxes,
                                      barcodesProductsMap,
                                      editObject,
                                  }: Props) => {
    let isBox = false;
    let object: ReceiptPallet | ReceiptBox;
    let parentPallet: ReceiptPallet | undefined;

    const onProductSelect = (product: ProductSchema) => {
        const productIdx = object.residualProducts.findIndex(p => p.product.id === product.id);
        if (productIdx === -1) {
            object.residualProducts.unshift({
                id: nextId(),
                quantity: 1,
                product,
            });
        } else {
            object.residualProducts[productIdx].quantity += 1;
        }
        editObject(object, isBox, parentPallet);
    };

    const showSelectProductModal = (productsToSelect: ProductSchema[]) => {
        modals.openContextModal({
            modal: "selectScannedProductModal",
            title: "Выберите товар для данного штрихкода",
            withCloseButton: false,
            innerProps: {
                productsToSelect,
                onProductSelect,
            },
        });
    };

    const findProductsByBarcode = (scannedValue: string) => {
        const productsToSelect = barcodesProductsMap.get(scannedValue) ?? [];
        if (productsToSelect?.length === 0) {
            notifications.error({ message: `Товара с штрихкодом ${scannedValue} не найдено` });
            return;
        }
        if (productsToSelect?.length === 1) {
            onProductSelect(productsToSelect[0]);
            return;
        }
        const product = findProductInObject(object, productsToSelect);
        if (product) {
            onProductSelect(product);
            return;
        }
        return showSelectProductModal(productsToSelect);
    };

    const onScanningFinish = (
        value: string,
        boxId?: number,
        palletId?: number,
    ) => {
        isBox = !!boxId;

        if (boxId) {
            let parentPalletIdx = -1;
            if (palletId) {
                parentPalletIdx = pallets.findIndex(pallet => pallet.id === palletId);
            }
            parentPallet = parentPalletIdx === -1 ? undefined : pallets[parentPalletIdx];

            const boxesToSearch = parentPallet?.boxes ?? boxes;
            const boxIdx = boxesToSearch.findIndex(box => box.id === boxId);

            object = boxesToSearch[boxIdx];
            findProductsByBarcode(value);
            return;
        }

        const palletIdx = pallets.findIndex(pallet => pallet.id === palletId);
        object = pallets[palletIdx];
        findProductsByBarcode(value);
    };

    return {
        onScanningFinish,
    };
};

export default useApplyingScannedResult;
