import { useCallback, useEffect, useRef, useState } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { Form } from 'antd';
import {
  GlobalOrderCardDetails,
  changeOrderCardDetails,
  changeHoldOrderDtl,
  changePreviousOrderLength,
  GlobalOrderType,
  GlobalReorderProductDetails,
  PreferenceData,
  getConfigType,
} from '../../../../../Features/BookingScreen/BookingData/BookingData';
import { Messages } from '../../../../../Components/Notifications/Messages';
import '../../../../../Styles/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/BSBillingEditQuantity.scss';
import { useApplyOfferto_CardDetail } from '../../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx';
import {
  getTemplateData,
  StoredSessionData,
} from '../../../../../Features/ThemeChange/ThemeChange.js';
import { GlobalEmpAccessDetail } from '../../../../../Features/AppPage/CenterPage.js';
import {
  ChangeFullFreeProductList,
  changeFullOfferAppliedProducts,
  ChangeOfferAppliedProducts,
  GlobalFreeProdList,
  GlobalOfferAppliedProducts,
  RemoveOfferAppliedProduct,
} from '../../../../../Features/Offer/Offernew/BookingOffernew.js';
import { validateOffers } from '../../BSItemCards/ValidateOffer.jsx';
import { v4 as uuidv4 } from 'uuid';
import "./ComboBillTableEdit.scss"

