import { notifications } from "../../../../../shared/lib/notifications.ts";
import { ProductSchema, ResidualBoxSchema, ResidualPalletSchema, ResiduesService } from "../../../../../client";
import { modals } from "@mantine/modals";
import findProductInObject from "../../NewReceipt/utils/findProductInObject.tsx";

type Props = {
    object: ResidualBoxSchema | ResidualPalletSchema | null;
    barcodesProductsMap: Map<string, ProductSchema[]>;
    refetch: () => void;
}

const useApplyingScannedResult = ({
                                      object,
                                      barcodesProductsMap,
                                      refetch,
                                  }: Props) => {
    let boxIdValue: number | null = null;

    const onProductSelect = (product: ProductSchema) => {
        if (!object) return;
        ResiduesService.createResidualProduct({
            requestBody: {
                data: {
                    productId: product.id,
                    quantity: 1,
                    palletId: boxIdValue ? null : object.id,
                    boxId: boxIdValue,
                },
            },
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message });
                refetch();
            })
            .catch(err => console.log(err));
    };

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

    const onScanningFinish = (
        value: string,
        boxId?: number,
        palletId?: number,
    ) => {
        if (!object) return;
        boxIdValue = boxId ?? null;
        let objectValue: ResidualPalletSchema | ResidualBoxSchema = object;

        if (palletId && boxId) {
            const pallet = object as ResidualPalletSchema;
            const boxOnPallet = pallet.boxes.find(box => box.id === boxId);
            if (!boxOnPallet) return;
            objectValue = boxOnPallet;
        }

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

    return { onScanningFinish };
};

export default useApplyingScannedResult;
