import { useDispatch, useSelector, shallowEqual } from 'react-redux';
import {
    ChangeFullFreeProductList,
    changeFullOfferAppliedProducts,
    ChangeOfferAppliedProducts,
    GlobalFreeProdList, GlobalOfferAppliedProducts
} from '../../../../../Features/Offer/Offernew/BookingOffernew.js';

export const useRemoveProducts = () => {
    const dispatch = useDispatch();
    const OfferFreeProduct = useSelector(GlobalFreeProdList, shallowEqual);
    const OfferAppliedProducts = useSelector(GlobalOfferAppliedProducts, shallowEqual);


    const removeProducts = (item) => {

        let offers = updateOfferOnRemove(OfferFreeProduct, {
            type: item?.Offer > 0 ? "FREE" : "BUY",
            prodId: item?.ProdId,
            inwardDtlId: item?.InwardDtlId,
            qtyToRemove: item?.OrderQty

        });

        dispatch(ChangeFullFreeProductList(offers));
        if (item?.Offer > 0) {

            const RemoveOffer = removeOffer(OfferAppliedProducts, item?.ProdId, item?.InwardDtlId)

            dispatch(changeFullOfferAppliedProducts(RemoveOffer));

 
        }
    };

    return removeProducts;
};

// pure helper function (kept outside hook)
function updateOfferOnRemove(offers, { type, prodId, inwardDtlId, qtyToRemove = 1 }) {

    if (type === "BUY") {
        return offers.filter(offer => offer.BuyInwardDtlId !== inwardDtlId);
    }

    if (type === "FREE") {

        return offers.map(offer => {
            if (offer.FreeProdId === prodId) {
                return {
                    ...offer,
                    ProdVariantDetails: offer.ProdVariantDetails?.map(variant => ({
                        ...variant,
                        StockDetails: variant.StockDetails?.map(stock => {
                            if (stock.InwardDtlId === inwardDtlId) {
                                return {
                                    ...stock,
                                    UsedFree: Math.max(0, stock.UsedFree - qtyToRemove),
                                    RemainingFree: (stock.RemainingFree || 0) + qtyToRemove
                                };
                            }
                            return stock;
                        })
                    })),
                    UsedFreeQty: Math.max(0, (offer.UsedFreeQty || 0) - qtyToRemove),
                    RemainingQty: (offer.RemainingQty || 0) + qtyToRemove
                };
            }
            return offer;
        });
    }

    return offers;
}
function removeOffer(OfferAppliedProducts, freeProdId, inwardDtlId) {
    return OfferAppliedProducts.filter((offer) => {
        const hasMatch = offer?.FreeProductsList?.FreeProdId === freeProdId && offer?.FreeProductsList.ProdVariantDetails?.some((variant) =>
            variant.StockDetails?.some(
                (stock) => stock.FreeInwardDtlId === inwardDtlId
            )
        )

        return !hasMatch;
    });
}