const ComboEditQtyAndRate = (props) => {
  const dispatch = useDispatch();
  const formRef = useRef(null);
  const quantityInputRef = useRef(null);
  const priceChangeInputRef = useRef(null);
  const { setIndex = () => {}, setEditQtyCombo = () => {}, setEditRateCombo = () => {} } = props;

  const [disableSubmitButton, setDisableSubmitButton] = useState(false);
  const SessionData = useSelector(StoredSessionData);
  // const AppId = SessionData?.AppId;
  // const CompId = SessionData?.CompId;
  // const BranchId = SessionData?.BranchId;
  const UserType = SessionData?.UserType;
  const applyOffer = useApplyOfferto_CardDetail();
  const preferenceDatas = useSelector(PreferenceData);
  const EmpAccessDetail = useSelector(GlobalEmpAccessDetail);
  const OverAllproductBasedOfferDatas = useSelector(
    (state) => state?.BookingOFferNew?.OverAllProductBasedProducts,
    shallowEqual
  );
  const preferenceOffer =
    preferenceDatas?.[0]?.['SettingDtlDetails']?.find(
      (item) => item.SettingIdName === 'Offer'
    )?.SettingValue === 'Y';
  const preferenceshortcutkey = preferenceDatas?.[0]?.[
    'SettingDtlDetails'
  ]?.some(
    (item) =>
      item.SettingIdName.toLowerCase() === 'shortcutkeys' &&
      item.SettingValue === 'Y'
  );
  console.log(preferenceshortcutkey, 'preferenceshortcutkey');
  const [PriceChangeaccess, setPriceChangeaccess] = useState(true);

  const [ConfigDataList, setConfigDataList] = useState([]);
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [EditOpen, setEditOpen] = useState(props?.BSBillingEditQuantity || props?.BSBillingEditRate);
  const [ItemData, setItemData] = useState(props?.Productdata);
  const [Quantity, setQuantity] = useState('');
  const ReorderProductData = useSelector(GlobalReorderProductDetails);
  const templateData = useSelector(getTemplateData);
  const OfferCheckedInSetup =
    templateData?.BookingNavbar?.[1].some(
      (item) => item?.OptionName == 'Offer'
    ) ||
    templateData?.BookingCombo1?.[1]?.some(
      (item) => item?.OptionName == 'Offer'
    );
  const [ClearQuantity, setClearQuantity] = useState(false);
  const CartOrderDetails = useSelector(GlobalOrderCardDetails);
  const SettingDataSelector = useSelector(PreferenceData);
  const OrderType = useSelector(GlobalOrderType);
  const [BillOrderPre, setBillOrderPre] = useState(null);
  const [RadioBtnSelection, setRadioBtnSelection] = useState();
  const [editedPrice, setEditedPrice] = useState(0);
  const allowDecimal = preferenceDatas?.[0]?.SettingDtlDetails?.find(
    (setting) =>
      setting?.SettingIdName?.toLowerCase() === 'decimal' &&
      setting?.SettingValue === 'Y'
  );
  const [PackageDtl, setPackageDtl] = useState([]);
  const OfferAppliedProducts = useSelector(
    GlobalOfferAppliedProducts,
    shallowEqual
  );
  const FreeProdList = useSelector(GlobalFreeProdList);
  console.log(CartOrderDetails, 'CartOrderDetails');

  const TakAwayId = ConfigDataList?.find(
    (a) => a?.ConfigName === 'TakeAway'
  )?.ConfigId;

  const DineinId = ConfigDataList?.find(
    (a) => a?.ConfigName === 'Dine In'
  )?.ConfigId;

  const hasOffer = preferenceOffer && OfferCheckedInSetup;

  useEffect(() => {
    if (ConfigDataList?.length === 0) {
      getBookingTypeId();
    }
  }, []);

  useEffect(
    () => {
      setEditOpen(props.BSBillingEditQuantity || props.BSBillingEditRate);
      setItemData(props.Productdata);
      setQuantity('');
       setEditedPrice('');
    },
    [props.BSBillingEditQuantity],
    [props.Productdata],
    [props.BSBillingEditRate]
  );

  useEffect(() => {
    if (props.BSBillingEditQuantity || props.BSBillingEditRate) {
      if (RadioBtnSelection === 'Quantity') {
        setTimeout(() => quantityInputRef.current?.focus(), 100);
      } else if (RadioBtnSelection === 'Rate') {
        setTimeout(() => priceChangeInputRef.current?.focus(), 100);
      }
    }
  }, [RadioBtnSelection, props.BSBillingEditQuantity, props.BSBillingEditRate]);

  useEffect(() => {
    const handleKeyDown = (event) => {
      if (preferenceshortcutkey && event.shiftKey && event.key === 'E') {
        event.preventDefault();
        if (PriceChangeaccess && props.Productdata?.Offer <= 0) {
          onRadioBtnChange('Price');
        }
      }
    };

    if (EditOpen) {
      document.addEventListener('keydown', handleKeyDown);
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [
    EditOpen,
    preferenceshortcutkey,
    PriceChangeaccess,
    props.Productdata?.Offer,
  ]);

  useEffect(() => {
    const BillOrder = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
      (item) => item.SettingIdName === 'BillItemsOrder'
    );
    setBillOrderPre(BillOrder?.SettingValue);
  }, []);

  useEffect(() => {
    if (UserType == 'Employee') {
      const Pricechange = EmpAccessDetail?.filter(
        (item) => item.ConfigName === 'Sales Discount'
      );

      setPriceChangeaccess(Pricechange?.[0]?.AddAccess != 'Y' ? false : true);
    }
  }, [EmpAccessDetail]);
  useEffect(() => {
    if (props?.BSBillingEditRate) {
      setRadioBtnSelection('Rate');
      setEditedPrice(props.Productdata?.OrderRate || 0);
    } else if (props?.BSBillingEditQuantity) {
      setRadioBtnSelection('Quantity');
    }
  }, [props?.BSBillingEditRate, props?.BSBillingEditQuantity, props.Productdata?.OrderRate]);
  const getBookingTypeId = async () => {
    let tempconfigdata = await dispatch(
      getConfigType({ TypeName: 'Booking Type' })
    ).unwrap();

    if (tempconfigdata?.data?.statusCode == 1) {
      setConfigDataList(tempconfigdata?.data?.data);
    }
  };


  const calculateOverAllQty = (item, filterItems) => {
    if (!item) return 0;

    const totalUsedQty =
      filterItems?.reduce((acc, card) => {
        if (card?.StockAvailable !== 'Y') return acc;

        const isSinglePcItem = item?.SinglePc === 'Y';
        const isSinglePcCard = card?.SinglePc === 'Y';

        let qty = 0;
        if (isSinglePcItem) {
          qty = isSinglePcCard ? card.OrderQty : card.OrderQty * card.NoOfPcs;
        } else {
          if (isSinglePcCard) {
            const remainder = card?.OverAllPcs % card?.NoOfPcs;
            qty =
              remainder >= card?.OrderQty
                ? 0
                : Math.ceil(card?.OrderQty / card?.NoOfPcs);
          } else {
            qty = card.OrderQty;
          }
        }
        return acc + qty;
      }, 0) || 0;

    const availableQty =
      item?.SinglePc === 'Y' ? item?.OverAllPcs : item?.BalanceQty;
    return availableQty - totalUsedQty;
  };
  const AddProductQuantity = async () => {
    let newPrice = editedPrice > 0 ? editedPrice : props.Productdata.OrderRate;
    await dispatch(changeHoldOrderDtl(false));
    await dispatch(changePreviousOrderLength(CartOrderDetails?.length));

    if (RadioBtnSelection === 'Rate') {
      let localId = props.Index;
      let editedProductIndex = CartOrderDetails?.findIndex(
        (e) => e?.localId == localId
      );
      if (editedProductIndex === -1) {
        setMessageType('error');
        setMessageData('Product not found in cart');
        return;
      }
      
      const editedProduct = CartOrderDetails[editedProductIndex];
      const existingQty = editedProduct.OrderQty;
      
      // Validate rate value
      if (!newPrice || newPrice <= 0) {
        setMessageType('error');
        setMessageData('Please enter a valid rate');
        return;
      }
      
      // Update ONLY the rate, use existing quantity
      await handleNormalEditQuantity(
        editedProduct,
        editedProductIndex,
        existingQty, 
        newPrice
      );
      
      // Reset and close
      setClearQuantity(false);
      setIndex(null);
      setEditQtyCombo(false);
      setEditRateCombo(false);
      setMessageType('success');
      setMessageData('Rate updated successfully');
      return;
    }

    // When editing quantity, validate quantity input
    if (
      (parseInt(Quantity) === 0 || Quantity === '') &&
      props?.Productdata?.ScaleType !== 'weight'
    ) {
      setMessageType('error');
      setMessageData('Please enter valid quantity');
      setQuantity('');
    } else {
      let localId = props.Index;
      const editedQty =
        props?.Productdata?.ScaleType !== 'weight'
          ? parseInt(Quantity)
          : props.Productdata.OrderQty;
      let editedProductIndex = CartOrderDetails?.findIndex(
        (e) => e?.localId == localId
      );
      const editedProduct = CartOrderDetails[editedProductIndex];
      const productBookingType = editedProduct?.BookingTypeName;
      const isItemInCart = CartOrderDetails?.find(
        (cartItem) =>
          cartItem?.ProdId === editedProduct?.ProdId &&
          cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
          cartItem?.OrderRate === editedProduct?.OrderRate &&
          cartItem?.BookingTypeName === editedProduct?.BookingTypeName &&
          !cartItem?.SalesId
      );
      // changing for one piece stock checking
      const isItemInCartfilter = CartOrderDetails?.filter(
        (cartItem) =>
          cartItem?.ProdId === editedProduct?.ProdId &&
          cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
          cartItem?.OrderRate !== editedProduct?.OrderRate &&
          !cartItem?.SalesId
      );

      const isItemInCartHold = CartOrderDetails?.find(
        (cartItem) =>
          cartItem?.ProdId === editedProduct?.ProdId &&
          cartItem?.InwardDtlId === editedProduct.InwardDtlId &&
          cartItem?.OrderRate === editedProduct?.OrderRate &&
          cartItem?.BookingTypeName === editedProduct?.BookingTypeName
      ); // check if the item is already in the cart
      const isItemInCartHoldfilter = CartOrderDetails?.filter(
        (cartItem) =>
          cartItem?.ProdId === editedProduct?.ProdId &&
          cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
          !(
            (cartItem?.OrderRate === editedProduct?.OrderRate)
            // && cartItem?.BookingTypeName === editedProduct?.BookingTypeName
          )
      );

      if (
        (isItemInCart &&
          productBookingType !== 'Dine In' &&
          OrderType != 'Hold') ||
        (isItemInCart &&
          productBookingType === 'Dine In' &&
          OrderType != 'Hold')
      ) {
        const overAllQuantity = calculateOverAllQty(
          isItemInCart,
          isItemInCartfilter
        );
        let totalUsedQty = 0;
        const sameProductInOtherBookingType = CartOrderDetails?.filter(
          (cartItem) =>
            cartItem?.ProdId === editedProduct?.ProdId &&
            cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
            cartItem?.OrderRate === editedProduct?.OrderRate &&
            cartItem?.BookingTypeName !== editedProduct?.BookingTypeName &&
            !cartItem?.SalesId
        );
        if (editedProduct?.Offer > 0) {
          // check same product available in paid product
          const sameProductAsPaidInSameBookingType = CartOrderDetails?.filter(
            (cartItem) =>
              cartItem?.ProdId === editedProduct?.ProdId &&
              cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
              cartItem?.OrderRate === editedProduct?.OrderRate &&
              cartItem?.BookingTypeName === editedProduct?.BookingTypeName &&
              !cartItem?.SalesId &&
              !cartItem?.OfferMode &&
              cartItem?.Offer === 0
          );

          if (sameProductAsPaidInSameBookingType?.length > 0) {
            const stockAvailable = sameProductAsPaidInSameBookingType?.some(
              (item) => item?.StockAvailable === 'Y'
            );
            if (stockAvailable) {
              totalUsedQty = sameProductAsPaidInSameBookingType?.reduce(
                (acc, item) => {
                  if (item?.StockAvailable === 'Y') {
                    return acc + parseInt(item?.OrderQty);
                  }
                  return acc;
                },
                0
              );
            }
          }
        } else if (!editedProduct?.Offer) {
          const sameProductAsFree = CartOrderDetails?.filter(
            (cartItem) =>
              cartItem?.ProdId === editedProduct?.ProdId &&
              cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
              cartItem?.OrderRate === editedProduct?.OrderRate &&
              cartItem?.BookingTypeName === editedProduct?.BookingTypeName &&
              !cartItem?.SalesId &&
              cartItem?.Offer > 0 &&
              cartItem?.OfferMode
          );

          if (sameProductAsFree?.length > 0) {
            const stockAvailable = sameProductAsFree?.some(
              (item) => item?.StockAvailable === 'Y'
            );
            if (stockAvailable) {
              totalUsedQty = sameProductAsFree?.reduce((acc, item) => {
                if (item?.StockAvailable === 'Y') {
                  return acc + parseInt(item?.OrderQty);
                }
                return acc;
              }, 0);
            }
          }
        }

        if (sameProductInOtherBookingType?.length > 0) {
          const stockAvailable = sameProductInOtherBookingType?.some(
            (item) => item?.StockAvailable === 'Y'
          );
          if (stockAvailable) {
            totalUsedQty += sameProductInOtherBookingType?.reduce(
              (acc, item) => {
                if (item?.StockAvailable === 'Y') {
                  return acc + parseInt(item?.OrderQty);
                }
                return acc;
              },
              0
            );
          }
        }

        if (
          overAllQuantity < editedQty + (totalUsedQty || 0) &&
          isItemInCart?.StockAvailable === 'Y'
        ) {
          setMessageType('error');
          setMessageData('Stock Not Available');
          return;
        }
      } else if (isItemInCartHold && OrderType === 'Hold') {
        const holddataproduct = ReorderProductData?.filter(
          (cartItem) =>
            cartItem?.ProdId === editedProduct?.ProdId &&
            cartItem?.InwardDtlId === editedProduct?.InwardDtlId
        );

        let totalSelectedProductQty = holddataproduct?.reduce(
          (accumulator, card) => {
            return (
              accumulator +
              parseInt(
                card?.StockAvailable === 'Y'
                  ? editedProduct?.SinglePc === 'Y'
                    ? card.SinglePc !== 'Y'
                      ? card.OrderQty * card.NoOfPcs
                      : card.OrderQty
                    : card.SinglePc !== 'Y'
                      ? card.OrderQty
                      : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
                        ? 0
                        : card.OrderQty % card.NoOfPcs === 0
                          ? Math.floor(card.OrderQty / card.NoOfPcs)
                          : Math.floor(card.OrderQty / card.NoOfPcs) + 1
                  : 0
              )
            );
          },
          0
        );

        let totalUsedQty = 0;

        const sameProductInOtherBookingType = CartOrderDetails?.filter(
          (cartItem) =>
            cartItem?.ProdId === editedProduct?.ProdId &&
            cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
            cartItem?.OrderRate === editedProduct?.OrderRate &&
            cartItem?.BookingTypeName !== editedProduct?.BookingTypeName
        );

        if (editedProduct?.Offer > 0) {
          // check same product available in paid product
          const sameProductAsPaid = CartOrderDetails?.find(
            (cartItem) =>
              cartItem?.ProdId === editedProduct?.ProdId &&
              cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
              cartItem?.OrderRate === editedProduct?.OrderRate &&
              cartItem?.BookingTypeName === editedProduct?.BookingTypeName &&
              !cartItem?.OfferMode &&
              cartItem?.Offer === 0
          );

          if (sameProductAsPaid?.StockAvailable === 'Y') {
            totalUsedQty = sameProductAsPaid?.OrderQty;
          }
        } else if (!editedProduct?.Offer) {
          const sameProductAsFree = CartOrderDetails?.find(
            (cartItem) =>
              cartItem?.ProdId === editedProduct?.ProdId &&
              cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
              cartItem?.OrderRate === editedProduct?.OrderRate &&
              cartItem?.BookingTypeName === editedProduct?.BookingTypeName &&
              cartItem?.Offer > 0 &&
              cartItem?.OfferMode
          );
          if (sameProductAsFree?.StockAvailable === 'Y') {
            totalUsedQty = sameProductAsFree?.OrderQty;
          }
        }

        if (sameProductInOtherBookingType?.length > 0) {
          const stockAvailable = sameProductInOtherBookingType?.some(
            (item) => item?.StockAvailable === 'Y'
          );
          if (stockAvailable) {
            totalUsedQty += sameProductInOtherBookingType?.reduce(
              (acc, item) => {
                if (item?.StockAvailable === 'Y') {
                  return acc + parseInt(item?.OrderQty);
                }
                return acc;
              },
              0
            );
          }
        }

        let overAllQuantityHold =
          calculateOverAllQty(isItemInCartHold, isItemInCartHoldfilter) +
          totalSelectedProductQty;
        if (
          isItemInCartHold?.StockAvailable === 'Y' &&
          overAllQuantityHold < editedQty + (totalUsedQty || 0)
        ) {
          setMessageType('error');
          setMessageData('Stock Not Available');
          return;
        }
      }
      await handleEditQuantity(editedProduct, editedProductIndex, newPrice);
      props.handleEditQuantityCancel();
      setClearQuantity(false);
    }
    setIndex(null);
    setEditQtyCombo(false);
    setEditRateCombo(false);
  };

  const handleEditQuantity = async (
    editedProduct,
    editedProductIndex,
    newPrice
  ) => {
    const editedQty =
      props?.Productdata?.ScaleType !== 'weight'
        ? parseInt(Quantity)
        : props.Productdata.OrderQty;
    const addFirst = BillOrderPre === 'Y';
    const isExistsInFreeProdList = FreeProdList?.find(
      (product) =>
        product?.ProdVariantDetails?.some((variant) =>
          variant?.StockDetails?.some(
            (stock) => stock?.FreeInwardDtlId === editedProduct?.InwardDtlId
          )
        ) &&
        editedProduct?.OfferMessage?.[0]?.OfferId === product?.OfferId &&
        editedProduct?.OfferMode === product?.OfferMode
    );
    console.log(FreeProdList, 'FreeProdList');

    if (
      isExistsInFreeProdList &&
      editedProduct?.Offer > 0 &&
      hasOffer &&
      editedProduct?.SinglePc !== 'Y'
    ) {
      const freeProductInOtherBooking = CartOrderDetails?.find((cartItem) => {
        return (
          cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
          cartItem?.OfferMessage?.[0]?.OfferId ===
            editedProduct?.OfferMessage?.[0]?.OfferId &&
          cartItem?.OfferMode === editedProduct?.OfferMode &&
          cartItem?.BookingTypeName !== editedProduct?.BookingTypeName
        );
      });

      const finalOrderQty =
        (freeProductInOtherBooking?.OrderQty || 0) + editedQty;

      if (isExistsInFreeProdList?.RemainingQty === 0) {
        // need to split the free product and paid product

        if (finalOrderQty > isExistsInFreeProdList?.OverAllFreeQty) {
          const paidQty =
            finalOrderQty - isExistsInFreeProdList?.OverAllFreeQty;
          const isAlreadyExistsInCart = CartOrderDetails?.findIndex(
            (cartItem) => {
              return (
                cartItem?.ProdId === editedProduct?.ProdId &&
                cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
                !cartItem?.OfferMode &&
                cartItem?.Offer === 0 &&
                cartItem?.BookingTypeName === editedProduct?.BookingTypeName &&
                cartItem?.OrderRate === editedProduct?.OrderRate
              );
            }
          );

          let updatedCart = [...CartOrderDetails];

          if (isAlreadyExistsInCart !== -1) {
            // update the existing paid product in cart
            const existingItem = updatedCart[isAlreadyExistsInCart];
            const updatedItem = {
              ...existingItem,
              OrderQty: existingItem?.OrderQty + paidQty,
              ...calculateTaxAmounts({
                qty: existingItem?.OrderQty + paidQty,
                rate: existingItem?.OrderRate,
                taxPercentage: existingItem?.TaxPercentage,
              }),
            };
            updatedCart?.splice(isAlreadyExistsInCart, 1);
            updatedCart = addFirst
              ? [updatedItem, ...updatedCart]
              : [...updatedCart, updatedItem];
          } else {
            // add new paid product in cart
            const paidProduct = {
              localId: uuidv4(),
              ...editedProduct,
              OrderQty: paidQty,
              Offer: 0,
              OfferMode: null,
              OfferMessage: null,
              OfferType: null,
              ...calculateTaxAmounts({
                qty: paidQty,
                rate: editedProduct.OrderRate,
                taxPercentage: editedProduct.TaxPercentage,
              }),
            };
            updatedCart = addFirst
              ? [paidProduct, ...updatedCart]
              : [...updatedCart, paidProduct];
          }
          dispatch(changeOrderCardDetails(updatedCart));
        } else {
          // Check if there is any same product but No offer applied in OrderCardDtls in same BookingType
          // In Same BookingType Have Enough Free Qty Just only Update Qty in Same Booking Type OtherWise need to update in Other Booking Type Qty also if exists in Other Booking Type
          const isAlreadyExistsInCart = CartOrderDetails?.find((cartItem) => {
            return (
              cartItem?.ProdId === editedProduct?.ProdId &&
              cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
              cartItem?.OrderRate === editedProduct?.OrderRate &&
              cartItem?.BookingTypeName === editedProduct?.BookingTypeName &&
              !cartItem?.OfferMode &&
              cartItem?.Offer === 0
            );
          });

          const freeQtyNeeded =
            isExistsInFreeProdList?.OverAllFreeQty - finalOrderQty;
          const paidQtySame = isAlreadyExistsInCart?.OrderQty || 0;

          if (paidQtySame >= freeQtyNeeded) {
            const remainingPaidQty = (paidQtySame || 0) - freeQtyNeeded;
            if (remainingPaidQty === 0) {
              // Just need to update the Free Qty and Remove the Paid Product from Cart
              const updatedCart = CartOrderDetails?.filter(
                (cartItem) => cartItem !== isAlreadyExistsInCart
              );
              dispatch(
                changeOrderCardDetails(
                  updatedCart?.map((cartItem) => {
                    if (cartItem === editedProduct) {
                      return {
                        ...cartItem,
                        PackageDtl: PackageDtl,
                      };
                    }
                    return cartItem;
                  })
                )
              );
            } else {
              // need to update the Paid Qty to Remaining Qty
              const updatedCart = CartOrderDetails?.map((cartItem) => {
                if (cartItem === isAlreadyExistsInCart) {
                  return {
                    ...cartItem,
                    OrderQty: remainingPaidQty,
                    ...calculateTaxAmounts({
                      qty: remainingPaidQty,
                      rate: cartItem.OrderRate,
                      taxPercentage: cartItem.TaxPercentage,
                    }),
                  };
                }
                return cartItem;
              });
              dispatch(changeOrderCardDetails(updatedCart));
            }
          } else {
            // check if the same product exists in other booking type as paid product
            // need to calculate how much qty going to be updated in other booking type and same booking type

            const diffBookingTypeProduct = CartOrderDetails?.find(
              (cartItem) => {
                return (
                  cartItem?.ProdId === editedProduct?.ProdId &&
                  cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
                  cartItem?.OrderRate === editedProduct?.OrderRate &&
                  cartItem?.BookingTypeName !==
                    editedProduct?.BookingTypeName &&
                  !cartItem?.OfferMode &&
                  cartItem?.Offer === 0
                );
              }
            );

            const diffBookingTypeFreeProduct = CartOrderDetails?.find(
              (cartItem) => {
                return (
                  cartItem?.ProdId === editedProduct?.ProdId &&
                  cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
                  cartItem?.OrderRate === editedProduct?.OrderRate &&
                  cartItem?.BookingTypeName !==
                    editedProduct?.BookingTypeName &&
                  cartItem?.OfferMode === editedProduct?.OfferMode &&
                  cartItem?.Offer > 0
                );
              }
            );

            const paidQtyOther = diffBookingTypeProduct?.OrderQty || 0;
            const sameBookTypeUpdateQty = freeQtyNeeded - paidQtySame;
            const otherBookTypePaidUpdateQty =
              paidQtyOther - sameBookTypeUpdateQty;
            const totalPaidQty = paidQtySame + paidQtyOther;

            if (paidQtySame || paidQtyOther) {
              let updatedCart = [...CartOrderDetails];

              // Remove paid product in same booking type if needed
              if (paidQtySame) {
                updatedCart = updatedCart.filter(
                  (cartItem) => cartItem !== isAlreadyExistsInCart
                );
                updatedCart = updatedCart.map((cartItem) => {
                  if (cartItem === editedProduct) {
                    return {
                      ...cartItem,
                      OrderQty: editedQty + paidQtySame,
                      ...calculateTaxAmounts({
                        qty: editedQty + paidQtySame,
                        rate: cartItem.OrderRate,
                        taxPercentage: cartItem.TaxPercentage,
                      }),
                      ...(cartItem?.Offer > 0 && {
                        Offer: (editedQty + paidQtySame) * cartItem.OrderRate,
                      }),
                    };
                  }
                  return cartItem;
                });
              }

              // Remove/update paid product in other booking type if needed
              if (paidQtyOther) {
                if (otherBookTypePaidUpdateQty <= 0) {
                  // Remove paid product from other booking type
                  updatedCart = updatedCart.filter(
                    (cartItem) => cartItem !== diffBookingTypeProduct
                  );
                  updatedCart = updatedCart.map((cartItem) => {
                    if (cartItem === diffBookingTypeFreeProduct) {
                      return {
                        ...cartItem,
                        OrderQty: paidQtyOther + cartItem?.OrderQty,
                        ...calculateTaxAmounts({
                          qty: paidQtyOther + cartItem?.OrderQty,
                          rate: cartItem?.OrderRate,
                          taxPercentage: cartItem?.TaxPercentage,
                        }),
                        Offer:
                          (paidQtyOther + cartItem?.OrderQty) *
                          cartItem?.OrderRate,
                      };
                    } else if (cartItem === editedProduct) {
                      return {
                        ...cartItem,
                        OrderQty: editedQty,
                        ...calculateTaxAmounts({
                          qty: editedQty,
                          rate: cartItem?.OrderRate,
                          taxPercentage: cartItem?.TaxPercentage,
                        }),
                        Offer: editedQty * cartItem?.OrderRate,
                      };
                    }
                    return cartItem;
                  });
                } else if (otherBookTypePaidUpdateQty > 0) {
                  updatedCart = updatedCart.map((cartItem) => {
                    if (cartItem === diffBookingTypeFreeProduct) {
                      return {
                        ...cartItem,
                        OrderQty: cartItem?.OrderQty + sameBookTypeUpdateQty,
                        ...calculateTaxAmounts({
                          qty: cartItem?.OrderQty + sameBookTypeUpdateQty,
                          rate: cartItem?.OrderRate,
                          taxPercentage: cartItem?.TaxPercentage,
                        }),
                        Offer:
                          (cartItem?.OrderQty + sameBookTypeUpdateQty) *
                          cartItem?.OrderRate,
                      };
                    } else if (cartItem === editedProduct) {
                      return {
                        ...cartItem,
                        OrderQty: editedQty,
                        ...calculateTaxAmounts({
                          qty: editedQty,
                          rate: cartItem?.OrderRate,
                          taxPercentage: cartItem?.TaxPercentage,
                        }),
                        Offer: editedQty * cartItem?.OrderRate,
                      };
                    } else if (cartItem === diffBookingTypeProduct) {
                      return {
                        ...cartItem,
                        OrderQty: otherBookTypePaidUpdateQty,
                        ...calculateTaxAmounts({
                          qty: otherBookTypePaidUpdateQty,
                          rate: cartItem?.OrderRate,
                          taxPercentage: cartItem?.TaxPercentage,
                        }),
                      };
                    }
                    return cartItem;
                  });
                }
              }

              // Only one dispatch after all updates
              dispatch(changeOrderCardDetails(updatedCart));

              if (totalPaidQty < freeQtyNeeded) {
                const additionalFreeQtyNeeded = freeQtyNeeded - totalPaidQty;

                const updatedFreeProdList = FreeProdList?.map((product) => {
                  if (
                    product?.FreeProdId === editedProduct?.ProdId &&
                    product?.ProdVariantDetails?.some((variant) =>
                      variant?.StockDetails?.some(
                        (stock) =>
                          stock?.FreeInwardDtlId === editedProduct?.InwardDtlId
                      )
                    ) &&
                    product?.OfferId ===
                      editedProduct?.OfferMessage?.[0]?.OfferId &&
                    product?.OfferMode === editedProduct?.OfferMode
                  ) {
                    const freeQty =
                      product?.OverAllFreeQty - additionalFreeQtyNeeded;
                    return {
                      ...product,
                      FreeQty: freeQty,
                      RemainingQty: additionalFreeQtyNeeded,
                      discount: freeQty * editedProduct?.OrderRate,
                    };
                  }
                  return product;
                });

                dispatch(ChangeFullFreeProductList(updatedFreeProdList));
                const updatedOfferAppliedProducts = OfferAppliedProducts?.map(
                  (offerProduct) => {
                    // Check if this offer product contains the edited product in its free products list
                    const hasMatchingFreeProduct =
                      offerProduct?.FreeProductsList?.some((freeProduct) =>
                        freeProduct?.ProdVariantDetails?.some((variant) =>
                          variant?.StockDetails?.some(
                            (stock) =>
                              stock?.FreeInwardDtlId ===
                              editedProduct?.InwardDtlId
                          )
                        )
                      );

                    // Also check main offer conditions
                    const isMatchingOffer =
                      offerProduct?.OfferId ===
                        editedProduct?.OfferMessage?.[0]?.OfferId &&
                      offerProduct?.OfferMode === editedProduct?.OfferMode;

                    if (hasMatchingFreeProduct && isMatchingOffer) {
                      // Get loyalty points from the matching free product
                      const matchingFreeProduct =
                        offerProduct?.FreeProductsList?.find((freeProduct) =>
                          freeProduct?.ProdVariantDetails?.some((variant) =>
                            variant?.StockDetails?.some(
                              (stock) =>
                                stock?.FreeInwardDtlId ===
                                editedProduct?.InwardDtlId
                            )
                          )
                        );

                      const prodLoyaltyPoint =
                        matchingFreeProduct?.ProdVariantDetails?.[0]
                          ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0;

                      const freeQty =
                        matchingFreeProduct?.FreeQty - additionalFreeQtyNeeded;
                      // Update the specific free product in the list
                      const updatedFreeProductsList =
                        offerProduct?.FreeProductsList?.map((freeProduct) => {
                          const isTargetFreeProduct =
                            freeProduct?.ProdVariantDetails?.some((variant) =>
                              variant?.StockDetails?.some(
                                (stock) =>
                                  stock?.FreeInwardDtlId ===
                                  editedProduct?.InwardDtlId
                              )
                            );

                          if (isTargetFreeProduct) {
                            return {
                              ...freeProduct,
                              FreeQty: freeQty,
                            };
                          }
                          return freeProduct;
                        });

                      return {
                        ...offerProduct,
                        ActualFreeQty: freeQty,
                        ActualOfferAmount: freeQty * editedProduct?.OrderRate,
                        OfferAmount: freeQty * editedProduct?.OrderRate,
                        OfferValue: freeQty * editedProduct?.OrderRate,
                        FreeProductsList: updatedFreeProductsList,
                        UsedCount: freeQty * prodLoyaltyPoint,
                      };
                    }

                    return offerProduct;
                  }
                );
                dispatch(
                  changeFullOfferAppliedProducts(updatedOfferAppliedProducts)
                );
              }
            } else {
              await handleNormalEditQuantity(
                editedProduct,
                editedProductIndex,
                editedQty,
                newPrice,
                true
              );
              const updatedFreeProdList = FreeProdList?.map((product) => {
                if (
                  product?.FreeProdId === editedProduct?.ProdId &&
                  product?.ProdVariantDetails?.some((variant) =>
                    variant?.StockDetails?.some(
                      (stock) =>
                        stock?.FreeInwardDtlId === editedProduct?.InwardDtlId
                    )
                  ) &&
                  product?.OfferId ===
                    editedProduct?.OfferMessage?.[0]?.OfferId &&
                  product?.OfferMode === editedProduct?.OfferMode
                ) {
                  return {
                    ...product,
                    FreeQty: finalOrderQty,
                    RemainingQty: product?.OverAllFreeQty - finalOrderQty,
                    discount: finalOrderQty * editedProduct?.OrderRate,
                  };
                }
                return product;
              });
              dispatch(ChangeFullFreeProductList(updatedFreeProdList));
              const updatedOfferAppliedProducts = OfferAppliedProducts?.map(
                (offerProduct) => {
                  // Check if this offer product contains the edited product in its free products list
                  const hasMatchingFreeProduct =
                    offerProduct?.FreeProductsList?.some((freeProduct) =>
                      freeProduct?.ProdVariantDetails?.some((variant) =>
                        variant?.StockDetails?.some(
                          (stock) =>
                            stock?.FreeInwardDtlId ===
                            editedProduct?.InwardDtlId
                        )
                      )
                    );

                  // Also check main offer conditions
                  const isMatchingOffer =
                    offerProduct?.OfferId ===
                      editedProduct?.OfferMessage?.[0]?.OfferId &&
                    offerProduct?.OfferMode === editedProduct?.OfferMode;

                  if (hasMatchingFreeProduct && isMatchingOffer) {
                    // Get loyalty points from the matching free product
                    const matchingFreeProduct =
                      offerProduct?.FreeProductsList?.find((freeProduct) =>
                        freeProduct?.ProdVariantDetails?.some((variant) =>
                          variant?.StockDetails?.some(
                            (stock) =>
                              stock?.FreeInwardDtlId ===
                              editedProduct?.InwardDtlId
                          )
                        )
                      );

                    const prodLoyaltyPoint =
                      matchingFreeProduct?.ProdVariantDetails?.[0]
                        ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0;

                    // Update the specific free product in the list
                    const updatedFreeProductsList =
                      offerProduct?.FreeProductsList?.map((freeProduct) => {
                        const isTargetFreeProduct =
                          freeProduct?.ProdVariantDetails?.some((variant) =>
                            variant?.StockDetails?.some(
                              (stock) =>
                                stock?.FreeInwardDtlId ===
                                editedProduct?.InwardDtlId
                            )
                          );

                        if (isTargetFreeProduct) {
                          return {
                            ...freeProduct,
                            FreeQty: finalOrderQty,
                          };
                        }
                        return freeProduct;
                      });

                    return {
                      ...offerProduct,
                      ActualFreeQty: finalOrderQty,
                      ActualOfferAmount:
                        finalOrderQty * editedProduct?.OrderRate,
                      OfferAmount: finalOrderQty * editedProduct?.OrderRate,
                      OfferValue: finalOrderQty * editedProduct?.OrderRate,
                      FreeProductsList: updatedFreeProductsList,
                      UsedCount: finalOrderQty * prodLoyaltyPoint,
                    };
                  }

                  return offerProduct;
                }
              );
              dispatch(
                changeFullOfferAppliedProducts(updatedOfferAppliedProducts)
              );
            }
          }
        }
      } else if (isExistsInFreeProdList?.RemainingQty > 0) {
        // perform normal edit qty operation
        // console.log(editedProduct?.OrderQty, "editedProduct")
        // await handleNormalEditQuantity(editedProduct, editedProductIndex);

        if (finalOrderQty > isExistsInFreeProdList?.OverAllFreeQty) {
          // split paid and free product
          const paidProdQty =
            finalOrderQty - isExistsInFreeProdList?.OverAllFreeQty;
          const freeProdQty = editedQty - paidProdQty;
          const isAlreadyExistsInCart = CartOrderDetails?.findIndex(
            (cartItem) => {
              return (
                cartItem?.ProdId === editedProduct?.ProdId &&
                cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
                !cartItem?.OfferMode &&
                cartItem?.Offer === 0 &&
                cartItem?.BookingTypeName === editedProduct?.BookingTypeName &&
                cartItem?.OrderRate === editedProduct?.OrderRate
              );
            }
          );

          let updatedCart = [...CartOrderDetails];

          if (isAlreadyExistsInCart !== -1) {
            // update the existing paid product in cart
            updatedCart[isAlreadyExistsInCart] = {
              ...updatedCart[isAlreadyExistsInCart],
              OrderQty:
                updatedCart[isAlreadyExistsInCart]?.OrderQty + paidProdQty,
              ...calculateTaxAmounts({
                qty: updatedCart[isAlreadyExistsInCart]?.OrderQty + paidProdQty,
                rate: updatedCart[isAlreadyExistsInCart]?.OrderRate,
                taxPercentage:
                  updatedCart[isAlreadyExistsInCart]?.TaxPercentage,
              }),
            };
          } else {
            // add new paid product in cart
            const paidProduct = {
              localId: uuidv4(),
              ...editedProduct,
              OrderQty: paidProdQty,
              Offer: 0,
              OfferMode: null,
              OfferMessage: null,
              OfferType: null,
              ...calculateTaxAmounts({
                qty: paidProdQty,
                rate: editedProduct?.OrderRate,
                taxPercentage: editedProduct?.TaxPercentage,
              }),
            };
            updatedCart = [...updatedCart, paidProduct];
          }

          dispatch(
            changeOrderCardDetails(
              updatedCart?.map((prod) => {
                if (prod === editedProduct) {
                  return {
                    ...prod,
                    OrderQty: freeProdQty,
                    ...calculateTaxAmounts({
                      qty: freeProdQty,
                      rate: prod.OrderRate,
                      taxPercentage: prod.TaxPercentage,
                    }),
                    ...(prod?.Offer > 0 && {
                      Offer: freeProdQty * prod.OrderRate,
                    }),
                  };
                }
                return prod;
              })
            )
          );
        } else if (finalOrderQty === isExistsInFreeProdList?.OverAllFreeQty) {
          // Just need to update the Qty in Edited Product and FreeProductList and OfferAppliedProducts
          await handleNormalEditQuantity(
            editedProduct,
            editedProductIndex,
            editedQty,
            newPrice,
            true
          );
          const updatedFreeProdList = FreeProdList?.map((product) => {
            if (
              product?.FreeProdId === editedProduct?.ProdId &&
              product?.ProdVariantDetails?.some((variant) =>
                variant?.StockDetails?.some(
                  (stock) =>
                    stock?.FreeInwardDtlId === editedProduct?.InwardDtlId
                )
              ) &&
              product?.OfferId === editedProduct?.OfferMessage?.[0]?.OfferId &&
              product?.OfferMode === editedProduct?.OfferMode
            ) {
              return {
                ...product,
                FreeQty: finalOrderQty,
                RemainingQty: 0,
                discount: finalOrderQty * editedProduct?.OrderRate,
              };
            }
            return product;
          });
          dispatch(ChangeFullFreeProductList(updatedFreeProdList));
          const updatedOfferAppliedProducts = OfferAppliedProducts?.map(
            (offerProduct) => {
              // Check if this offer product contains the edited product in its free products list
              const hasMatchingFreeProduct =
                offerProduct?.FreeProductsList?.some((freeProduct) =>
                  freeProduct?.ProdVariantDetails?.some((variant) =>
                    variant?.StockDetails?.some(
                      (stock) =>
                        stock?.FreeInwardDtlId === editedProduct?.InwardDtlId
                    )
                  )
                );

              // Also check main offer conditions
              const isMatchingOffer =
                offerProduct?.OfferId ===
                  editedProduct?.OfferMessage?.[0]?.OfferId &&
                offerProduct?.OfferMode === editedProduct?.OfferMode;

              if (hasMatchingFreeProduct && isMatchingOffer) {
                // Get loyalty points from the matching free product
                const matchingFreeProduct =
                  offerProduct?.FreeProductsList?.find((freeProduct) =>
                    freeProduct?.ProdVariantDetails?.some((variant) =>
                      variant?.StockDetails?.some(
                        (stock) =>
                          stock?.FreeInwardDtlId === editedProduct?.InwardDtlId
                      )
                    )
                  );

                const prodLoyaltyPoint =
                  matchingFreeProduct?.ProdVariantDetails?.[0]
                    ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0;

                // Update the specific free product in the list
                const updatedFreeProductsList =
                  offerProduct?.FreeProductsList?.map((freeProduct) => {
                    const isTargetFreeProduct =
                      freeProduct?.ProdVariantDetails?.some((variant) =>
                        variant?.StockDetails?.some(
                          (stock) =>
                            stock?.FreeInwardDtlId ===
                            editedProduct?.InwardDtlId
                        )
                      );

                    if (isTargetFreeProduct) {
                      return {
                        ...freeProduct,
                        FreeQty: finalOrderQty,
                      };
                    }
                    return freeProduct;
                  });

                return {
                  ...offerProduct,
                  ActualFreeQty: finalOrderQty,
                  ActualOfferAmount: finalOrderQty * editedProduct?.OrderRate,
                  OfferAmount: finalOrderQty * editedProduct?.OrderRate,
                  OfferValue: finalOrderQty * editedProduct?.OrderRate,
                  FreeProductsList: updatedFreeProductsList,
                  UsedCount: finalOrderQty * prodLoyaltyPoint,
                };
              }

              return offerProduct;
            }
          );
          dispatch(changeFullOfferAppliedProducts(updatedOfferAppliedProducts));
        } else if (finalOrderQty < isExistsInFreeProdList?.OverAllFreeQty) {
          // Just need to update the Qty in Edited Product and FreeProductList and OfferAppliedProducts
          await handleNormalEditQuantity(
            editedProduct,
            editedProductIndex,
            editedQty,
            newPrice,
            true
          );
          const updatedFreeProdList = FreeProdList?.map((product) => {
            if (
              product?.FreeProdId === editedProduct?.ProdId &&
              product?.ProdVariantDetails?.some((variant) =>
                variant?.StockDetails?.some(
                  (stock) =>
                    stock?.FreeInwardDtlId === editedProduct?.InwardDtlId
                )
              ) &&
              product?.OfferId === editedProduct?.OfferMessage?.[0]?.OfferId &&
              product?.OfferMode === editedProduct?.OfferMode
            ) {
              return {
                ...product,
                FreeQty: finalOrderQty,
                RemainingQty: product?.OverAllFreeQty - finalOrderQty,
                discount: finalOrderQty * editedProduct?.OrderRate,
              };
            }
            return product;
          });
          dispatch(ChangeFullFreeProductList(updatedFreeProdList));
          const updatedOfferAppliedProducts = OfferAppliedProducts?.map(
            (offerProduct) => {
              // Check if this offer product contains the edited product in its free products list
              const hasMatchingFreeProduct =
                offerProduct?.FreeProductsList?.some((freeProduct) =>
                  freeProduct?.ProdVariantDetails?.some((variant) =>
                    variant?.StockDetails?.some(
                      (stock) =>
                        stock?.FreeInwardDtlId === editedProduct?.InwardDtlId
                    )
                  )
                );

              // Also check main offer conditions
              const isMatchingOffer =
                offerProduct?.OfferId ===
                  editedProduct?.OfferMessage?.[0]?.OfferId &&
                offerProduct?.OfferMode === editedProduct?.OfferMode;

              if (hasMatchingFreeProduct && isMatchingOffer) {
                // Get loyalty points from the matching free product
                const matchingFreeProduct =
                  offerProduct?.FreeProductsList?.find((freeProduct) =>
                    freeProduct?.ProdVariantDetails?.some((variant) =>
                      variant?.StockDetails?.some(
                        (stock) =>
                          stock?.FreeInwardDtlId === editedProduct?.InwardDtlId
                      )
                    )
                  );

                const prodLoyaltyPoint =
                  matchingFreeProduct?.ProdVariantDetails?.[0]
                    ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0;

                // Update the specific free product in the list
                const updatedFreeProductsList =
                  offerProduct?.FreeProductsList?.map((freeProduct) => {
                    const isTargetFreeProduct =
                      freeProduct?.ProdVariantDetails?.some((variant) =>
                        variant?.StockDetails?.some(
                          (stock) =>
                            stock?.FreeInwardDtlId ===
                            editedProduct?.InwardDtlId
                        )
                      );

                    if (isTargetFreeProduct) {
                      return {
                        ...freeProduct,
                        FreeQty: finalOrderQty,
                      };
                    }
                    return freeProduct;
                  });

                return {
                  ...offerProduct,
                  ActualFreeQty: finalOrderQty,
                  ActualOfferAmount: finalOrderQty * editedProduct?.OrderRate,
                  OfferAmount: finalOrderQty * editedProduct?.OrderRate,
                  OfferValue: finalOrderQty * editedProduct?.OrderRate,
                  FreeProductsList: updatedFreeProductsList,
                  UsedCount: finalOrderQty * prodLoyaltyPoint,
                };
              }

              return offerProduct;
            }
          );
          dispatch(changeFullOfferAppliedProducts(updatedOfferAppliedProducts));
        }
      }
    } else {
      // check is there any free product applicable for the edited product
      const isFreeProductApplicable = FreeProdList?.find((product) => {
        return (
          product?.ProdId === editedProduct?.ProdId &&
          product?.InwardDtlId === editedProduct?.InwardDtlId
        );
      });

      const sameProductInOtherBooking = CartOrderDetails?.find((cartItem) => {
        return (
          cartItem?.ProdId === editedProduct?.ProdId &&
          cartItem?.InwardDtlId === editedProduct?.InwardDtlId &&
          cartItem?.BookingTypeName !== editedProduct?.BookingTypeName
        );
      });

      const finalOrderQty =
        (sameProductInOtherBooking?.OrderQty || 0) + editedQty;

      if (isFreeProductApplicable && hasOffer) {
        const applicableFreeProducts =
          isFreeProductApplicable?.ProdVariantDetails;

        const freeProductVariants = applicableFreeProducts?.map((variant) => {
          return {
            ...variant,
            FreeProdId: isFreeProductApplicable?.FreeProdId,
            OfferId: isFreeProductApplicable?.OfferId,
            OfferMode: isFreeProductApplicable?.OfferMode,
          };
        });

        if (isFreeProductApplicable?.OverAllFreeQty > finalOrderQty) {
          if (isFreeProductApplicable?.FreeQty === 0) {
            await handleNormalEditQuantity(
              editedProduct,
              editedProductIndex,
              editedQty,
              newPrice
            );
            // update free product list (Set OverAllFreeQty = OrderQty and Remaining = OrderQty)
            const updatedFreeProdList = FreeProdList?.map((product) => {
              if (
                product?.ProdId === editedProduct?.ProdId &&
                product?.InwardDtlId === editedProduct?.InwardDtlId
              ) {
                return {
                  ...product,
                  FreeQty: 0,
                  OverAllFreeQty: finalOrderQty,
                  RemainingQty: finalOrderQty,
                  discount: finalOrderQty * editedProduct?.OrderRate,
                };
              }
              return product;
            });
            dispatch(ChangeFullFreeProductList(updatedFreeProdList));
          } else if (isFreeProductApplicable?.FreeQty <= finalOrderQty) {
            // check if there is any applicable free product in cart
            await handleNormalEditQuantity(
              editedProduct,
              editedProductIndex,
              editedQty,
              newPrice
            );
            const updatedFreeProdList = FreeProdList?.map((product) => {
              if (
                product?.ProdId === editedProduct?.ProdId &&
                product?.InwardDtlId === editedProduct?.InwardDtlId
              ) {
                return {
                  ...product,
                  OverAllFreeQty: finalOrderQty,
                  RemainingQty: finalOrderQty - product?.FreeQty,
                };
              }
              return product;
            });
            dispatch(ChangeFullFreeProductList(updatedFreeProdList));
          } else if (isFreeProductApplicable?.FreeQty > finalOrderQty) {
            // need to split free product and paid product
            let remainingPaidQty =
              isFreeProductApplicable?.FreeQty - finalOrderQty;
            const applicableFreeInCart = CartOrderDetails?.filter(
              (cartItem) => {
                return (
                  freeProductVariants?.some(
                    (variant) =>
                      variant.FreeProdId === cartItem.ProdId &&
                      variant?.StockDetails?.some(
                        (stock) =>
                          stock.FreeInwardDtlId === cartItem.InwardDtlId
                      )
                  ) &&
                  cartItem?.Offer &&
                  isFreeProductApplicable?.OfferId ===
                    cartItem?.OfferMessage?.[0]?.OfferId
                );
              }
            );
            const applicableFreeInCartAsPaid = CartOrderDetails?.filter(
              (cartItem) => {
                return (
                  freeProductVariants?.some(
                    (variant) =>
                      variant.FreeProdId === cartItem.ProdId &&
                      variant?.StockDetails?.some(
                        (stock) =>
                          stock.FreeInwardDtlId === cartItem.InwardDtlId
                      )
                  ) && !cartItem?.Offer
                );
              }
            );
            const sameBookingTypeProduct = applicableFreeInCart?.find(
              (cartItem) => {
                return (
                  cartItem?.BookingTypeName === editedProduct?.BookingTypeName
                );
              }
            );
            const otherBookingTypeProduct = applicableFreeInCart?.find(
              (cartItem) => {
                return (
                  cartItem?.BookingTypeName !== editedProduct?.BookingTypeName
                );
              }
            );
            const sameBookingTypeProductAsPaid =
              applicableFreeInCartAsPaid?.find((cartItem) => {
                return (
                  cartItem?.BookingTypeName === editedProduct?.BookingTypeName
                );
              });
            const otherBookingTypeProductAsPaid =
              applicableFreeInCartAsPaid?.find((cartItem) => {
                return (
                  cartItem?.BookingTypeName !== editedProduct?.BookingTypeName
                );
              });
            let updatedCart = [...CartOrderDetails];
            if (sameBookingTypeProduct) {
              if (sameBookingTypeProductAsPaid) {
                if (sameBookingTypeProduct?.OrderQty <= remainingPaidQty) {
                  updatedCart = updatedCart?.filter(
                    (cartItem) => cartItem !== sameBookingTypeProduct
                  );
                  updatedCart = updatedCart?.map((cartItem) => {
                    if (cartItem === sameBookingTypeProductAsPaid) {
                      const newItem = {
                        ...cartItem,
                        OrderQty:
                          cartItem.OrderQty + sameBookingTypeProduct?.OrderQty,
                        ...calculateTaxAmounts({
                          qty:
                            cartItem.OrderQty +
                            sameBookingTypeProduct?.OrderQty,
                          rate: cartItem.OrderRate,
                          taxPercentage: cartItem.TaxPercentage,
                        }),
                        Offer: 0,
                      };

                      delete newItem.OfferMode;
                      delete newItem.OfferMessage;
                      delete newItem.OfferType;

                      return newItem;
                    }
                    return cartItem;
                  });
                } else if (
                  sameBookingTypeProduct?.OrderQty > remainingPaidQty
                ) {
                  updatedCart = updatedCart?.map((cartItem) => {
                    if (cartItem === sameBookingTypeProduct) {
                      return {
                        ...cartItem,
                        OrderQty: cartItem.OrderQty - remainingPaidQty,
                        ...calculateTaxAmounts({
                          qty: cartItem.OrderQty - remainingPaidQty,
                          rate: cartItem.OrderRate,
                          taxPercentage: cartItem.TaxPercentage,
                        }),
                        Offer:
                          (cartItem?.OrderQty - remainingPaidQty) *
                          cartItem?.OrderRate,
                      };
                    } else if (cartItem === sameBookingTypeProductAsPaid) {
                      return {
                        ...cartItem,
                        OrderQty: cartItem?.OrderQty + remainingPaidQty,
                        ...calculateTaxAmounts({
                          qty: cartItem?.OrderQty + remainingPaidQty,
                          rate: cartItem?.OrderRate,
                          taxPercentage: cartItem?.TaxPercentage,
                        }),
                      };
                    }
                    return cartItem;
                  });
                }
              } else {
                if (sameBookingTypeProduct?.OrderQty <= remainingPaidQty) {
                  updatedCart = updatedCart?.map((cartItem) => {
                    if (cartItem === sameBookingTypeProduct) {
                      const newPaidProd = {
                        ...cartItem,
                        Offer: 0,
                      };

                      delete newPaidProd.OfferMode;
                      delete newPaidProd.OfferMessage;
                      delete newPaidProd.OfferType;
                      return newPaidProd;
                    }
                    return cartItem;
                  });
                } else if (
                  sameBookingTypeProduct?.OrderQty > remainingPaidQty
                ) {
                  const newPaidProduct = {
                    ...sameBookingTypeProduct,
                    OrderQty: remainingPaidQty,
                    Offer: 0,
                  };
                  delete newPaidProduct.OfferMode;
                  delete newPaidProduct.OfferMessage;
                  delete newPaidProduct.OfferType;
                  updatedCart = updatedCart?.map((cartItem) => {
                    if (cartItem === sameBookingTypeProduct) {
                      return {
                        ...cartItem,
                        OrderQty: cartItem.OrderQty - remainingPaidQty,
                        ...calculateTaxAmounts({
                          qty: cartItem?.OrderQty,
                          rate: cartItem?.OrderRate,
                          taxPercentage: cartItem?.TaxPercentage,
                        }),
                        Offer:
                          (cartItem?.OrderQty - remainingPaidQty) *
                          cartItem?.OrderRate,
                      };
                    }
                    return cartItem;
                  });
                  updatedCart = [...updatedCart, newPaidProduct];
                }
              }
              remainingPaidQty =
                remainingPaidQty - sameBookingTypeProduct?.OrderQty;
            }

            if (otherBookingTypeProduct && remainingPaidQty > 0) {
              if (otherBookingTypeProductAsPaid) {
                if (otherBookingTypeProduct?.OrderQty <= remainingPaidQty) {
                  updatedCart = updatedCart?.filter(
                    (cartItem) => cartItem !== otherBookingTypeProduct
                  );
                  updatedCart = updatedCart?.map((cartItem) => {
                    if (cartItem === otherBookingTypeProductAsPaid) {
                      const newItem = {
                        ...cartItem,
                        OrderQty:
                          cartItem.OrderQty + otherBookingTypeProduct?.OrderQty,
                        ...calculateTaxAmounts({
                          qty:
                            cartItem.OrderQty +
                            otherBookingTypeProduct?.OrderQty,
                          rate: cartItem.OrderRate,
                          taxPercentage: cartItem.TaxPercentage,
                        }),
                        Offer: 0,
                      };

                      delete newItem.OfferMode;
                      delete newItem.OfferMessage;
                      delete newItem.OfferType;

                      return newItem;
                    }
                    return cartItem;
                  });
                } else if (
                  otherBookingTypeProduct?.OrderQty > remainingPaidQty
                ) {
                  updatedCart = updatedCart?.map((cartItem) => {
                    if (cartItem === otherBookingTypeProduct) {
                      return {
                        ...cartItem,
                        OrderQty: cartItem.OrderQty - remainingPaidQty,
                        ...calculateTaxAmounts({
                          qty: cartItem.OrderQty - remainingPaidQty,
                          rate: cartItem.OrderRate,
                          taxPercentage: cartItem.TaxPercentage,
                        }),
                        Offer:
                          (cartItem?.OrderQty - remainingPaidQty) *
                          cartItem?.OrderRate,
                      };
                    } else if (cartItem === otherBookingTypeProductAsPaid) {
                      return {
                        ...cartItem,
                        OrderQty: cartItem?.OrderQty + remainingPaidQty,
                        ...calculateTaxAmounts({
                          qty: cartItem?.OrderQty + remainingPaidQty,
                          rate: cartItem?.OrderRate,
                          taxPercentage: cartItem?.TaxPercentage,
                        }),
                      };
                    }
                    return cartItem;
                  });
                }
              } else {
                if (otherBookingTypeProduct?.OrderQty <= remainingPaidQty) {
                  updatedCart = updatedCart?.map((cartItem) => {
                    if (cartItem === otherBookingTypeProduct) {
                      const newPaidProd = {
                        ...cartItem,
                        Offer: 0,
                      };
                      delete newPaidProd.OfferMode;
                      delete newPaidProd.OfferMessage;
                      delete newPaidProd.OfferType;
                      return newPaidProd;
                    }
                    return cartItem;
                  });
                } else if (
                  otherBookingTypeProduct?.OrderQty > remainingPaidQty
                ) {
                  const newPaidProduct = {
                    ...otherBookingTypeProduct,
                    OrderQty:
                      otherBookingTypeProduct?.OrderQty - remainingPaidQty,
                    Offer: 0,
                  };
                  delete newPaidProduct.OfferMode;
                  delete newPaidProduct.OfferMessage;
                  delete newPaidProduct.OfferType;
                  updatedCart = updatedCart?.map((cartItem) => {
                    if (cartItem === otherBookingTypeProduct) {
                      return {
                        ...cartItem,
                        OrderQty: cartItem.OrderQty - remainingPaidQty,
                        ...calculateTaxAmounts({
                          qty: cartItem?.OrderQty,
                          rate: cartItem?.OrderRate,
                          taxPercentage: cartItem?.TaxPercentage,
                        }),
                        Offer:
                          (cartItem?.OrderQty - remainingPaidQty) *
                          cartItem?.OrderRate,
                      };
                    }
                    return cartItem;
                  });
                  updatedCart = [...updatedCart, newPaidProduct];
                }
              }
            }

            updatedCart = updatedCart?.map((cartItem) => {
              if (cartItem === editedProduct) {
                return {
                  ...cartItem,
                  OrderQty: editedQty,
                  ...calculateTaxAmounts({
                    qty: editedQty,
                    rate: cartItem.OrderRate,
                    taxPercentage: cartItem.TaxPercentage,
                  }),
                };
              }
              return cartItem;
            });

            dispatch(changeOrderCardDetails(updatedCart));

            const updatedFreeProdList = FreeProdList?.map((product) => {
              if (
                product?.ProdId === editedProduct?.ProdId &&
                product?.InwardDtlId === editedProduct?.InwardDtlId &&
                product?.OfferId ===
                  (sameBookingTypeProduct?.OfferMessage?.[0]?.OfferId ||
                    otherBookingTypeProduct?.OfferMessage?.[0]?.OfferId) &&
                product?.OfferMode ===
                  (sameBookingTypeProduct?.OfferMode ||
                    otherBookingTypeProduct?.OfferMode)
              ) {
                return {
                  ...product,
                  FreeQty: finalOrderQty,
                  OverAllFreeQty: finalOrderQty,
                  RemainingQty: 0,
                  discount:
                    finalOrderQty *
                    (sameBookingTypeProduct?.OrderRate ||
                      otherBookingTypeProduct?.OrderRate),
                };
              }
              return product;
            });
            dispatch(ChangeFullFreeProductList(updatedFreeProdList));
            const updatedOfferAppliedProducts = OfferAppliedProducts?.map(
              (offerProduct) => {
                // Check if this offer product contains the edited product in its free products list
                const hasMatchingFreeProduct =
                  offerProduct?.FreeProductsList?.some((freeProduct) =>
                    freeProduct?.ProdVariantDetails?.some((variant) =>
                      variant?.StockDetails?.some(
                        (stock) =>
                          stock?.FreeInwardDtlId ===
                          (sameBookingTypeProduct?.InwardDtlId ||
                            otherBookingTypeProduct?.InwardDtlId)
                      )
                    )
                  );

                // Also check main offer conditions
                const isMatchingOffer =
                  offerProduct?.OfferId ===
                    (sameBookingTypeProduct?.OfferMessage?.[0]?.OfferId ||
                      otherBookingTypeProduct?.OfferMessage?.[0]?.OfferId) &&
                  offerProduct?.OfferMode ===
                    (sameBookingTypeProduct?.OfferMode ||
                      otherBookingTypeProduct?.OfferMode);

                if (hasMatchingFreeProduct && isMatchingOffer) {
                  // Get loyalty points from the matching free product
                  const matchingFreeProduct =
                    offerProduct?.FreeProductsList?.find((freeProduct) =>
                      freeProduct?.ProdVariantDetails?.some((variant) =>
                        variant?.StockDetails?.some(
                          (stock) =>
                            stock?.FreeInwardDtlId ===
                            (sameBookingTypeProduct?.InwardDtlId ||
                              otherBookingTypeProduct?.InwardDtlId)
                        )
                      )
                    );

                  const prodLoyaltyPoint =
                    matchingFreeProduct?.ProdVariantDetails?.[0]
                      ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0;

                  // Update the specific free product in the list
                  const updatedFreeProductsList =
                    offerProduct?.FreeProductsList?.map((freeProduct) => {
                      const isTargetFreeProduct =
                        freeProduct?.ProdVariantDetails?.some((variant) =>
                          variant?.StockDetails?.some(
                            (stock) =>
                              stock?.FreeInwardDtlId ===
                              (sameBookingTypeProduct?.InwardDtlId ||
                                otherBookingTypeProduct?.InwardDtlId)
                          )
                        );

                      if (isTargetFreeProduct) {
                        return {
                          ...freeProduct,
                          FreeQty: finalOrderQty,
                        };
                      }
                      return freeProduct;
                    });

                  return {
                    ...offerProduct,
                    ActualFreeQty: finalOrderQty,
                    ActualOfferAmount:
                      finalOrderQty *
                      (sameBookingTypeProduct?.OrderRate ||
                        otherBookingTypeProduct?.OrderRate),
                    OfferAmount:
                      finalOrderQty *
                      (sameBookingTypeProduct?.OrderRate ||
                        otherBookingTypeProduct?.OrderRate),
                    OfferValue:
                      finalOrderQty *
                      (sameBookingTypeProduct?.OrderRate ||
                        otherBookingTypeProduct?.OrderRate),
                    FreeProductsList: updatedFreeProductsList,
                    UsedCount: finalOrderQty * prodLoyaltyPoint,
                  };
                }

                return offerProduct;
              }
            );
            dispatch(
              changeFullOfferAppliedProducts(updatedOfferAppliedProducts)
            );
          }
        } else {
          if (isFreeProductApplicable?.FreeQty === 0) {
            await handleNormalEditQuantity(
              editedProduct,
              editedProductIndex,
              editedQty,
              newPrice
            );
            // update free product list (Set OverAllFreeQty = OrderQty and Remaining = OrderQty)
            const updatedFreeProdList = FreeProdList?.map((product) => {
              if (
                product?.ProdId === editedProduct?.ProdId &&
                product?.InwardDtlId === editedProduct?.InwardDtlId
              ) {
                return {
                  ...product,
                  FreeQty: 0,
                  OverAllFreeQty: finalOrderQty,
                  RemainingQty: finalOrderQty,
                  discount: finalOrderQty * editedProduct?.OrderRate,
                };
              }
              return product;
            });
            dispatch(ChangeFullFreeProductList(updatedFreeProdList));
          } else if (isFreeProductApplicable?.FreeQty === finalOrderQty) {
            dispatch(
              changeOrderCardDetails(
                updatedCart?.map((cartItem) => {
                  if (cartItem === editedProduct) {
                    return {
                      ...cartItem,
                      PackageDtl: PackageDtl,
                    };
                  }
                  return cartItem;
                })
              )
            );
            return;
          } else if (isFreeProductApplicable?.FreeQty < finalOrderQty) {
            // check if there is any applicable free product in cart
            console.log(freeProductVariants, 'freeProductVariants');
            const applicableFreeInCart = CartOrderDetails?.filter(
              (cartItem) => {
                return (
                  freeProductVariants?.some(
                    (variant) =>
                      variant.FreeProdId === cartItem.ProdId &&
                      variant?.StockDetails?.some(
                        (stock) =>
                          stock.FreeInwardDtlId === cartItem.InwardDtlId
                      )
                  ) && !cartItem?.Offer
                );
              }
            );

            const applicableOfferAppliedFreeInCart = CartOrderDetails?.filter(
              (cartItem) => {
                return (
                  freeProductVariants?.some(
                    (variant) =>
                      variant.FreeProdId === cartItem.ProdId &&
                      variant?.StockDetails?.some(
                        (stock) =>
                          stock.FreeInwardDtlId === cartItem.InwardDtlId
                      )
                  ) &&
                  cartItem?.Offer > 0 &&
                  isFreeProductApplicable?.OfferMode === cartItem?.OfferMode &&
                  isFreeProductApplicable?.OfferId ===
                    cartItem?.OfferMessage?.[0]?.OfferId
                );
              }
            );

            if (applicableFreeInCart?.length > 0) {
              console.log(applicableFreeInCart, 'applicableFreeInCart');
              const sameBookingTypeProduct = applicableFreeInCart?.find(
                (cartItem) => {
                  return (
                    cartItem?.BookingTypeName === editedProduct?.BookingTypeName
                  );
                }
              );
              const otherBookingTypeProduct = applicableFreeInCart?.find(
                (cartItem) => {
                  return (
                    cartItem?.BookingTypeName !== editedProduct?.BookingTypeName
                  );
                }
              );
              const sameBookingTypeFreeProduct =
                applicableOfferAppliedFreeInCart?.find((cartItem) => {
                  return (
                    cartItem?.BookingTypeName === editedProduct?.BookingTypeName
                  );
                });
              const otherBookingTypeFreeProduct =
                applicableOfferAppliedFreeInCart?.find((cartItem) => {
                  return (
                    cartItem?.BookingTypeName !== editedProduct?.BookingTypeName
                  );
                });
              // find how many qty need to be updated as free product
              const totalFreeQtyInCart = applicableFreeInCart?.reduce(
                (acc, item) => acc + item.OrderQty,
                0
              );
              const freeQtyNeeded =
                finalOrderQty - isFreeProductApplicable?.OverAllFreeQty;
              if (totalFreeQtyInCart === freeQtyNeeded) {
                let updatedCart = [...CartOrderDetails];
                if (sameBookingTypeProduct) {
                  if (sameBookingTypeFreeProduct) {
                    updatedCart = updatedCart?.filter(
                      (cartItem) => cartItem !== sameBookingTypeProduct
                    );
                    updatedCart = updatedCart?.map((cartItem) => {
                      if (cartItem === sameBookingTypeFreeProduct) {
                        return {
                          ...cartItem,
                          OrderQty:
                            cartItem.OrderQty +
                            sameBookingTypeProduct?.OrderQty,
                          ...calculateTaxAmounts({
                            qty:
                              cartItem.OrderQty +
                              sameBookingTypeProduct?.OrderQty,
                            rate: cartItem.OrderRate,
                            taxPercentage: cartItem.TaxPercentage,
                          }),
                          Offer:
                            (cartItem.OrderQty +
                              sameBookingTypeProduct?.OrderQty) *
                            cartItem.OrderRate,
                        };
                      }
                      return cartItem;
                    });
                  } else {
                    updatedCart = updatedCart?.map((cartItem) => {
                      if (cartItem === sameBookingTypeProduct) {
                        return {
                          ...cartItem,
                          Offer:
                            sameBookingTypeProduct?.OrderQty *
                            cartItem.OrderRate,
                          OfferMode: isFreeProductApplicable?.OfferMode,
                          OfferType: isFreeProductApplicable?.OfferType,
                          OfferMessage: [
                            {
                              OfferId: isFreeProductApplicable?.OfferId,
                              OfferName: isFreeProductApplicable?.OfferName,
                              OfferDescription:
                                isFreeProductApplicable?.OfferDescription,
                            },
                          ],
                        };
                      }
                      return cartItem;
                    });
                  }
                }

                if (otherBookingTypeProduct) {
                  if (otherBookingTypeFreeProduct) {
                    updatedCart = updatedCart?.filter(
                      (cartItem) => cartItem !== otherBookingTypeProduct
                    );
                    updatedCart = updatedCart?.map((cartItem) => {
                      if (
                        cartItem.ProdId === otherBookingTypeProduct.ProdId &&
                        cartItem.InwardDtlId ===
                          otherBookingTypeProduct.InwardDtlId &&
                        cartItem.BookingTypeName ===
                          otherBookingTypeProduct.BookingTypeName &&
                        cartItem.OrderRate ===
                          otherBookingTypeProduct.OrderRate &&
                        cartItem.OfferMode &&
                        cartItem.Offer > 0
                      ) {
                        return {
                          ...cartItem,
                          OrderQty:
                            cartItem.OrderQty +
                            otherBookingTypeProduct?.OrderQty,
                          ...calculateTaxAmounts({
                            qty:
                              cartItem.OrderQty +
                              otherBookingTypeProduct?.OrderQty,
                            rate: cartItem.OrderRate,
                            taxPercentage: cartItem.TaxPercentage,
                          }),
                          Offer:
                            (cartItem.OrderQty +
                              otherBookingTypeProduct?.OrderQty) *
                            cartItem.OrderRate,
                        };
                      }
                      return cartItem;
                    });
                  } else {
                    updatedCart = updatedCart?.map((cartItem) => {
                      if (cartItem === otherBookingTypeProduct) {
                        return {
                          ...cartItem,
                          Offer:
                            otherBookingTypeProduct?.OrderQty *
                            cartItem.OrderRate,
                          OfferMode: isFreeProductApplicable?.OfferMode,
                          OfferType: isFreeProductApplicable?.OfferType,
                          OfferMessage: [
                            {
                              OfferId: isFreeProductApplicable?.OfferId,
                              OfferName: isFreeProductApplicable?.OfferName,
                              OfferDescription:
                                isFreeProductApplicable?.OfferDescription,
                            },
                          ],
                        };
                      }
                      return cartItem;
                    });
                  }
                }
                updatedCart = updatedCart?.map((cartItem) => {
                  if (cartItem === editedProduct) {
                    return {
                      ...cartItem,
                      OrderQty: editedQty,
                      ...calculateTaxAmounts({
                        qty: editedQty,
                        rate: cartItem.OrderRate,
                        taxPercentage: cartItem.TaxPercentage,
                      }),
                      ...(cartItem?.Offer > 0 && {
                        Offer: editedQty * cartItem.OrderRate,
                      }),
                    };
                  }
                  return cartItem;
                });
                dispatch(changeOrderCardDetails(updatedCart));
                const updatedFreeProdList = FreeProdList?.map((product) => {
                  if (
                    product?.ProdId === editedProduct?.ProdId &&
                    product?.InwardDtlId === editedProduct?.InwardDtlId &&
                    product?.OfferId ===
                      (sameBookingTypeFreeProduct?.OfferMessage?.[0]?.OfferId ||
                        otherBookingTypeFreeProduct?.OfferMessage?.[0]
                          ?.OfferId) &&
                    product?.OfferMode ===
                      (sameBookingTypeFreeProduct?.OfferMode ||
                        otherBookingTypeFreeProduct?.OfferMode)
                  ) {
                    return {
                      ...product,
                      FreeQty: finalOrderQty,
                      OverAllFreeQty: finalOrderQty,
                      RemainingQty: 0,
                      discount:
                        finalOrderQty *
                        (sameBookingTypeProduct?.OrderRate ||
                          otherBookingTypeProduct?.OrderRate),
                    };
                  }
                  return product;
                });
                dispatch(ChangeFullFreeProductList(updatedFreeProdList));
                const updatedOfferAppliedProducts = OfferAppliedProducts?.map(
                  (offerProduct) => {
                    // Check if this offer product contains the edited product in its free products list
                    const hasMatchingFreeProduct =
                      offerProduct?.FreeProductsList?.some((freeProduct) =>
                        freeProduct?.ProdVariantDetails?.some((variant) =>
                          variant?.StockDetails?.some(
                            (stock) =>
                              stock?.FreeInwardDtlId ===
                              (sameBookingTypeFreeProduct?.InwardDtlId ||
                                otherBookingTypeProduct?.InwardDtlId)
                          )
                        )
                      );

                    // Also check main offer conditions
                    const isMatchingOffer =
                      offerProduct?.OfferId ===
                        (sameBookingTypeFreeProduct?.OfferMessage?.[0]
                          ?.OfferId ||
                          otherBookingTypeFreeProduct?.OfferMessage?.[0]
                            ?.OfferId) &&
                      offerProduct?.OfferMode ===
                        (sameBookingTypeFreeProduct?.OfferMode ||
                          otherBookingTypeFreeProduct?.OfferMode);

                    if (hasMatchingFreeProduct && isMatchingOffer) {
                      // Get loyalty points from the matching free product
                      const matchingFreeProduct =
                        offerProduct?.FreeProductsList?.find((freeProduct) =>
                          freeProduct?.ProdVariantDetails?.some((variant) =>
                            variant?.StockDetails?.some(
                              (stock) =>
                                stock?.FreeInwardDtlId ===
                                (sameBookingTypeProduct?.InwardDtlId ||
                                  otherBookingTypeProduct?.InwardDtlId)
                            )
                          )
                        );

                      const prodLoyaltyPoint =
                        matchingFreeProduct?.ProdVariantDetails?.[0]
                          ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0;

                      // Update the specific free product in the list
                      const updatedFreeProductsList =
                        offerProduct?.FreeProductsList?.map((freeProduct) => {
                          const isTargetFreeProduct =
                            freeProduct?.ProdVariantDetails?.some((variant) =>
                              variant?.StockDetails?.some(
                                (stock) =>
                                  stock?.FreeInwardDtlId ===
                                  (sameBookingTypeProduct?.InwardDtlId ||
                                    otherBookingTypeProduct?.InwardDtlId)
                              )
                            );

                          if (isTargetFreeProduct) {
                            return {
                              ...freeProduct,
                              FreeQty: finalOrderQty,
                            };
                          }
                          return freeProduct;
                        });

                      return {
                        ...offerProduct,
                        ActualFreeQty: finalOrderQty,
                        ActualOfferAmount:
                          finalOrderQty *
                          (sameBookingTypeProduct?.OrderRate ||
                            otherBookingTypeProduct?.OrderRate),
                        OfferAmount:
                          finalOrderQty *
                          (sameBookingTypeProduct?.OrderRate ||
                            otherBookingTypeProduct?.OrderRate),
                        OfferValue:
                          finalOrderQty *
                          (sameBookingTypeProduct?.OrderRate ||
                            otherBookingTypeProduct?.OrderRate),
                        FreeProductsList: updatedFreeProductsList,
                        UsedCount: finalOrderQty * prodLoyaltyPoint,
                      };
                    }

                    return offerProduct;
                  }
                );
                dispatch(
                  changeFullOfferAppliedProducts(updatedOfferAppliedProducts)
                );
              } else if (totalFreeQtyInCart > freeQtyNeeded) {
                let updatedCart = [...CartOrderDetails];
                if (sameBookingTypeProduct) {
                  // if available same booking type product qty is more than or equal to freeQtyNeeded.
                  // if more than then we need to update both free and paid product=
                  if (sameBookingTypeProduct?.OrderQty === freeQtyNeeded) {
                    if (sameBookingTypeFreeProduct) {
                      updatedCart = updatedCart?.filter(
                        (cartItem) => cartItem !== sameBookingTypeProduct
                      );
                      updatedCart = updatedCart?.map((cartItem) => {
                        if (
                          cartItem.ProdId === sameBookingTypeProduct.ProdId &&
                          cartItem.InwardDtlId ===
                            sameBookingTypeProduct.InwardDtlId &&
                          cartItem.BookingTypeName ===
                            sameBookingTypeProduct.BookingTypeName &&
                          cartItem.OrderRate ===
                            sameBookingTypeProduct.OrderRate &&
                          cartItem.OfferMode &&
                          cartItem.Offer > 0
                        ) {
                          return {
                            ...cartItem,
                            OrderQty:
                              cartItem.OrderQty +
                              sameBookingTypeProduct?.OrderQty,
                            ...calculateTaxAmounts({
                              qty:
                                cartItem.OrderQty +
                                sameBookingTypeProduct?.OrderQty,
                              rate: cartItem.OrderRate,
                              taxPercentage: cartItem.TaxPercentage,
                            }),
                            Offer:
                              (cartItem.OrderQty +
                                sameBookingTypeProduct?.OrderQty) *
                              cartItem.OrderRate,
                          };
                        }
                        return cartItem;
                      });
                    } else {
                      updatedCart = updatedCart?.map((cartItem) => {
                        if (cartItem === sameBookingTypeProduct) {
                          return {
                            ...cartItem,
                            Offer:
                              sameBookingTypeProduct?.OrderQty *
                              cartItem.OrderRate,
                            OfferMode: isFreeProductApplicable?.OfferMode,
                            OfferType: isFreeProductApplicable?.OfferType,
                            OfferMessage: [
                              {
                                OfferId: isFreeProductApplicable?.OfferId,
                                OfferName: isFreeProductApplicable?.OfferName,
                                OfferDescription:
                                  isFreeProductApplicable?.OfferDescription,
                              },
                            ],
                          };
                        }
                        return cartItem;
                      });
                    }
                  } else if (sameBookingTypeProduct?.OrderQty > freeQtyNeeded) {
                    if (sameBookingTypeFreeProduct) {
                      updatedCart = updatedCart?.map((cartItem) => {
                        if (
                          cartItem.ProdId === sameBookingTypeProduct.ProdId &&
                          cartItem.InwardDtlId ===
                            sameBookingTypeProduct.InwardDtlId &&
                          cartItem.BookingTypeName ===
                            sameBookingTypeProduct.BookingTypeName &&
                          cartItem.OrderRate ===
                            sameBookingTypeProduct.OrderRate &&
                          cartItem.OfferMode &&
                          cartItem.Offer > 0
                        ) {
                          return {
                            ...cartItem,
                            OrderQty: cartItem.OrderQty + freeQtyNeeded,
                            ...calculateTaxAmounts({
                              qty: cartItem.OrderQty + freeQtyNeeded,
                              rate: cartItem.OrderRate,
                              taxPercentage: cartItem.TaxPercentage,
                            }),
                            Offer:
                              (cartItem.OrderQty + freeQtyNeeded) *
                              cartItem.OrderRate,
                          };
                        } else if (cartItem === sameBookingTypeProduct) {
                          return {
                            ...cartItem,
                            OrderQty: cartItem.OrderQty - freeQtyNeeded,
                            ...calculateTaxAmounts({
                              qty: cartItem.OrderQty - freeQtyNeeded,
                              rate: cartItem.OrderRate,
                              taxPercentage: cartItem.TaxPercentage,
                            }),
                          };
                        }
                        return cartItem;
                      });
                    } else {
                      const remainingPaidQty =
                        sameBookingTypeProduct?.OrderQty - freeQtyNeeded;
                      updatedCart = updatedCart?.map((cartItem) => {
                        if (cartItem === sameBookingTypeProduct) {
                          return {
                            ...cartItem,
                            OrderQty: remainingPaidQty,
                            ...calculateTaxAmounts({
                              qty: remainingPaidQty,
                              rate: cartItem.OrderRate,
                              taxPercentage: cartItem.TaxPercentage,
                            }),
                          };
                        }
                        return cartItem;
                      });
                      const freeProduct = {
                        ...sameBookingTypeProduct,
                        OrderQty: freeQtyNeeded,
                        ...calculateTaxAmounts({
                          qty: freeQtyNeeded,
                          rate: sameBookingTypeProduct.OrderRate,
                          taxPercentage: sameBookingTypeProduct.TaxPercentage,
                        }),
                        Offer: freeQtyNeeded * sameBookingTypeProduct.OrderRate,
                        OfferMode: isFreeProductApplicable?.OfferMode,
                        OfferType: isFreeProductApplicable?.OfferType,
                        OfferMessage: [
                          {
                            OfferId: isFreeProductApplicable?.OfferId,
                            OfferName: isFreeProductApplicable?.OfferName,
                            OfferDescription:
                              isFreeProductApplicable?.OfferDescription,
                          },
                        ],
                        localId: uuidv4(),
                      };
                      updatedCart = [...updatedCart, freeProduct];
                    }
                  }
                }

                if (
                  otherBookingTypeProduct &&
                  freeQtyNeeded > (sameBookingTypeProduct?.OrderQty || 0)
                ) {
                  const remainingFreeQtyNeeded =
                    freeQtyNeeded - (sameBookingTypeProduct?.OrderQty || 0);
                  if (
                    remainingFreeQtyNeeded === otherBookingTypeProduct?.OrderQty
                  ) {
                    if (otherBookingTypeFreeProduct) {
                      updatedCart = updatedCart?.filter(
                        (cartItem) => cartItem !== otherBookingTypeProduct
                      );
                      updatedCart = updatedCart?.map((cartItem) => {
                        if (
                          cartItem.ProdId === otherBookingTypeProduct.ProdId &&
                          cartItem?.InwardDtlId ===
                            otherBookingTypeProduct.InwardDtlId &&
                          cartItem?.BookingTypeName ===
                            otherBookingTypeProduct.BookingTypeName &&
                          cartItem?.OrderRate ===
                            otherBookingTypeProduct.OrderRate &&
                          cartItem?.OfferMode &&
                          cartItem?.Offer > 0
                        ) {
                          return {
                            ...cartItem,
                            OrderQty:
                              cartItem.OrderQty +
                              otherBookingTypeProduct?.OrderQty,
                            ...calculateTaxAmounts({
                              qty:
                                cartItem.OrderQty +
                                otherBookingTypeProduct?.OrderQty,
                              rate: cartItem.OrderRate,
                              taxPercentage: cartItem.TaxPercentage,
                            }),
                            Offer:
                              (cartItem.OrderQty +
                                otherBookingTypeProduct?.OrderQty) *
                              cartItem.OrderRate,
                          };
                        }
                        return cartItem;
                      });
                    } else {
                      updatedCart = updatedCart?.map((cartItem) => {
                        if (
                          cartItem.ProdId === otherBookingTypeProduct.ProdId &&
                          cartItem.InwardDtlId ===
                            otherBookingTypeProduct.InwardDtlId &&
                          cartItem.BookingTypeName ===
                            otherBookingTypeProduct.BookingTypeName &&
                          cartItem.OrderRate ===
                            otherBookingTypeProduct.OrderRate &&
                          cartItem.OfferMode &&
                          cartItem.Offer > 0
                        ) {
                          return {
                            ...cartItem,
                            Offer: cartItem.OrderQty * cartItem.OrderRate,
                            OfferMode: isFreeProductApplicable?.OfferMode,
                            OfferType: isFreeProductApplicable?.OfferType,
                            OfferMessage: [
                              {
                                OfferId: isFreeProductApplicable?.OfferId,
                                OfferName: isFreeProductApplicable?.OfferName,
                                OfferDescription:
                                  isFreeProductApplicable?.OfferDescription,
                              },
                            ],
                          };
                        }
                        return cartItem;
                      });
                    }
                  } else if (
                    otherBookingTypeProduct?.OrderQty > remainingFreeQtyNeeded
                  ) {
                    if (otherBookingTypeFreeProduct) {
                      updatedCart = updatedCart?.map((cartItem) => {
                        if (
                          cartItem.ProdId === otherBookingTypeProduct.ProdId &&
                          cartItem.InwardDtlId ===
                            otherBookingTypeProduct.InwardDtlId &&
                          cartItem.BookingTypeName ===
                            otherBookingTypeProduct.BookingTypeName &&
                          cartItem.OrderRate ===
                            otherBookingTypeProduct.OrderRate &&
                          cartItem.OfferMode &&
                          cartItem.Offer > 0
                        ) {
                          return {
                            ...cartItem,
                            OrderQty:
                              cartItem.OrderQty + remainingFreeQtyNeeded,
                            ...calculateTaxAmounts({
                              qty: cartItem.OrderQty + remainingFreeQtyNeeded,
                              rate: cartItem.OrderRate,
                              taxPercentage: cartItem.TaxPercentage,
                            }),
                            Offer:
                              (cartItem.OrderQty + remainingFreeQtyNeeded) *
                              cartItem.OrderRate,
                          };
                        } else if (cartItem === otherBookingTypeProduct) {
                          return {
                            ...cartItem,
                            OrderQty:
                              cartItem.OrderQty - remainingFreeQtyNeeded,
                            ...calculateTaxAmounts({
                              qty: cartItem.OrderQty - remainingFreeQtyNeeded,
                              rate: cartItem.OrderRate,
                              taxPercentage: cartItem.TaxPercentage,
                            }),
                          };
                        }
                        return cartItem;
                      });
                    } else {
                      const remainingPaidQty =
                        otherBookingTypeProduct?.OrderQty -
                        remainingFreeQtyNeeded;
                      const newFreeProduct = {
                        ...otherBookingTypeProduct,
                        OrderQty: remainingFreeQtyNeeded,
                        ...calculateTaxAmounts({
                          qty: remainingFreeQtyNeeded,
                          rate: otherBookingTypeProduct.OrderRate,
                          taxPercentage: otherBookingTypeProduct.TaxPercentage,
                        }),
                        Offer:
                          remainingFreeQtyNeeded *
                          otherBookingTypeProduct.OrderRate,
                        OfferMode: isFreeProductApplicable?.OfferMode,
                        OfferType: isFreeProductApplicable?.OfferType,
                        OfferMessage: [
                          {
                            OfferId: isFreeProductApplicable?.OfferId,
                            OfferName: isFreeProductApplicable?.OfferName,
                            OfferDescription:
                              isFreeProductApplicable?.OfferDescription,
                          },
                        ],
                        localId: uuidv4(),
                      };
                      updatedCart = updatedCart?.map((cartItem) => {
                        if (cartItem === otherBookingTypeProduct) {
                          return {
                            ...cartItem,
                            OrderQty: remainingPaidQty,
                            ...calculateTaxAmounts({
                              qty: remainingPaidQty,
                              rate: cartItem.OrderRate,
                              taxPercentage: cartItem.TaxPercentage,
                            }),
                          };
                        }
                        return cartItem;
                      });
                      updatedCart = [...updatedCart, newFreeProduct];
                    }
                  }
                }
                updatedCart = updatedCart?.map((cartItem) => {
                  if (cartItem === editedProduct) {
                    return {
                      ...cartItem,
                      OrderQty: editedQty,
                      ...calculateTaxAmounts({
                        qty: editedQty,
                        rate: cartItem.OrderRate,
                        taxPercentage: cartItem.TaxPercentage,
                      }),
                      ...(cartItem?.Offer > 0 && {
                        Offer: editedQty * cartItem.OrderRate,
                      }),
                    };
                  }
                  return cartItem;
                });
                dispatch(changeOrderCardDetails(updatedCart));
                const updatedFreeProdList = FreeProdList?.map((product) => {
                  if (
                    product?.ProdId === editedProduct?.ProdId &&
                    product?.InwardDtlId === editedProduct?.InwardDtlId &&
                    product?.OfferId ===
                      (sameBookingTypeFreeProduct?.OfferMessage?.[0]?.OfferId ||
                        otherBookingTypeFreeProduct?.OfferMessage?.[0]
                          ?.OfferId) &&
                    product?.OfferMode ===
                      (sameBookingTypeFreeProduct?.OfferMode ||
                        otherBookingTypeFreeProduct?.OfferMode)
                  ) {
                    return {
                      ...product,
                      FreeQty: finalOrderQty,
                      OverAllFreeQty: finalOrderQty,
                      RemainingQty: 0,
                      discount:
                        finalOrderQty *
                        (sameBookingTypeProduct?.OrderRate ||
                          otherBookingTypeProduct?.OrderRate),
                    };
                  }
                  return product;
                });
                dispatch(ChangeFullFreeProductList(updatedFreeProdList));
                const updatedOfferAppliedProducts = OfferAppliedProducts?.map(
                  (offerProduct) => {
                    // Check if this offer product contains the edited product in its free products list
                    const hasMatchingFreeProduct =
                      offerProduct?.FreeProductsList?.some((freeProduct) =>
                        freeProduct?.ProdVariantDetails?.some((variant) =>
                          variant?.StockDetails?.some(
                            (stock) =>
                              stock?.FreeInwardDtlId ===
                              (sameBookingTypeProduct?.InwardDtlId ||
                                otherBookingTypeProduct?.InwardDtlId)
                          )
                        )
                      );

                    // Also check main offer conditions
                    const isMatchingOffer =
                      offerProduct?.OfferId ===
                        (sameBookingTypeProduct?.OfferMessage?.[0]?.OfferId ||
                          otherBookingTypeProduct?.OfferMessage?.[0]
                            ?.OfferId) &&
                      offerProduct?.OfferMode ===
                        (sameBookingTypeProduct?.OfferMode ||
                          otherBookingTypeProduct?.OfferMode);

                    if (hasMatchingFreeProduct && isMatchingOffer) {
                      // Get loyalty points from the matching free product
                      const matchingFreeProduct =
                        offerProduct?.FreeProductsList?.find((freeProduct) =>
                          freeProduct?.ProdVariantDetails?.some((variant) =>
                            variant?.StockDetails?.some(
                              (stock) =>
                                stock?.FreeInwardDtlId ===
                                (sameBookingTypeProduct?.InwardDtlId ||
                                  otherBookingTypeProduct?.InwardDtlId)
                            )
                          )
                        );

                      const prodLoyaltyPoint =
                        matchingFreeProduct?.ProdVariantDetails?.[0]
                          ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0;

                      // Update the specific free product in the list
                      const updatedFreeProductsList =
                        offerProduct?.FreeProductsList?.map((freeProduct) => {
                          const isTargetFreeProduct =
                            freeProduct?.ProdVariantDetails?.some((variant) =>
                              variant?.StockDetails?.some(
                                (stock) =>
                                  stock?.FreeInwardDtlId ===
                                  (sameBookingTypeProduct?.InwardDtlId ||
                                    otherBookingTypeProduct?.InwardDtlId)
                              )
                            );

                          if (isTargetFreeProduct) {
                            return {
                              ...freeProduct,
                              FreeQty: finalOrderQty,
                            };
                          }
                          return freeProduct;
                        });

                      return {
                        ...offerProduct,
                        ActualFreeQty: finalOrderQty,
                        ActualOfferAmount:
                          finalOrderQty *
                          (sameBookingTypeProduct?.OrderRate ||
                            otherBookingTypeProduct?.OrderRate),
                        OfferAmount:
                          finalOrderQty *
                          (sameBookingTypeProduct?.OrderRate ||
                            otherBookingTypeProduct?.OrderRate),
                        OfferValue:
                          finalOrderQty *
                          (sameBookingTypeProduct?.OrderRate ||
                            otherBookingTypeProduct?.OrderRate),
                        FreeProductsList: updatedFreeProductsList,
                        UsedCount: finalOrderQty * prodLoyaltyPoint,
                      };
                    }

                    return offerProduct;
                  }
                );
                dispatch(
                  changeFullOfferAppliedProducts(updatedOfferAppliedProducts)
                );
              } else if (totalFreeQtyInCart < freeQtyNeeded) {
                let updatedCart = [...CartOrderDetails];
                if (sameBookingTypeProduct) {
                  if (sameBookingTypeFreeProduct) {
                    updatedCart = updatedCart?.filter(
                      (cartItem) => cartItem !== sameBookingTypeProduct
                    );
                    updatedCart = updatedCart?.map((cartItem) => {
                      if (
                        cartItem.ProdId === sameBookingTypeProduct.ProdId &&
                        cartItem.InwardDtlId ===
                          sameBookingTypeProduct.InwardDtlId &&
                        cartItem.BookingTypeName ===
                          sameBookingTypeProduct.BookingTypeName &&
                        cartItem.OrderRate ===
                          sameBookingTypeProduct.OrderRate &&
                        cartItem.OfferMode &&
                        cartItem.Offer > 0
                      ) {
                        return {
                          ...cartItem,
                          OrderQty:
                            cartItem.OrderQty +
                            sameBookingTypeProduct?.OrderQty,
                          ...calculateTaxAmounts({
                            qty:
                              cartItem.OrderQty +
                              sameBookingTypeProduct?.OrderQty,
                            rate: cartItem.OrderRate,
                            taxPercentage: cartItem.TaxPercentage,
                          }),
                          Offer:
                            (cartItem.OrderQty +
                              sameBookingTypeProduct?.OrderQty) *
                            cartItem.OrderRate,
                        };
                      }
                      return cartItem;
                    });
                  } else {
                    updatedCart = updatedCart?.map((cartItem) => {
                      if (cartItem === sameBookingTypeProduct) {
                        return {
                          ...cartItem,
                          Offer:
                            (cartItem.OrderQty +
                              sameBookingTypeProduct?.OrderQty) *
                            cartItem.OrderRate,
                          OfferMode: isFreeProductApplicable?.OfferMode,
                          OfferType: isFreeProductApplicable?.OfferType,
                          OfferMessage: [
                            {
                              OfferId: isFreeProductApplicable?.OfferId,
                              OfferName: isFreeProductApplicable?.OfferName,
                              OfferDescription:
                                isFreeProductApplicable?.OfferDescription,
                            },
                          ],
                        };
                      }
                      return cartItem;
                    });
                  }
                }

                if (otherBookingTypeProduct) {
                  if (otherBookingTypeFreeProduct) {
                    updatedCart = updatedCart?.filter(
                      (cartItem) => cartItem !== otherBookingTypeProduct
                    );
                    updatedCart = updatedCart?.map((cartItem) => {
                      if (
                        cartItem.ProdId === otherBookingTypeProduct.ProdId &&
                        cartItem.InwardDtlId ===
                          otherBookingTypeProduct.InwardDtlId &&
                        cartItem.BookingTypeName ===
                          otherBookingTypeProduct.BookingTypeName &&
                        cartItem.OrderRate ===
                          otherBookingTypeProduct.OrderRate &&
                        cartItem.OfferMode &&
                        cartItem.Offer > 0
                      ) {
                        return {
                          ...cartItem,
                          OrderQty:
                            cartItem.OrderQty +
                            otherBookingTypeProduct?.OrderQty,
                          ...calculateTaxAmounts({
                            qty:
                              cartItem.OrderQty +
                              otherBookingTypeProduct?.OrderQty,
                            rate: cartItem.OrderRate,
                            taxPercentage: cartItem.TaxPercentage,
                          }),
                          Offer:
                            (cartItem.OrderQty +
                              otherBookingTypeProduct?.OrderQty) *
                            cartItem.OrderRate,
                        };
                      }
                      return cartItem;
                    });
                  } else {
                    updatedCart = updatedCart?.map((cartItem) => {
                      if (cartItem === otherBookingTypeProduct) {
                        return {
                          ...cartItem,
                          Offer:
                            otherBookingTypeProduct?.OrderQty *
                            cartItem.OrderRate,
                          OfferMode: isFreeProductApplicable?.OfferMode,
                          OfferType: isFreeProductApplicable?.OfferType,
                          OfferMessage: [
                            {
                              OfferId: isFreeProductApplicable?.OfferId,
                              OfferName: isFreeProductApplicable?.OfferName,
                              OfferDescription:
                                isFreeProductApplicable?.OfferDescription,
                            },
                          ],
                        };
                      }
                      return cartItem;
                    });
                  }
                }
                updatedCart = updatedCart?.map((cartItem) => {
                  if (cartItem === editedProduct) {
                    return {
                      ...cartItem,
                      OrderQty: editedQty,
                      ...calculateTaxAmounts({
                        qty: editedQty,
                        rate: cartItem.OrderRate,
                        taxPercentage: cartItem.TaxPercentage,
                      }),
                      ...(cartItem?.Offer > 0 && {
                        Offer: editedQty * cartItem.OrderRate,
                      }),
                    };
                  }
                  return cartItem;
                });
                dispatch(changeOrderCardDetails(updatedCart));
                const remainingQty = freeQtyNeeded - totalFreeQtyInCart;
                const updatedFreeProdList = FreeProdList?.map((product) => {
                  if (
                    product?.ProdId === editedProduct?.ProdId &&
                    product?.InwardDtlId === editedProduct?.InwardDtlId &&
                    product?.OfferId ===
                      (sameBookingTypeFreeProduct?.OfferMessage?.[0]?.OfferId ||
                        otherBookingTypeFreeProduct?.OfferMessage?.[0]
                          ?.OfferId) &&
                    product?.OfferMode ===
                      (sameBookingTypeFreeProduct?.OfferMode ||
                        otherBookingTypeFreeProduct?.OfferMode)
                  ) {
                    return {
                      ...product,
                      FreeQty: finalOrderQty - remainingQty,
                      OverAllFreeQty: finalOrderQty,
                      RemainingQty: remainingQty,
                      discount:
                        (finalOrderQty - remainingQty) *
                        (sameBookingTypeProduct?.OrderRate ||
                          otherBookingTypeProduct?.OrderRate),
                    };
                  }
                  return product;
                });
                dispatch(ChangeFullFreeProductList(updatedFreeProdList));
                const updatedOfferAppliedProducts = OfferAppliedProducts?.map(
                  (offerProduct) => {
                    // Check if this offer product contains the edited product in its free products list
                    const hasMatchingFreeProduct =
                      offerProduct?.FreeProductsList?.some((freeProduct) =>
                        freeProduct?.ProdVariantDetails?.some((variant) =>
                          variant?.StockDetails?.some(
                            (stock) =>
                              stock?.FreeInwardDtlId ===
                              (sameBookingTypeProduct?.InwardDtlId ||
                                otherBookingTypeProduct?.InwardDtlId)
                          )
                        )
                      );

                    // Also check main offer conditions
                    const isMatchingOffer =
                      offerProduct?.OfferId ===
                        (sameBookingTypeProduct?.OfferMessage?.[0]?.OfferId ||
                          otherBookingTypeProduct?.OfferMessage?.[0]
                            ?.OfferId) &&
                      offerProduct?.OfferMode ===
                        (sameBookingTypeProduct?.OfferMode ||
                          otherBookingTypeProduct?.OfferMode);

                    if (hasMatchingFreeProduct && isMatchingOffer) {
                      // Get loyalty points from the matching free product
                      const matchingFreeProduct =
                        offerProduct?.FreeProductsList?.find((freeProduct) =>
                          freeProduct?.ProdVariantDetails?.some((variant) =>
                            variant?.StockDetails?.some(
                              (stock) =>
                                stock?.FreeInwardDtlId ===
                                (sameBookingTypeProduct?.InwardDtlId ||
                                  otherBookingTypeProduct?.InwardDtlId)
                            )
                          )
                        );

                      const prodLoyaltyPoint =
                        matchingFreeProduct?.ProdVariantDetails?.[0]
                          ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0;

                      // Update the specific free product in the list
                      const updatedFreeProductsList =
                        offerProduct?.FreeProductsList?.map((freeProduct) => {
                          const isTargetFreeProduct =
                            freeProduct?.ProdVariantDetails?.some((variant) =>
                              variant?.StockDetails?.some(
                                (stock) =>
                                  stock?.FreeInwardDtlId ===
                                  (sameBookingTypeProduct?.InwardDtlId ||
                                    otherBookingTypeProduct?.InwardDtlId)
                              )
                            );

                          if (isTargetFreeProduct) {
                            return {
                              ...freeProduct,
                              FreeQty: finalOrderQty - remainingQty,
                            };
                          }
                          return freeProduct;
                        });

                      return {
                        ...offerProduct,
                        ActualFreeQty: finalOrderQty - remainingQty,
                        ActualOfferAmount:
                          (finalOrderQty - remainingQty) *
                          (sameBookingTypeProduct?.OrderRate ||
                            otherBookingTypeProduct?.OrderRate),
                        OfferAmount:
                          (finalOrderQty - remainingQty) *
                          (sameBookingTypeProduct?.OrderRate ||
                            otherBookingTypeProduct?.OrderRate),
                        OfferValue:
                          (finalOrderQty - remainingQty) *
                          (sameBookingTypeProduct?.OrderRate ||
                            otherBookingTypeProduct?.OrderRate),
                        FreeProductsList: updatedFreeProductsList,
                        UsedCount:
                          (finalOrderQty - remainingQty) * prodLoyaltyPoint,
                      };
                    }

                    return offerProduct;
                  }
                );
                dispatch(
                  changeFullOfferAppliedProducts(updatedOfferAppliedProducts)
                );
              }
            } else {
              // just update the free product list
              await handleNormalEditQuantity(
                editedProduct,
                editedProductIndex,
                editedQty,
                newPrice
              );
              const updatedFreeProdList = FreeProdList?.map((product) => {
                if (
                  product?.ProdId === editedProduct?.ProdId &&
                  product?.InwardDtlId === editedProduct?.InwardDtlId
                ) {
                  return {
                    ...product,
                    OverAllFreeQty: finalOrderQty,
                    RemainingQty: finalOrderQty - product?.FreeQty,
                    discount: finalOrderQty * editedProduct?.OrderRate,
                  };
                }
                return product;
              });
              dispatch(ChangeFullFreeProductList(updatedFreeProdList));
            }
          }
        }
      } else {
        await handleNormalEditQuantity(
          editedProduct,
          editedProductIndex,
          editedQty,
          newPrice
        );
      }
    }
  };

  const handleNormalEditQuantity = async (
    editedProduct,
    index,
    qty,
    newPrice = 0,
    offerApply = false
  ) => {
    const updatedProduct = {
      ...editedProduct,
      OrderQty: qty,
      OrderRate: newPrice > 0 ? newPrice : editedProduct?.OrderRate,
      ...calculateTaxAmounts({
        qty: qty,
        rate: newPrice > 0 ? newPrice : editedProduct?.OrderRate,
        taxPercentage: editedProduct?.TaxPercentage,
        type: editedProduct?.Type,
        product: editedProduct,
      }),
      PackageDtl: PackageDtl,
      // ✅ FIXED: Proper conditional property assignment
      ...(offerApply && {
        Offer: qty * (newPrice > 0 ? newPrice : editedProduct?.OrderRate),
      }),
    };

    if (hasOffer) {
      const offers = validateOffers(
        updatedProduct,
        OverAllproductBasedOfferDatas,
        CartOrderDetails,
        TakAwayId,
        DineinId
      );
      if (!offers?.length) {
        if (updatedProduct?.OfferType && updatedProduct?.Offer > 0) {
          dispatch(
            RemoveOfferAppliedProduct({
              ProdId: updatedProduct?.ProdId,
              InwardDtlId: updatedProduct?.InwardDtlId,
              OfferType: updatedProduct?.OfferType,
            })
          );
        }
        dispatch(
          changeOrderCardDetails(
            CartOrderDetails?.map((i) =>
              i?.InwardDtlId == updatedProduct?.InwardDtlId &&
              i?.BookingTypeName == updatedProduct?.BookingTypeName &&
              i?.localId === updatedProduct?.localId
                ? {
                    ...updatedProduct,
                    Offer: 0,
                    OfferType:
                      updatedProduct?.Type === 'C'
                        ? updatedProduct?.OfferType
                        : null,
                    OfferMessage: null,
                  }
                : i
            )
          )
        );
        return;
      }

      let bestOffer = null;
      for (const offer of offers) {
        if (!bestOffer || offer.OfferAmount > bestOffer.OfferAmount) {
          bestOffer = offer;
        }
      }

      const UpdatedCartItemWithOffer = {
        ...updatedProduct,
        Offer:
          bestOffer?.OfferMode === 'I' || bestOffer?.OfferMode === 'Q'
            ? bestOffer?.OfferAmount || updatedProduct.Offer
            : updatedProduct.Offer || bestOffer?.OfferAmount,
        OfferType: updatedProduct?.OfferType || bestOffer?.OfferType,
        OfferMessage: updatedProduct?.OfferMessage || bestOffer?.OfferMessage,
      };

      console.log(updatedProduct, 'updatedProduct');

      const shouldRemove = (c) =>
        c.ProdId === updatedProduct.ProdId &&
        c.InwardDtlId === updatedProduct.InwardDtlId &&
        c.OrderRate === updatedProduct.OrderRate &&
        c.BookingTypeName === updatedProduct.BookingTypeName &&
        !c.SalesId &&
        ((c?.OfferModeType && c?.OfferMode === 'B'
          ? true
          : c?.OfferMode !== 'B') &&
        c?.OfferMode !== 'P' &&
        c?.OfferMode !== 'C' &&
        c?.OfferMode !== 'O' &&
        c?.OfferMode !== 'L'
          ? true
          : c?.Offer === 0);

      const filteredCart = CartOrderDetails?.filter((c) => !shouldRemove(c));
      const updatedCartData = [UpdatedCartItemWithOffer, ...filteredCart];

      if (bestOffer) {
        dispatch(ChangeOfferAppliedProducts(bestOffer));
      }

      dispatch(changeOrderCardDetails(updatedCartData));
    } else {
      const updatedData = [...CartOrderDetails];
      updatedData[index] = updatedProduct;
      dispatch(changeOrderCardDetails(updatedData));
    }
  };

  const calculateTaxAmounts = ({
    qty,
    rate,
    taxPercentage,
    type = null,
    product = {},
    isOfferApply = false,
  }) => {
    const { OfferType = null, OfferPrice = 0 } = product;
    const totalAmount = qty * rate;
    const taxAmount = (
      (totalAmount * taxPercentage) /
      (100 + taxPercentage)
    ).toFixed(2);
    const withoutTaxRate = (totalAmount - taxAmount).toFixed(2);
    const offerValue =
      type === 'C'
        ? OfferType === 'F'
          ? qty * OfferPrice
          : (qty * rate * OfferPrice) / 100
        : null;

    return {
      TotalAmt:
        type === 'C' && OfferPrice > 0
          ? totalAmount - (offerValue || 0)
          : totalAmount,
      TaxAmt: parseFloat(taxAmount),
      WithoutTaxRate: parseFloat(withoutTaxRate),
      OfferValue: offerValue,
    };
  };

  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const SellingPriceChange = (data) => {
    if (props.Productdata?.Offer > 0) {
      setMessageData(
        'You cant Change Price Because You Applied Offer This Product'
      );
      setMessageType('error');
      setDisableSubmitButton(true);
      return;
    }
    if (data?.target.value) {
      const sellingPrice = parseFloat(props.Productdata?.SellingPrice || 0);
      const limit = parseFloat(props.Productdata?.DiscountLimit || 0);
      const limitType = props.Productdata?.DiscountLimitType;
      const enteredDiscount = parseFloat(data?.target.value);

      if (limit === null || limit === undefined || limit === 0) {
        if (
          parseFloat(enteredDiscount) < parseFloat(sellingPrice) ||
          parseFloat(enteredDiscount) === parseFloat(sellingPrice)
        ) {
          setEditedPrice(enteredDiscount);
          setDisableSubmitButton(true);
        } else {
          setMessageType('error');
          setMessageData('Please Give less than value for sell price');
          setDisableSubmitButton(false);
          setEditedPrice(0);
          formRef.current?.resetFields();
        }
        return;
      }

      let maxDiscount = 0;
      if (limitType === 'F') {
        maxDiscount = limit;
      } else if (limitType === 'P') {
        const afterdiscountfullamount = (sellingPrice * limit) / 100;
        maxDiscount = afterdiscountfullamount;
      }

      if (enteredDiscount === maxDiscount) {
        setEditedPrice(data?.target.value);
        setDisableSubmitButton(true);
        return;
      }

      if (enteredDiscount < maxDiscount) {
        setMessageType('error');
        setMessageData(`You cannot sell below ₹${maxDiscount.toFixed(2)}`);
        setEditedPrice(0);
        setDisableSubmitButton(false);
        return;
      }
      setDisableSubmitButton(true);
      setEditedPrice(data?.target.value);
    } else {
      setDisableSubmitButton(false);
      setEditedPrice(0);
    }
  };

  const onRadioBtnChange = (data) => {
    setRadioBtnSelection(data);
  };

  useEffect(() => {
    const handleOutsideClick = (e) => {
      if (
        quantityInputRef.current &&
        !quantityInputRef.current.contains(e.target) &&
        priceChangeInputRef.current &&
        !priceChangeInputRef.current.contains(e.target)
      ) {
        setIndex(null);
        setEditQtyCombo(false);
        setEditRateCombo(false);
      }
    };

    document.addEventListener('mousedown', handleOutsideClick);
    return () => {
      document.removeEventListener('mousedown', handleOutsideClick);
    };
  }, []);

  return (
    <div className="BSBilling-EditQuantity-Modal">
      <Messages
        messageType={messageType}
        messageData={messageData}
        onComplete={onComplete}
      />
      <Form
        onFinish={(values) => {
          if (RadioBtnSelection === 'Rate' && !disableSubmitButton) {
            return;
          }
          AddProductQuantity(values);
        }}
      >
        {RadioBtnSelection == 'Quantity' && (
          <>
            <input
              ref={quantityInputRef}
              type="number"
              value={Quantity}
              onChange={(e) => setQuantity(e.target.value)}
              onBlur={() => {
                if (Quantity && Quantity.trim() !== '') {
                  AddProductQuantity();
                }
              }}
              className="EditQTYcomboInput"
              placeholder="Enter Qty"
            />
          </>
        )}
        {RadioBtnSelection == 'Rate' && (
          <>
            <div className="EditQuantity-PriceChange">
              <input
                autoFocus
                ref={priceChangeInputRef}
                value={editedPrice}
                autoComplete="off"
                onChange={SellingPriceChange}
                onBlur={() => {
                  if (editedPrice && editedPrice !== '' && disableSubmitButton) {
                    AddProductQuantity();
                  }
                }}
                inputMode="decimal"
                className="EditQTYcomboInputRate"
                placeholder="Enter Rate"
                onInput={(e) => {
                  const cleanedValue = e.target.value.replace(/[^0-9.]/g, '');
                  const parts = cleanedValue.split('.');
                  e.target.value =
                    parts.length > 2
                      ? `${parts[0]}.${parts.slice(1).join('')}`
                      : cleanedValue;
                }}
              />
            </div>
          </>
        )}
      </Form>
    </div>
  );
};
export default ComboEditQtyAndRate;
