import useProductsList from "../../ProductsPage/hooks/useProductsList.tsx";
import { useEffect, useState } from "react";
import { ProductSchema } from "../../../client";

type Props = {
    clientId?: number;
}

const useBarcodesProductsMap = ({ clientId }: Props) => {
    const {
        products,
        isLoading: isProductsLoading,
    } = useProductsList({ clientId: clientId ?? 0, searchInput: "" });

    const [barcodesProductsMap, setBarcodesProductsMap] = useState(new Map<string, ProductSchema[]>());

    const productsToBarcodesProducts = () => {
        const data = new Map<string, ProductSchema[]>();
        products.forEach(product => {
            product.barcodes.forEach(barcode => {
                if (data.has(barcode)) {
                    data.set(barcode, [...data.get(barcode)!, product]);
                } else {
                    data.set(barcode, [product]);
                }
            });
        });
        setBarcodesProductsMap(data);
    };

    useEffect(() => {
        if (products.length !== 0) {
            productsToBarcodesProducts();
        }
    }, [isProductsLoading]);

    return {
        barcodesProductsMap,
    };
};

export default useBarcodesProductsMap;
