import React, { useEffect, useState } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { Popconfirm, Tooltip } from 'antd';
import WebFont from 'webfontloader';
import { isMobile } from 'react-device-detect';
import { AiOutlineClose, AiFillDelete } from 'react-icons/ai';
import TakeAwayIcon from '../../../../../Images/Take away.svg';
import dineInIcon from '../../../../../Images/Dine In.svg';
import {
  ChangeTotalAmount,
  globalExtraTotalAmount,
} from '../../../../../Features/ExteraCharges/ExtraCharges.js';
import BSBillingEditQuantity from '../BSBillingEditQuantity/BSBillingEditQuantity';
import {
  changeholddata,
  gettinghold,
  puttinghold,
} from '../../../../../Features/BookingScreen/HoldOption/HoldOption.js';
import { getCustomerDisplayWindow } from '../../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
import BSEditTotalAmt from '../BSEditTotalAmount/BSEditTotalAmt.jsx';
import { useApplyOfferto_CardDetail } from '../../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx';
import BSImeiDetails from '../BSImeiDetails/BSImeiDetails.jsx';
import {
  getTemplateData,
  SelectedGlobalBillingColorDetail,
  SelectedGlobalBillingFont,
  StoredSessionData,
} from '../../../../../Features/ThemeChange/ThemeChange';
import {
  GlobalOrderCardDetails,
  changeOrderCardDetails,
  GlobalBookingType,
  GlobalPreviousOrderLength,
  GlobalHoldOrderDtl,
  GlobalUnpaidData,
  ChangeSelectedCustDisable,
  changeSelectedOption,
  changeReorderHoldDetails,
  changeUnpaidData,
  changeBookingType,
  GlobalSelProdWiseEst,
  GlobalBookingTypeBoth,
  GlobalOrderType,
  changeReorderProductDetails,
  GlobalReorderHoldDetails,
  getSelectedFavItems,
  getLayoutproductCard,
  getCardDataWithoutSubmodule,
  getCardDataWithoutSub,
  changeOrderType,
  GlobalProductCategorie,
  GlobalProductSubCategorie,
  changeAllProductTokenAvailable,
  changeTokenOnly,
  PreferenceData,
  GlobalEstimateBooking,
  ChangeOverAllDiscSales,
  ChangeOverAllDiscEstimate,
  changeSelProdWiseEst,
  GlobalOtherSevices,
  GlobalDefaultBookingType,
  GlobalSelOption,
  GlobalCustId,
} from '../../../../../Features/BookingScreen/BookingData/BookingData';
import '../../../../../Styles/BookingScreen/Components/BSBillingTables/BSBillingTables3/BSBillingTable3.scss';
import {
  ChangeOfferAppliedProducts,
  ChangeFreeProductList,
  ChangeFullFreeProductList,
  GlobalFreeProdList,
  GlobalOfferAppliedProducts,
  changeFullOfferAppliedProducts,
  changeLoyaltyConsumedQuantities,
  ClearOfferAppliedProducts,
} from '../../../../../Features/Offer/Offernew/BookingOffernew.js';
import { useRemoveProducts } from './RemoveCartWithOffer.jsx';
import { useUtilsComponent } from '../../../../../Services/utils.js';
import CustomerPriceHistory from '../../UtillComponents/CustomerPriceHistory.jsx';

const BSBillingTable3 = () => {
  const { removeExtraCharge } = useUtilsComponent();
  const dispatch = useDispatch();
  const removeProducts = useRemoveProducts();
  const applyOffer = useApplyOfferto_CardDetail();
  const preferenceDatas = useSelector(PreferenceData);
  const preferenceDetails = preferenceDatas?.[0]?.SettingDtlDetails;
  const preferenceOffer =
    preferenceDetails?.find((item) => item.SettingIdName === 'Offer')
      ?.SettingValue === 'Y';
  const BillOrderPre = preferenceDatas?.[0]?.SettingDtlDetails?.find(
    (item) => item.SettingIdName === 'BillItemsOrder'
  )?.SettingValue;
  const allowDecimal = preferenceDatas?.[0]?.SettingDtlDetails?.find(
    (setting) =>
      setting?.SettingIdName?.toLowerCase() === 'decimal' &&
      setting?.SettingValue === 'Y'
  );
  const SessionData = useSelector(StoredSessionData);
  const BranchId = SessionData?.BranchId;
  const AppId = SessionData?.AppId;
  const CompId = SessionData?.CompId;
  const templateData = useSelector(getTemplateData);
  const tableOptions = templateData?.BookingBilling?.[1];
  const OfferCheckedInSetup = templateData?.BookingNavbar?.[1].some(
    (item) => item?.OptionName == 'Offer'
  );
  const SelectedBillColor = useSelector(SelectedGlobalBillingColorDetail);
  const SelectedFont = useSelector(SelectedGlobalBillingFont);
  const GlobalOfferAppliedProductsData = useSelector(
    GlobalOfferAppliedProducts
  );
  const [Index, setIndex] = useState(null);

  const BookingType = useSelector(GlobalBookingType);
  const defaultBookingType = useSelector(GlobalDefaultBookingType);
  const tableData = useSelector(GlobalOrderCardDetails, shallowEqual);
  const PreviousOrderLength = useSelector(GlobalPreviousOrderLength);
  const HoldOrderDtl = useSelector(GlobalHoldOrderDtl);
  const UnpaidData = useSelector(GlobalUnpaidData);
  const GlobProdwisedata = useSelector(GlobalSelProdWiseEst);
  const ReportholdData = useSelector(GlobalReorderHoldDetails);
  const prodCat = useSelector(GlobalProductCategorie);
  const ProdSubCat = useSelector(GlobalProductSubCategorie);
  const [PreviousdataLength, setPreviousdataLength] =
    useState(PreviousOrderLength);
  const BookingTypeBoth = useSelector(GlobalBookingTypeBoth);
  const OrderType = useSelector(GlobalOrderType);
  const GlobEstBooking = useSelector(GlobalEstimateBooking);
  const GlobalExtraCharge = useSelector(globalExtraTotalAmount);
  const OfferFreeProduct = useSelector(GlobalFreeProdList, shallowEqual);
  const OtherServicesglobal = useSelector(GlobalOtherSevices);
  const GetCustId = useSelector(GlobalCustId);
  const selectedCustomer = useSelector(GlobalSelOption);

  const [customerPriceHistoryOpen, setCustomerPriceHistoryOpen] = useState(false);
  const [customerProduct, setCustomerProduct] = useState(null);
  const preferenceshortcutkey = preferenceDatas?.[0]?.[
    'SettingDtlDetails'
  ]?.some(
    (item) =>
      item.SettingIdName.toLowerCase() === 'shortcutkeys' &&
      item.SettingValue === 'Y'
  );
  console.log(preferenceshortcutkey, 'preferenceshortcutkey');
  const tableDataDinein = tableData?.filter(
    (a, b) => a.BookingTypeName === 'Dine In' && !a?.SalesId
  );
  const tableDataTakeAway =
    OrderType === 'Hold'
      ? tableData?.filter((a, b) => a.BookingTypeName === 'TakeAway')
      : tableData?.filter(
        (a, b) => a.BookingTypeName === 'TakeAway' && !a?.SalesId
      );
  const OldtableDataDinein = tableData?.filter(
    (a, b) => a.BookingTypeName === 'Dine In' && a?.SalesId
  );
  const OldtableDataTakeAway =
    OrderType != 'Hold'
      ? tableData?.filter(
        (a, b) => a.BookingTypeName === 'TakeAway' && a?.SalesId
      )
      : [];
  const [EditQuantity, setEditQuantity] = useState(false);
  const [Modaldata, setModaldata] = useState([]);
  const [triggerAnimation, setTriggerAnimation] = useState(true);
  const editField =
    tableOptions?.some((item) => item.OptionName === 'Edit') ?? false;

  const [OpenEditTotalAmt, setOpenEditTotalAmt] = useState(false);
  const [OpenImeiDetail, setOpenImeiDetail] = useState(false);
  const [shortKeyMethod, setshortKeyMethod] = useState(null);
  const productBasedExtraCharges = GlobalExtraCharge.filter(
    (obj) => 'ProdName' in obj
  );
  useEffect(() => {
    if (SelectedFont) {
      WebFont.load({
        google: {
          families: [SelectedFont], // Load the selected font
        },
      });
    }
  }, [SelectedFont]);

  useEffect(() => {
    const handleKeyDown = (e) => {
      if (e.ctrlKey && e.key.toLowerCase() === 'i') {
        e.preventDefault();

        const prodId = tableData?.[0]?.ProdId;

        if (GetCustId && prodId) {
          setCustomerPriceHistoryOpen(true);
          setCustomerProduct(prodId);
        }
      }
    };

    window.addEventListener('keydown', handleKeyDown);

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [GetCustId, tableData]);

  useEffect(() => {
    if (!preferenceshortcutkey) return;

    const getItem = (data = []) => {
      if (!data.length) return null;
      return BillOrderPre === 'Y' ? data[0] : data[data.length - 1];
    };

    const getSelectedItem = () => {
      if (tableDataTakeAway && tableDataTakeAway.length) {
        return getItem(tableDataTakeAway);
      }
      if (tableDataDinein && tableDataDinein.length) {
        return getItem(tableDataDinein);
      }
      return null;
    };

    const handleShortcut = (method) => {
      const item = getSelectedItem();
      if (!item) return;

      handleEditQuantity(item);
      setshortKeyMethod(method);
    };

    const handleKeyDown = (event) => {
      if (!event.ctrlKey) return;

      const key = event.key.toLowerCase();

      if (key === 'q') {
        event.preventDefault();
        handleShortcut('qty');
      }

      if (key === 'e') {
        event.preventDefault();
        handleShortcut('price');
      }
    };
    window.addEventListener('keydown', handleKeyDown);

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [preferenceshortcutkey, tableDataTakeAway, tableDataDinein, BillOrderPre]);

  const getstockbadge = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
    };
    await dispatch(getSelectedFavItems(data)).unwrap();

    let data1 = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      ProdSubCat: ProdSubCat,
    };

    let data2 = {
      compId: CompId,
      branchId: BranchId,
      appId: AppId,
      prodCat: prodCat,
    };

    if (
      templateData?.BookingLayout?.[1]?.some(
        (item) => item?.OptionName === 'SubCategory'
      ) &&
      ProdSubCat
    ) {
      await dispatch(getLayoutproductCard(data1)).unwrap();
    } else if (
      !templateData?.BookingLayout?.[1]?.some(
        (item) => item?.OptionName === 'SubCategory'
      )
    ) {
      await dispatch(getCardDataWithoutSubmodule(data2)).unwrap();
    } else {
      await dispatch(getCardDataWithoutSub(data2)).unwrap();
    }
  };

  const ClearOfferDetails = () => {
    dispatch(changeFullOfferAppliedProducts([]));
    dispatch(ChangeFullFreeProductList([]));
    dispatch(changeLoyaltyConsumedQuantities({}));
  };

  const Clearall = async () => {
    if (OrderType === 'Hold') {
      if (OfferCheckedInSetup && preferenceOffer) {
        await ClearOfferDetails();
      }
      dispatch(changeOrderCardDetails([]));

      let putData = { OrderId: [ReportholdData?.OrderId] };
      let response = await dispatch(puttinghold(putData)).unwrap();
      if (response?.data?.statusCode == 1) {
        getstockbadge();
        let holdingData = await dispatch(
          gettinghold({ CompId: CompId, BranchId: BranchId, AppId: AppId })
        ).unwrap();
        if (holdingData?.data?.statusCode === 1) {
          dispatch(changeholddata(holdingData?.data?.data));
        } else {
          dispatch(changeholddata([]));
        }
      }
      await dispatch(ChangeTotalAmount([]));
      await dispatch(changeOrderType(null));
      await dispatch(changeReorderHoldDetails({}));
    } else if (OrderType === 'Reorder') {
      const UpdatedData = tableData?.filter((cartItem) => cartItem?.SalesId);

      if (OfferCheckedInSetup && preferenceOffer) {
        await ClearOfferDetails();
      }
      dispatch(changeOrderCardDetails(UpdatedData));

      await dispatch(changeBookingType('Dine In'));
    } else {
      if (OfferCheckedInSetup && preferenceOffer) {
        await ClearOfferDetails();
      }
      dispatch(changeOrderCardDetails([]));
      await dispatch(ChangeTotalAmount([]));
      await dispatch(changeUnpaidData(false));
      await dispatch(changeReorderHoldDetails({}));
      await dispatch(changeReorderProductDetails([]));
      await dispatch(ChangeSelectedCustDisable(false));
      await dispatch(changeSelectedOption(false));
      await dispatch(changeBookingType(defaultBookingType || 'TakeAway'));
      // await dispatch(changeholddata([]))
      await dispatch(changeOrderType());
    }
    await dispatch(ChangeOverAllDiscSales(null));
    await dispatch(ChangeOverAllDiscEstimate(null));
    await dispatch(changeTokenOnly(false));
    await dispatch(changeAllProductTokenAvailable(false));
    await dispatch(changeSelProdWiseEst([]));
    const customerDisplayWindow = getCustomerDisplayWindow();
    if (customerDisplayWindow && !customerDisplayWindow.closed) {
      const updatedData = {
        type: 'remove',
        keyValue: 'customer',
      };
      customerDisplayWindow.postMessage(updatedData, '*');
    } else {
      console.error(
        'Customer display window is not available or has been closed.'
      );
    }
  };

  const handleCustomerProductPriceHistory = (item) => {
    setCustomerPriceHistoryOpen(true);
    setCustomerProduct(item?.ProdId);
  }

  function safeRound(amountStr) {
    if (amountStr == null) return allowDecimal ? '0.00' : '0';

    const cleaned = String(amountStr).replace(/[^0-9.-]+/g, '');
    const num = Number(cleaned);

    if (isNaN(num)) return allowDecimal ? '0.00' : '0';

    return allowDecimal ? num.toFixed(2) : Math.round(num).toString();
  }

  const calculateAmounts = (
    OrderQty,
    OrderRate,
    TaxPercentage,
    IsPaid = true
  ) => {
    const total = OrderQty * OrderRate;

    const withoutTax = total - (total * TaxPercentage) / (100 + TaxPercentage);

    return {
      TotalAmt: total,
      ...(IsPaid && { Offer: total }),
      WithoutTaxRate: +withoutTax.toFixed(2),
    };
  };

  const ChangeOrderCardDetailsFn = async ({
    OrderQty,
    InwardDtlId,
    Offer,
    CompleteRemove = false,
    RemoveAndUpdate = false,
    BuyInwardDtlId,
    BuyProdQty,
    UpdateBuyAndFree = false,
    CompleteRemoveBuyAndAddWithPaid = false,
    CompleteRemoveconvertFreetoPaid = false,
    CompleteRemoveconvertFreetoPaidTwoTypes = false,
    CompleteRemoveconvertFreetoPaidNotCompletely = false,
    CompleteRemoveAndPaidToFreeOtherType = false,
    CompleteRemoveAndPaidToFreeOtherTypeWithoutMerge = false,
    RemoveAndUpdateOtherBookingType = false,
    BookingTypeName,
    OrderRate,
  }) => {
    let ModifiedOrderCardDetail = JSON.parse(JSON.stringify(tableData));

    if (RemoveAndUpdate) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === InwardDtlId &&
            e?.Offer === Offer &&
            e?.BookingTypeName === BookingTypeName &&
            (!e?.SalesId || OrderType == 'Hold')
          )
      )?.map((e) => {
        if (
          e?.InwardDtlId == InwardDtlId &&
          e?.Offer > 0 &&
          e?.BookingTypeName === BookingTypeName
        ) {
          const newQty = OrderQty;
          return {
            ...e,
            OrderQty: newQty,
            ...calculateAmounts(newQty, e.OrderRate, e.TaxPercentage),
          };
        }

        if (e?.InwardDtlId == BuyInwardDtlId) {
          return {
            ...e,
            OrderQty: BuyProdQty,
            ...calculateAmounts(
              BuyProdQty,
              e.OrderRate,
              e.TaxPercentage,
              false
            ),
          };
        }

        return e;
      });

      return dispatch(changeOrderCardDetails(data));
    }
    if (RemoveAndUpdateOtherBookingType) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === InwardDtlId &&
            e?.Offer === Offer &&
            e?.BookingTypeName === BookingTypeName &&
            (!e?.SalesId || OrderType == 'Hold')
          )
      )?.flatMap((e) => {
        if (
          e?.InwardDtlId == InwardDtlId &&
          e?.Offer > 0 &&
          e?.BookingTypeName === BookingTypeName
        ) {
          const newQty = e?.OrderQty - BuyProdQty;

          return {
            ...e,
            OrderQty: newQty,
            ...calculateAmounts(newQty, e.OrderRate, e.TaxPercentage),
          };
        }
        if (
          e?.InwardDtlId == InwardDtlId &&
          e?.Offer == 0 &&
          e?.BookingTypeName !== BookingTypeName
        ) {
          const newQty = e?.OrderQty - BuyProdQty;

          let first = {
            ...e,
            OrderQty: BuyProdQty,
            ...calculateAmounts(BuyProdQty, e.OrderRate, e.TaxPercentage),
          };
          if (newQty > 0) {
            let second = {
              ...e,
              Offer: 0,
              OrderQty: newQty,
              ...calculateAmounts(newQty, e.OrderRate, e.TaxPercentage, false),
            };
            return [first, second];
          }
          return [first];
        }

        if (e?.InwardDtlId == BuyInwardDtlId) {
          return {
            ...e,
            OrderQty: BuyProdQty,
            ...calculateAmounts(
              BuyProdQty,
              e.OrderRate,
              e.TaxPercentage,
              false
            ),
          };
        }

        return e;
      });

      return dispatch(changeOrderCardDetails(data));
    }
    if (CompleteRemove) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === InwardDtlId &&
            e?.Offer === Offer &&
            e?.BookingTypeName === BookingTypeName &&
            (!e?.SalesId || OrderType == 'Hold') &&
            e?.SinglePc == 'N' &&
            e?.OrderRate == OrderRate
          )
      );
      return dispatch(changeOrderCardDetails(data));
    }
    if (CompleteRemoveAndPaidToFreeOtherType) {
      let data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === InwardDtlId &&
            e?.Offer === Offer &&
            e?.BookingTypeName === BookingTypeName &&
            (!e?.SalesId || OrderType == 'Hold')
          )
      )?.flatMap((exp) => {
        // Same product but different booking type and not an offer
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer == 0 &&
          exp?.BookingTypeName !== BookingTypeName
        ) {
          const remainingQty = exp.OrderQty - OrderQty;

          if (remainingQty === 0) {
            return {
              ...exp,
              OfferMode: 'B',
              ...calculateAmounts(
                exp.OrderQty,
                exp.OrderRate,
                exp.TaxPercentage,
                true
              ),
            };
          }

          if (remainingQty > 0) {
            return [
              {
                ...exp,
                OrderQty: remainingQty,
                ...calculateAmounts(
                  remainingQty,
                  exp.OrderRate,
                  exp.TaxPercentage,
                  false
                ),
              },
              {
                ...exp,
                OrderQty: OrderQty,
                Offer: 0,
                OfferMode: 'B',
                ...calculateAmounts(
                  OrderQty,
                  exp.OrderRate,
                  exp.TaxPercentage,
                  true
                ),
              },
            ];
          }
        }

        return exp;
      });

      // ===== Merge duplicates for free offers =====
      const mergedData = [];
      data?.forEach((item) => {
        if (item?.OfferMode === 'B') {
          // Check if a free item already exists for this product + booking type
          const existingIndex = mergedData.findIndex(
            (e) =>
              e.InwardDtlId === item.InwardDtlId &&
              e.BookingTypeName === item.BookingTypeName &&
              e.OfferMode === 'B'
          );

          if (existingIndex > -1) {
            // Merge quantities
            const existing = mergedData[existingIndex];
            const newQty = existing.OrderQty + item.OrderQty;
            mergedData[existingIndex] = {
              ...existing,
              OrderQty: newQty,
              ...calculateAmounts(
                newQty,
                item.OrderRate,
                item.TaxPercentage,
                true
              ),
            };
          } else {
            mergedData.push(item);
          }
        } else {
          mergedData.push(item);
        }
      });

      return dispatch(changeOrderCardDetails(mergedData));
    }
    if (CompleteRemoveAndPaidToFreeOtherTypeWithoutMerge) {
      let data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === InwardDtlId &&
            e?.Offer === Offer &&
            e?.BookingTypeName === BookingTypeName &&
            (!e?.SalesId || OrderType == 'Hold')
          )
      )?.flatMap((exp) => {
        // Same product but different booking type and not an offer
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer == 0 &&
          exp?.BookingTypeName !== BookingTypeName
        ) {
          const remainingQty = exp.OrderQty - OrderQty;

          if (remainingQty === 0) {
            return {
              ...exp,
              OfferMode: 'B',
              ...calculateAmounts(
                exp.OrderQty,
                exp.OrderRate,
                exp.TaxPercentage,
                true
              ),
            };
          }

          if (remainingQty < 0) {
            return [
              {
                ...exp,
                OrderQty: exp.OrderQty,
                OfferMode: 'B',
                ...calculateAmounts(
                  exp.OrderQty,
                  exp.OrderRate,
                  exp.TaxPercentage,
                  true
                ),
              },
            ];
          }
        }

        return exp;
      });

      return dispatch(changeOrderCardDetails(data));
    }

    if (CompleteRemoveconvertFreetoPaid) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === BuyInwardDtlId &&
            e?.BookingTypeName === BookingTypeName &&
            (!e?.SalesId || OrderType == 'Hold')
          )
      )?.map((exp) => {
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer > 0 &&
          exp?.BookingTypeName === BookingTypeName
        ) {
          const { OfferType, OfferMessage, ...exp1 } = exp;
          return {
            ...exp1,
            Offer: 0,
            OrderQty: OrderQty,
            ...calculateAmounts(
              OrderQty,
              exp.OrderRate,
              exp.TaxPercentage,
              false
            ),
          };
        }
        return exp; // keep unchanged item
      });

      return dispatch(changeOrderCardDetails(data));
    }
    if (CompleteRemoveconvertFreetoPaidNotCompletely) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === BuyInwardDtlId &&
            e?.BookingTypeName === BookingTypeName &&
            (!e?.SalesId || OrderType == 'Hold')
          )
      )?.flatMap((exp) => {
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer > 0 &&
          exp?.BookingTypeName === BookingTypeName
        ) {
          const { OfferType, OfferMessage, ...exp1 } = exp;
          let first = {
            ...exp1,
            Offer: 0,
            OrderQty: BuyProdQty,
            ...calculateAmounts(
              OrderQty,
              exp.OrderRate,
              exp.TaxPercentage,
              false
            ),
          };
          if (BuyProdQty < OrderQty) {
            let second = {
              ...exp1,
              Offer: 0,
              OrderQty: exp1?.OrderQty - BuyProdQty,
              ...calculateAmounts(
                exp1?.OrderQty - BuyProdQty,
                exp.OrderRate,
                exp.TaxPercentage,
                true
              ),
            };
            return [first, second];
          }
          return [first];
        }
        return exp; // keep unchanged item
      });

      return dispatch(changeOrderCardDetails(data));
    }
    if (CompleteRemoveBuyAndAddWithPaid) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            (e?.InwardDtlId === BuyInwardDtlId &&
              e?.BookingTypeName === BookingTypeName &&
              (!e?.SalesId || OrderType == 'Hold')) ||
            (e?.InwardDtlId == InwardDtlId &&
              e?.Offer > 0 &&
              e?.BookingTypeName === BookingTypeName &&
              (!e?.SalesId || OrderType == 'Hold'))
          )
      )?.map((exp) => {
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer == 0 &&
          exp?.BookingTypeName === BookingTypeName
        ) {
          return {
            ...exp, // keep existing fields
            OrderQty: OrderQty,
            ...calculateAmounts(
              OrderQty,
              exp.OrderRate,
              exp.TaxPercentage,
              false
            ),
          };
        }
        return exp; // keep unchanged item
      });

      return dispatch(changeOrderCardDetails(data));
    }

    if (UpdateBuyAndFree) {
      const data = ModifiedOrderCardDetail?.map((e) => {
        if (
          e?.InwardDtlId == InwardDtlId &&
          e?.Offer > 0 &&
          e?.BookingTypeName === BookingTypeName
        ) {
          const newQty = e?.OrderQty + OrderQty;
          return {
            ...e,
            OrderQty: newQty,
            ...calculateAmounts(newQty, e.OrderRate, e.TaxPercentage),
          };
        }
        if (e?.InwardDtlId == InwardDtlId && e?.Offer == Offer) {
          const newQty = e?.OrderQty - OrderQty;
          return {
            ...e,
            OrderQty: newQty,

            ...calculateAmounts(newQty, e.OrderRate, e.TaxPercentage, false),
          };
        }

        if (
          e?.InwardDtlId == BuyInwardDtlId &&
          e?.BookingTypeName === BookingTypeName
        ) {
          return {
            ...e,
            OrderQty: BuyProdQty,
            ...calculateAmounts(
              BuyProdQty,
              e.OrderRate,
              e.TaxPercentage,
              false
            ),
          };
        }

        return e;
      });

      return dispatch(changeOrderCardDetails(data));
    }

    if (CompleteRemoveconvertFreetoPaidTwoTypes) {
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === BuyInwardDtlId &&
            e?.BookingTypeName === BookingTypeName &&
            (!e?.SalesId || OrderType == 'Hold')
          )
      )?.flatMap((exp) => {
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer > 0 &&
          exp?.BookingTypeName === BookingTypeName
        ) {
          const { OfferType, OfferMessage, ...exp1 } = exp;
          return {
            ...exp1,
            Offer: 0,
            OrderQty: OrderQty,
            ...calculateAmounts(
              OrderQty,
              exp.OrderRate,
              exp.TaxPercentage,
              false
            ),
          };
        }
        if (
          exp?.InwardDtlId == InwardDtlId &&
          exp?.Offer > 0 &&
          exp?.BookingTypeName !== BookingTypeName
        ) {
          const { ...exp1 } = exp;
          let first = {
            ...exp1,
            // Offer: 0,
            OrderQty: exp1?.OrderQty - BuyProdQty,
            ...calculateAmounts(
              exp1?.OrderQty - BuyProdQty,
              exp.OrderRate,
              exp.TaxPercentage,
              true
            ),
          };

          let second = {
            ...exp1,
            Offer: 0,
            OrderQty: BuyProdQty,
            ...calculateAmounts(
              BuyProdQty,
              exp.OrderRate,
              exp.TaxPercentage,
              false
            ),
          };
          delete second?.OfferMessage;
          delete second?.OfferType;
          return [first, second];
        }
        return exp; // keep unchanged item
      });

      return dispatch(changeOrderCardDetails(data));
    }
    // Update qty for normal case

    const data = ModifiedOrderCardDetail?.map((e) => {
      if (
        e?.InwardDtlId == InwardDtlId &&
        e?.Offer == Offer &&
        e?.BookingTypeName === BookingTypeName
      ) {
        return {
          ...e,
          OrderQty,
          ...calculateAmounts(OrderQty, e.OrderRate, e.TaxPercentage, false),
        };
      }
      return e;
    });

    dispatch(changeOrderCardDetails(data));
  };

  const ChangeFreeprodlistFn = async ({
    FreeProdId,
    OfferId,
    OverAllFreeQty,
    RemainingQty,
    FreeQty,
    CompleteRemove = false,
  }) => {
    const deepCopy = JSON.parse(JSON.stringify(OfferFreeProduct));

    let ModifyedData;

    if (CompleteRemove) {
      // 🔹 Remove the matching FreeProd completely
      ModifyedData = deepCopy?.filter(
        (exp) => !(exp?.OfferId == OfferId && exp?.FreeProdId == FreeProdId)
      );
    } else {
      // 🔹 Update the matching FreeProd
      ModifyedData = deepCopy?.map((exp) => {
        if (exp?.OfferId == OfferId && FreeProdId == exp?.FreeProdId) {
          return {
            ...exp,
            OverAllFreeQty,
            RemainingQty,
            FreeQty,
          };
        }
        return { ...exp };
      });
    }

    dispatch(ChangeFullFreeProductList(ModifyedData));
  };

  const ChangeOfferAppliedProdsFn = async ({
    inwardDtlId,
    OfferAmount,
    FreeQty,
    CompleteRemove = false,
    insideinwardDtlId = false,
  }) => {
    const deepCopy = JSON.parse(JSON.stringify(GlobalOfferAppliedProductsData));

    let ModifyedData;

    if (CompleteRemove) {
      // 🔹 Remove case
      if (!insideinwardDtlId) {
        ModifyedData = deepCopy?.filter(
          (exp) => exp?.InwardDtlId !== inwardDtlId
        );
      } else {
        ModifyedData = deepCopy?.filter(
          (exp) =>
            !(
              Array?.isArray(exp?.FreeProductsList)
                ? exp?.FreeProductsList
                : [exp?.FreeProductsList]
            )?.some((freeProd) =>
              freeProd?.ProdVariantDetails?.some((variant) =>
                variant?.StockDetails?.some(
                  (stock) => stock?.FreeInwardDtlId === inwardDtlId
                )
              )
            )
        );
      }
    } else {
      // 🔹 Update case
      ModifyedData = deepCopy?.map((exp) => {
        let shouldUpdate = false;

        if (!insideinwardDtlId) {
          shouldUpdate = exp?.InwardDtlId == inwardDtlId;
        } else {
          shouldUpdate = (
            Array?.isArray(exp?.FreeProductsList)
              ? exp?.FreeProductsList
              : [exp?.FreeProductsList]
          )?.some((freeProd) =>
            freeProd?.ProdVariantDetails?.some((variant) =>
              variant?.StockDetails?.some(
                (stock) => stock?.FreeInwardDtlId === inwardDtlId
              )
            )
          );
        }

        if (shouldUpdate) {
          return {
            ...exp,
            OfferAmount,
            ActualFreeQty: FreeQty,
            FreeProductsList: (Array?.isArray(exp?.FreeProductsList)
              ? exp?.FreeProductsList
              : [exp?.FreeProductsList]
            )?.map((item, idx) =>
              idx === 0
                ? {
                  ...item,
                  FreeQty,
                }
                : item
            ),
          };
        }

        return { ...exp };
      });
    }

    dispatch(changeFullOfferAppliedProducts(ModifyedData));
  };

  const removeFromCart = async (item) => {
    removeExtraCharge(item);

    setPreviousdataLength(tableData?.length);

    if (item?.SinglePc == 'Y') {
      let ModifiedOrderCardDetail = JSON.parse(JSON.stringify(tableData));
      const data = ModifiedOrderCardDetail?.filter(
        (e) =>
          !(
            e?.InwardDtlId === item?.InwardDtlId &&
            e?.Offer === item?.Offer &&
            e?.BookingTypeName === item?.BookingTypeName &&
            (!e?.SalesId || OrderType == 'Hold') &&
            e?.SinglePc == 'Y'
          )
      );
      return dispatch(changeOrderCardDetails(data));
    }
    let ischeckBothBookingType = tableData?.find(
      (e) =>
        e?.InwardDtlId == item?.InwardDtlId &&
        e?.Offer > 0 &&
        e?.BookingTypeName != item?.BookingTypeName
    );

    if (item?.Offer > 0) {
      //check is Buyxgetx Or something
      // let ischeck=  GlobalOfferAppliedProductsData?.some((e)=>e?.FreeProductsList?.[0]??.
      const isBuyAndGetX =
        GlobalOfferAppliedProductsData?.find((data) =>
          (Array?.isArray(data?.FreeProductsList)
            ? data?.FreeProductsList
            : [data?.FreeProductsList]
          )?.some((freeProd) =>
            freeProd?.ProdVariantDetails?.some((variant) =>
              variant?.StockDetails?.some(
                (stock) => stock?.FreeInwardDtlId === item?.InwardDtlId
              )
            )
          )
        )?.OfferMode == 'B';

      const isItemWiseOrQuantityProduct = GlobalOfferAppliedProductsData?.find(
        (data) =>
          data?.ProdId === item?.ProdId &&
          data?.InwardDtlId === item?.InwardDtlId &&
          (data?.OfferMode === 'I' || data?.OfferMode === 'Q') &&
          data?.OfferAmount === item?.Offer
      );

      const isCheckFreeProduct = GlobalOfferAppliedProductsData?.find((off) =>
        (Array.isArray(off?.FreeProductsList)
          ? off?.FreeProductsList
          : [off?.FreeProductsList]
        )?.some((prod) =>
          prod?.ProdVariantDetails?.some((variant) =>
            variant?.StockDetails?.some(
              (stock) => stock.FreeInwardDtlId === item?.InwardDtlId
            )
          )
        )
      );

      if (isBuyAndGetX) {
        let isPaidproduct = tableData?.find(
          (e) =>
            e?.InwardDtlId == item?.InwardDtlId &&
            e?.Offer == 0 &&
            item?.BookingTypeName == e?.BookingTypeName
        );
        const isCheckFreeProduct = OfferFreeProduct?.find((exp) =>
          exp?.ProdVariantDetails?.some((variant) =>
            variant?.StockDetails?.some(
              (stock) => stock?.FreeInwardDtlId === item?.InwardDtlId
            )
          )
        );
        if (isPaidproduct) {
          if (isPaidproduct?.OrderQty == item?.OrderQty) {
            //just remove Paid Qty
            await ChangeOrderCardDetailsFn({
              BookingTypeName: item?.BookingTypeName,
              BuyProdQty: null,
              OrderQty: isPaidproduct?.OrderQty,
              CompleteRemove: true,
              InwardDtlId: isPaidproduct?.InwardDtlId,
              BuyInwardDtlId: null,
              Offer: 0,
            });
          } else if (isPaidproduct?.OrderQty > item?.OrderQty) {
            // Just Decrease Paid Qty
            await ChangeOrderCardDetailsFn({
              BookingTypeName: item?.BookingTypeName,
              BuyProdQty: null,
              OrderQty: isPaidproduct?.OrderQty - item?.OrderQty,
              CompleteRemove: false,
              InwardDtlId: isPaidproduct?.InwardDtlId,
              BuyInwardDtlId: null,
              Offer: 0,
            });
          } else if (isPaidproduct?.OrderQty < item?.OrderQty) {
            //just remove Paid Qty
            //decrease FreeQty

            if (ischeckBothBookingType) {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: -isPaidproduct?.OrderQty,
                RemoveAndUpdate: true,
                InwardDtlId: isPaidproduct?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: 0,
              });

              await ChangeFreeprodlistFn({
                OverAllFreeQty: isCheckFreeProduct?.OverAllFreeQty,
                RemainingQty:
                  isCheckFreeProduct?.OverAllFreeQty -
                  (ischeckBothBookingType?.OrderQty + isPaidproduct?.OrderQty),
                FreeQty:
                  ischeckBothBookingType?.OrderQty + isPaidproduct?.OrderQty,
                FreeProdId: isPaidproduct?.ProdId,
                OfferId: isCheckFreeProduct?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: isPaidproduct?.InwardDtlId,
                OfferAmount: isPaidproduct?.OrderRate * isPaidproduct?.OrderQty,
                FreeQty: isPaidproduct?.OrderQty,
                CompleteRemove: false,
                insideinwardDtlId: true,
              });
            } else {
              let FreeProdcutinPaidModeOtherBookingType = tableData?.find(
                (e) =>
                  e?.InwardDtlId == item?.InwardDtlId &&
                  e?.Offer == 0 &&
                  item?.BookingTypeName != e?.BookingTypeName
              );

              if (FreeProdcutinPaidModeOtherBookingType) {
                await ChangeOrderCardDetailsFn({
                  BookingTypeName: item?.BookingTypeName,
                  BuyProdQty: item?.OrderQty - isPaidproduct?.OrderQty,
                  OrderQty: item.OrderQty,
                  RemoveAndUpdateOtherBookingType: true,
                  InwardDtlId: isPaidproduct?.InwardDtlId,
                  BuyInwardDtlId: null,
                  Offer: 0,
                });

                await ChangeFreeprodlistFn({
                  OverAllFreeQty: item?.OrderQty,
                  RemainingQty:
                    item?.OrderQty -
                    (isPaidproduct?.OrderQty +
                      (FreeProdcutinPaidModeOtherBookingType?.OrderQty -
                        (item?.OrderQty - isPaidproduct?.OrderQty) ||
                        FreeProdcutinPaidModeOtherBookingType?.OrderQty)),
                  FreeQty:
                    isPaidproduct?.OrderQty +
                    (FreeProdcutinPaidModeOtherBookingType?.OrderQty -
                      (item?.OrderQty - isPaidproduct?.OrderQty) ||
                      FreeProdcutinPaidModeOtherBookingType?.OrderQty),
                  FreeProdId: isPaidproduct?.ProdId,
                  OfferId: isCheckFreeProduct?.OfferId,
                });
                // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)

                await ChangeOfferAppliedProdsFn({
                  inwardDtlId: isPaidproduct?.InwardDtlId,
                  OfferAmount:
                    isPaidproduct?.OrderRate *
                    (isPaidproduct?.OrderQty +
                      (FreeProdcutinPaidModeOtherBookingType?.OrderQty -
                        (item?.OrderQty - isPaidproduct?.OrderQty) ||
                        FreeProdcutinPaidModeOtherBookingType?.OrderQty)),
                  FreeQty:
                    isPaidproduct?.OrderQty +
                    (FreeProdcutinPaidModeOtherBookingType?.OrderQty -
                      (item?.OrderQty - isPaidproduct?.OrderQty) ||
                      FreeProdcutinPaidModeOtherBookingType?.OrderQty),
                  insideinwardDtlId: true,
                });
              } else {
                await ChangeOrderCardDetailsFn({
                  BookingTypeName: item?.BookingTypeName,
                  BuyProdQty: null,
                  OrderQty: isPaidproduct?.OrderQty,
                  RemoveAndUpdate: true,
                  InwardDtlId: isPaidproduct?.InwardDtlId,
                  BuyInwardDtlId: null,
                  Offer: 0,
                });

                await ChangeFreeprodlistFn({
                  OverAllFreeQty: item?.OrderQty,
                  RemainingQty: item?.OrderQty - isPaidproduct?.OrderQty,
                  FreeQty: isPaidproduct?.OrderQty,
                  FreeProdId: isPaidproduct?.ProdId,
                  OfferId: isCheckFreeProduct?.OfferId,
                });
                // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)

                await ChangeOfferAppliedProdsFn({
                  inwardDtlId: isPaidproduct?.InwardDtlId,
                  OfferAmount:
                    isPaidproduct?.OrderRate * isPaidproduct?.OrderQty,
                  FreeQty: isPaidproduct?.OrderQty,
                  CompleteRemove: false,
                  insideinwardDtlId: true,
                });
              }
            }
          }
        } else {
          if (ischeckBothBookingType) {
            // //Free Product in Paid Mode
            let FreeProdcutinPaidModeOtherBookingType = tableData?.find(
              (e) =>
                e?.InwardDtlId == item?.InwardDtlId &&
                e?.Offer == 0 &&
                item?.BookingTypeName != e?.BookingTypeName
            );

            //if free product is available in paid mode in other booking type then just decrease the free qty from that product
            if (FreeProdcutinPaidModeOtherBookingType) {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: item?.OrderQty,
                CompleteRemoveAndPaidToFreeOtherType: true,
                InwardDtlId: item?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: item?.Offer,
              });
              await ChangeFreeprodlistFn({
                OverAllFreeQty: isCheckFreeProduct?.OverAllFreeQty,
                RemainingQty: isCheckFreeProduct?.OverAllFreeQty,
                FreeQty: isCheckFreeProduct?.FreeQty,
                FreeProdId: isCheckFreeProduct?.FreeProdId,
                OfferId: isCheckFreeProduct?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * Quantity), Quantity, true,)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount: isCheckFreeProduct?.FreeQty * item?.OrderRate,
                FreeQty: item?.OrderQty,
                CompleteRemove: false,
                insideinwardDtlId: true,
              });
            } else {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: isPaidproduct?.OrderQty,
                CompleteRemove: true,
                InwardDtlId: item?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: item?.Offer,
              });
              await ChangeFreeprodlistFn({
                OverAllFreeQty: isCheckFreeProduct?.OverAllFreeQty,
                RemainingQty:
                  isCheckFreeProduct?.OverAllFreeQty - item?.OrderQty,
                FreeQty: isCheckFreeProduct?.FreeQty - item?.OrderQty,
                FreeProdId: isCheckFreeProduct?.FreeProdId,
                OfferId: isCheckFreeProduct?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * Quantity), Quantity, true,)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount:
                  (isCheckFreeProduct?.FreeQty - item?.OrderQty) *
                  item?.OrderRate,
                FreeQty: item?.OrderQty,
                CompleteRemove: false,
                insideinwardDtlId: true,
              });
            }
          }

          // }
          else {
            let isPaidProductAvailableInCartOtherType = tableData?.find(
              (e) =>
                e?.InwardDtlId == item?.InwardDtlId &&
                e?.Offer == 0 &&
                item?.BookingTypeName != e?.BookingTypeName
            );

            if (isPaidProductAvailableInCartOtherType) {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: item?.OrderQty,
                CompleteRemoveAndPaidToFreeOtherTypeWithoutMerge: true,
                InwardDtlId: item?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: item?.Offer,
              });
              await ChangeFreeprodlistFn({
                OverAllFreeQty: isCheckFreeProduct?.OverAllFreeQty,
                RemainingQty:
                  isCheckFreeProduct?.OverAllFreeQty -
                  (isCheckFreeProduct?.FreeQty -
                    (item?.OrderQty -
                      isPaidProductAvailableInCartOtherType?.OrderQty)),
                FreeQty:
                  isCheckFreeProduct?.FreeQty -
                  (item?.OrderQty -
                    isPaidProductAvailableInCartOtherType?.OrderQty),
                FreeProdId: isCheckFreeProduct?.FreeProdId,
                OfferId: isCheckFreeProduct?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * Quantity), Quantity, true,)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount:
                  item?.OrderRate *
                  (isCheckFreeProduct?.FreeQty -
                    (item?.OrderQty -
                      isPaidProductAvailableInCartOtherType?.OrderQty)),
                FreeQty:
                  isCheckFreeProduct?.FreeQty -
                  (item?.OrderQty -
                    isPaidProductAvailableInCartOtherType?.OrderQty),
                CompleteRemove: false,
                insideinwardDtlId: true,
              });
            } else {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: isPaidproduct?.OrderQty,
                CompleteRemove: true,
                InwardDtlId: item?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: item?.Offer,
              });
              await ChangeFreeprodlistFn({
                OverAllFreeQty: isCheckFreeProduct?.OverAllFreeQty,
                RemainingQty: isCheckFreeProduct?.OverAllFreeQty,
                FreeQty: 0,
                FreeProdId: isCheckFreeProduct?.FreeProdId,
                OfferId: isCheckFreeProduct?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * Quantity), Quantity, true,)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount: item?.OrderRate * item?.OrderQty,
                FreeQty: item?.OrderQty,
                CompleteRemove: true,
                insideinwardDtlId: true,
              });
            }
          }
          //Change Remove OrderCartDetail
          //Remove FreeprodList
          //ChangeOfferApplied Products
        }
      } else {
        ///remove item wise offer
        if (isItemWiseOrQuantityProduct) {
          await ChangeOrderCardDetailsFn({
            BookingTypeName: item?.BookingTypeName,
            BuyProdQty: null,
            OrderQty: item?.OrderQty,
            CompleteRemove: true,
            InwardDtlId: item?.InwardDtlId,
            BuyInwardDtlId: null,
            Offer: item?.Offer,
          });
          await ChangeOfferAppliedProdsFn({
            inwardDtlId: item?.InwardDtlId,
            OfferAmount: item?.OrderRate * item?.OrderQty,
            FreeQty: item?.OrderQty,
            CompleteRemove: true,
          });
        } else if (isCheckFreeProduct) {
          // remove or update loyalty/code based free product which is added in cart
          const freeProdList = Array?.isArray(
            isCheckFreeProduct?.FreeProductsList
          )
            ? isCheckFreeProduct?.FreeProductsList?.[0]
            : isCheckFreeProduct?.FreeProductsList;
          let isPaidProductAvailableInCart = tableData?.find(
            (e) =>
              e?.InwardDtlId == item?.InwardDtlId &&
              e?.Offer == 0 &&
              item?.BookingTypeName == e?.BookingTypeName
          );
          if (isPaidProductAvailableInCart) {
            if (isPaidProductAvailableInCart?.OrderQty === item?.OrderQty) {
              //just remove Paid Qty
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: isPaidProductAvailableInCart?.OrderQty,
                CompleteRemove: true,
                InwardDtlId: isPaidProductAvailableInCart?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: 0,
              });
            } else if (
              isPaidProductAvailableInCart?.OrderQty > item?.OrderQty
            ) {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty:
                  isPaidProductAvailableInCart?.OrderQty - item?.OrderQty,
                CompleteRemove: false,
                InwardDtlId: isPaidProductAvailableInCart?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: 0,
              });
            } else if (
              isPaidProductAvailableInCart?.OrderQty < item?.OrderQty
            ) {
              //just remove Paid Qty
              //decrease FreeQty
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: -isPaidProductAvailableInCart?.OrderQty,
                RemoveAndUpdate: true,
                InwardDtlId: isPaidProductAvailableInCart?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: 0,
              });

              if (ischeckBothBookingType) {
                await ChangeFreeprodlistFn({
                  OverAllFreeQty: freeProdList?.OverAllFreeQty,
                  RemainingQty:
                    freeProdList?.OverAllFreeQty -
                    (ischeckBothBookingType?.OrderQty +
                      isPaidProductAvailableInCart?.OrderQty),
                  FreeQty:
                    ischeckBothBookingType?.OrderQty +
                    isPaidProductAvailableInCart?.OrderQty,
                  FreeProdId: isPaidProductAvailableInCart?.ProdId,
                  OfferId: freeProdList?.OfferId,
                });
                // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)
                await ChangeOfferAppliedProdsFn({
                  inwardDtlId: isPaidProductAvailableInCart?.InwardDtlId,
                  OfferAmount:
                    isPaidProductAvailableInCart?.OrderRate *
                    isPaidProductAvailableInCart?.OrderQty,
                  FreeQty: isPaidProductAvailableInCart?.OrderQty,
                  CompleteRemove: false,
                  insideinwardDtlId: true,
                });
              } else {
                await ChangeFreeprodlistFn({
                  OverAllFreeQty: item?.OrderQty,
                  RemainingQty:
                    item?.OrderQty - isPaidProductAvailableInCart?.OrderQty,
                  FreeQty: isPaidProductAvailableInCart?.OrderQty,
                  FreeProdId: isPaidProductAvailableInCart?.ProdId,
                  OfferId: freeProdList?.OfferId,
                });
                // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)
                await ChangeOfferAppliedProdsFn({
                  inwardDtlId: isPaidProductAvailableInCart?.InwardDtlId,
                  OfferAmount:
                    isPaidProductAvailableInCart?.OrderRate *
                    isPaidProductAvailableInCart?.OrderQty,
                  FreeQty: isPaidProductAvailableInCart?.OrderQty,
                  CompleteRemove: false,
                  insideinwardDtlId: true,
                });
              }
            }
          } else {
            if (ischeckBothBookingType) {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: isPaidProductAvailableInCart?.OrderQty,
                CompleteRemove: true,
                InwardDtlId: item?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: item?.Offer,
              });
              await ChangeFreeprodlistFn({
                OverAllFreeQty: freeProdList?.OverAllFreeQty,
                RemainingQty: freeProdList?.OverAllFreeQty - item?.OrderQty,
                FreeQty: freeProdList?.FreeQty - item?.OrderQty,
                FreeProdId: freeProdList?.FreeProdId,
                OfferId: freeProdList?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * Quantity), Quantity, true,)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount:
                  (freeProdList?.FreeQty - item?.OrderQty) * item?.OrderRate,
                FreeQty: item?.OrderQty,
                CompleteRemove: false,
                insideinwardDtlId: true,
              });
            } else {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: isPaidProductAvailableInCart?.OrderQty,
                CompleteRemove: true,
                InwardDtlId: item?.InwardDtlId,
                BuyInwardDtlId: null,
                Offer: item?.Offer,
              });
              await ChangeFreeprodlistFn({
                OverAllFreeQty: freeProdList?.OverAllFreeQty,
                RemainingQty: freeProdList?.OverAllFreeQty,
                FreeQty: 0,
                FreeProdId: freeProdList?.FreeProdId,
                OfferId: freeProdList?.OfferId,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * Quantity), Quantity, true,)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount: item?.OrderRate * item?.OrderQty,
                FreeQty: item?.OrderQty,
                CompleteRemove: true,
                insideinwardDtlId: true,
              });
            }
          }
        } else {
          let ModifiedOrderCardDetail = JSON.parse(JSON.stringify(tableData));

          const data = ModifiedOrderCardDetail?.filter(
            (e) =>
              !(
                e?.InwardDtlId === item?.InwardDtlId &&
                e?.Offer === item?.Offer &&
                e?.BookingTypeName === item?.BookingTypeName &&
                (!e?.SalesId || OrderType == 'Hold')
              )
          );
          return dispatch(changeOrderCardDetails(data));
        }
      }
    } else {
      const isCheckFreeProductOutside = OfferFreeProduct?.find(
        (exp) => exp?.InwardDtlId == item?.InwardDtlId
      );

      if (!isCheckFreeProductOutside) {
        await ChangeOrderCardDetailsFn({
          BookingTypeName: item?.BookingTypeName,
          BuyProdQty: null,
          OrderQty: item?.OrderQty,
          CompleteRemove: true,
          InwardDtlId: item?.InwardDtlId,
          BuyInwardDtlId: null,
          Offer: item?.Offer,
          OrderRate: item?.OrderRate,
        });
      } else {
        const isCheck = GlobalOfferAppliedProductsData?.find(
          (exp) => exp?.InwardDtlId === item?.InwardDtlId
        );
        const FreeProd = OfferFreeProduct?.find(
          (exp) => exp?.InwardDtlId === item?.InwardDtlId
        );

        if (isCheck) {
          let inward =
            isCheck?.FreeProductsList?.[0]?.ProdVariantDetails?.[0]
              ?.StockDetails?.[0]?.FreeInwardDtlId;

          let isPaidproduct = tableData?.find(
            (e) =>
              e?.InwardDtlId == inward &&
              e?.Offer == 0 &&
              e?.BookingTypeName == item?.BookingTypeName
          );
          if (isPaidproduct) {
            let ischeckBothBookingType = tableData?.find(
              (e) =>
                e?.InwardDtlId == inward &&
                e?.Offer > 0 &&
                e?.BookingTypeName != item?.BookingTypeName
            );

            //if any Paid Product is there, we have to Merge With That
            if (ischeckBothBookingType) {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty:
                  isPaidproduct?.OrderQty +
                  isCheck?.ActualFreeQty -
                  ischeckBothBookingType?.OrderQty,
                CompleteRemoveBuyAndAddWithPaid: true,
                InwardDtlId: isPaidproduct?.InwardDtlId,
                BuyInwardDtlId: item?.InwardDtlId,
                Offer: item?.Offer,
              });

              await ChangeFreeprodlistFn({
                OverAllFreeQty: FreeProd?.OverAllFreeQty - item?.OrderQty,
                RemainingQty:
                  FreeProd?.OverAllFreeQty -
                  item?.OrderQty -
                  (FreeProd?.FreeQty - item?.OrderQty),
                FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                FreeProdId: FreeProd?.FreeProdId,
                OfferId: FreeProd?.OfferId,
                CompleteRemove: false,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount:
                  isPaidproduct?.OrderRate *
                  (FreeProd?.FreeQty - item?.OrderQty),
                FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                CompleteRemove: false,
                insideinwardDtlId: false,
              });
            } else {
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: isPaidproduct?.OrderQty + isCheck?.ActualFreeQty,
                CompleteRemoveBuyAndAddWithPaid: true,
                InwardDtlId: isPaidproduct?.InwardDtlId,
                BuyInwardDtlId: item?.InwardDtlId,
                Offer: item?.Offer,
              });

              await ChangeFreeprodlistFn({
                OverAllFreeQty: item?.OrderQty,
                RemainingQty: item?.OrderQty - isPaidproduct?.OrderQty,
                FreeQty: isPaidproduct?.OrderQty,
                FreeProdId: FreeProd?.FreeProdId,
                OfferId: FreeProd?.OfferId,
                CompleteRemove: true,
              });
              // await ChangeOfferAppliedProdsFn(isPaidproduct?.InwardDtlId, (isPaidproduct?.OrderRate * isPaidproduct?.OrderQty), isPaidproduct?.OrderQty, true, insideinwardDtlId true)
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount: isPaidproduct?.OrderRate * isPaidproduct?.OrderQty,
                FreeQty: isPaidproduct?.OrderQty,
                CompleteRemove: true,
                insideinwardDtlId: false,
              });
            }
          } else {
            //have to find if thereis two Booking Type is there
            //Convert That Free Product To Paid Product
            let ischeckBothBookingType = tableData?.find(
              (e) =>
                e?.InwardDtlId == inward &&
                e?.Offer > 0 &&
                e?.BookingTypeName != item?.BookingTypeName
            );

            let FreeProductSameBookingType = tableData?.find(
              (e) =>
                e?.InwardDtlId == inward &&
                e?.Offer > 0 &&
                e?.BookingTypeName == item?.BookingTypeName
            );
            if (ischeckBothBookingType) {
              //Convert That Free Product To Paid Product

              //merge that paid product with same booking type
              //decrease free prod list qty
              //change offer applied product qty
              // await ChangeOrderCardDetailsFn(item?.BookingTypeName, null, ischeckBothBookingType?.OrderQty + FreeProductSameBookingType?.OrderQty, false, ischeckBothBookingType?.InwardDtlId, item?.InwardDtlId, item?.Offer, true)
              if (FreeProductSameBookingType?.OrderQty >= item?.OrderQty) {
                await ChangeFreeprodlistFn({
                  OverAllFreeQty: FreeProd?.OverAllFreeQty - item?.OrderQty,
                  RemainingQty:
                    FreeProd?.OverAllFreeQty -
                    item?.OrderQty -
                    (FreeProd?.FreeQty - item?.OrderQty),
                  FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                  FreeProdId: FreeProd?.FreeProdId,
                  OfferId: FreeProd?.OfferId,
                  CompleteRemove: false,
                });
                await ChangeOrderCardDetailsFn({
                  BookingTypeName: item?.BookingTypeName,
                  BuyProdQty: item?.OrderQty,
                  OrderQty: FreeProductSameBookingType?.OrderQty,
                  CompleteRemoveconvertFreetoPaidNotCompletely: true,
                  InwardDtlId: inward,
                  BuyInwardDtlId: item?.InwardDtlId,
                  Offer: item?.Offer,
                });
                await ChangeOfferAppliedProdsFn({
                  inwardDtlId: item?.InwardDtlId,
                  OfferAmount:
                    (FreeProd?.FreeQty - item?.OrderQty) *
                    ischeckBothBookingType?.OrderRate,
                  FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                  CompleteRemove: false,
                  insideinwardDtlId: false,
                });
              } else {
                let data = isCheckFreeProductOutside?.FreeQty - item?.OrderQty;
                //First i Calculate Another Booking Type Qty
                let anotherBookingType = tableData?.find(
                  (e) =>
                    e?.InwardDtlId == item?.InwardDtlId &&
                    e?.Offer == 0 &&
                    e?.BookingTypeName != item?.BookingTypeName
                );
                let anotherBookingTypeOffer = tableData?.find(
                  (e) =>
                    e?.InwardDtlId == inward &&
                    e?.Offer > 0 &&
                    e?.BookingTypeName != item?.BookingTypeName
                );

                let diff =
                  item?.OrderQty - FreeProductSameBookingType?.OrderQty;

                //SameBookingFreeQty
                //FreeProductSameBookingType?.OrderQty

                //Another BookingType Paid Qty
                //anotherBookingType

                //anotherBookingType?.Free OrderQty
                //ischeckBothBookingType

                //anotherBookingType?.OrderQty-ischeckBothBookingType?.OrderQty
                //convert another Booking Type Qty also Free to Paid

                if (
                  (anotherBookingType?.OrderQty || 0) <
                  anotherBookingTypeOffer?.OrderQty
                ) {
                  //paidproduct                         ischeckBothBookingType?.OrderQty-anotherBookingType?.OrderQty
                  //PaidProdcut Current BookingType    FreeProductSameBookingType?.OrderQty
                  let paidproductAnotherType =
                    ischeckBothBookingType?.OrderQty -
                    anotherBookingType?.OrderQty;
                  let paidproductCurrentType =
                    FreeProductSameBookingType?.OrderQty;

                  await ChangeOrderCardDetailsFn({
                    BookingTypeName: item?.BookingTypeName,
                    BuyProdQty: paidproductAnotherType,
                    OrderQty: paidproductCurrentType,
                    CompleteRemoveconvertFreetoPaidTwoTypes: true,
                    InwardDtlId: inward,
                    BuyInwardDtlId: item?.InwardDtlId,
                    Offer: item?.Offer,
                  });

                  await ChangeFreeprodlistFn({
                    OverAllFreeQty: FreeProd?.OverAllFreeQty - item?.OrderQty,
                    RemainingQty:
                      FreeProd?.OverAllFreeQty -
                      item?.OrderQty -
                      (FreeProd?.FreeQty -
                        (paidproductCurrentType + paidproductCurrentType)),
                    FreeQty:
                      FreeProd?.FreeQty -
                      (paidproductCurrentType + paidproductCurrentType),
                    FreeProdId: FreeProd?.FreeProdId,
                    OfferId: FreeProd?.OfferId,
                    CompleteRemove: false,
                  });
                  await ChangeOfferAppliedProdsFn({
                    inwardDtlId: item?.InwardDtlId,
                    OfferAmount:
                      (FreeProd?.FreeQty - item?.OrderQty) *
                      ischeckBothBookingType?.OrderRate,
                    FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                    CompleteRemove: false,
                    insideinwardDtlId: false,
                  });
                } else {
                  await ChangeFreeprodlistFn({
                    OverAllFreeQty: FreeProd?.OverAllFreeQty - item?.OrderQty,
                    RemainingQty:
                      FreeProd?.OverAllFreeQty -
                      item?.OrderQty -
                      (FreeProd?.FreeQty - item?.OrderQty),
                    FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                    FreeProdId: FreeProd?.FreeProdId,
                    OfferId: FreeProd?.OfferId,
                    CompleteRemove: false,
                  });
                  await ChangeOrderCardDetailsFn({
                    BookingTypeName: item?.BookingTypeName,
                    BuyProdQty: null,
                    OrderQty: FreeProductSameBookingType?.OrderQty,
                    CompleteRemoveconvertFreetoPaid: true,
                    InwardDtlId: inward,
                    BuyInwardDtlId: item?.InwardDtlId,
                    Offer: item?.Offer,
                  });
                  await ChangeOfferAppliedProdsFn({
                    inwardDtlId: item?.InwardDtlId,
                    OfferAmount:
                      (FreeProd?.FreeQty - item?.OrderQty) *
                      ischeckBothBookingType?.OrderRate,
                    FreeQty: FreeProd?.FreeQty - item?.OrderQty,
                    CompleteRemove: false,
                    insideinwardDtlId: false,
                  });
                }
              }
            } else {
              await ChangeFreeprodlistFn({
                OverAllFreeQty: item?.OrderQty,
                RemainingQty: item?.OrderQty - isPaidproduct?.OrderQty,
                FreeQty: isPaidproduct?.OrderQty,
                FreeProdId: FreeProd?.FreeProdId,
                OfferId: FreeProd?.OfferId,
                CompleteRemove: true,
              });
              await ChangeOrderCardDetailsFn({
                BookingTypeName: item?.BookingTypeName,
                BuyProdQty: null,
                OrderQty: FreeProductSameBookingType?.OrderQty,
                CompleteRemoveconvertFreetoPaid: true,
                InwardDtlId: inward,
                BuyInwardDtlId: item?.InwardDtlId,
                Offer: item?.Offer,
              });
              await ChangeOfferAppliedProdsFn({
                inwardDtlId: item?.InwardDtlId,
                OfferAmount:
                  (isCheck?.ActualFreeQty -
                    FreeProductSameBookingType?.OrderQty) *
                  isPaidproduct?.OrderQty,
                FreeQty:
                  isCheck?.ActualFreeQty - FreeProductSameBookingType?.OrderQty,
                CompleteRemove: true,
                insideinwardDtlId: false,
              });
            }
          }
        } else {
          let ischeckBothBookingType = tableData?.find(
            (e) =>
              e?.InwardDtlId == item?.InwardDtlId &&
              e?.Offer == 0 &&
              e?.BookingTypeName != item?.BookingTypeName
          );

          if (ischeckBothBookingType) {
            await ChangeOrderCardDetailsFn({
              BookingTypeName: item?.BookingTypeName,
              BuyProdQty: null,
              OrderQty: 0,
              CompleteRemove: true,
              InwardDtlId: item?.InwardDtlId,
              BuyInwardDtlId: item?.InwardDtlId,
              Offer: item?.Offer,
            });
            await ChangeFreeprodlistFn({
              OverAllFreeQty: FreeProd?.OverAllFreeQty - item?.OrderQty,
              RemainingQty: FreeProd?.OverAllFreeQty - item?.OrderQty,
              FreeQty: 0,
              FreeProdId: FreeProd?.FreeProdId,
              OfferId: FreeProd?.OfferId,
              CompleteRemove: false,
            });
          } else {
            await ChangeOrderCardDetailsFn({
              BookingTypeName: item?.BookingTypeName,
              BuyProdQty: null,
              OrderQty: 0,
              CompleteRemove: true,
              InwardDtlId: item?.InwardDtlId,
              BuyInwardDtlId: item?.InwardDtlId,
              Offer: item?.Offer,
            });
            await ChangeFreeprodlistFn({
              OverAllFreeQty: item?.OrderQty,
              RemainingQty: 0,
              FreeQty: 0,
              FreeProdId: FreeProd?.FreeProdId,
              OfferId: FreeProd?.OfferId,
              CompleteRemove: true,
            });
          }
          //Remove From Free ProdList  That Entirely
        }
      }
    }
  };

  // const removeFromCart = async (item) => {
  //   setPreviousdataLength(tableData?.length);
  //   if (item?.BookingTypeName !== 'Dine In' && OrderType !== 'Hold') {
  //     const UpdatedData = tableData?.filter(
  //       (cartItem) =>
  //         !(
  //           cartItem?.ProdId === item?.ProdId &&
  //           cartItem?.InwardDtlId === item?.InwardDtlId &&
  //           cartItem?.OrderRate === item?.OrderRate &&
  //           cartItem?.BookingTypeName === item?.BookingTypeName &&
  //           !cartItem?.SalesId
  //         )
  //     );

  //     if (OfferCheckedInSetup && preferenceOffer) {
  //       await applyOffer(UpdatedData);
  //     } else {
  //       dispatch(changeOrderCardDetails(UpdatedData));
  //     }

  //     await dispatch(
  //       ChangeTotalAmount(
  //         GlobalExtraCharge?.filter((extra) => {
  //           if (BookingType === 'Dine In') {
  //             // Remove extra charges linked to the removed product
  //             return !(extra.ProdId === item?.ProdId && !extra.SalesId);
  //           } else if (BookingType === 'TakeAway') {
  //             // Remove extra charges only if SalesId is not present
  //             return extra.ProdId !== item?.ProdId;
  //           }
  //           return true; // Keep everything else
  //         })
  //       )
  //     );
  //     // if the quantity of the item is 1, remove the item from the cart
  //     if (tableData?.length <= 1) {
  //       await dispatch(changeReorderHoldDetails({}));
  //       await dispatch(changeReorderProductDetails([]));
  //       await dispatch(changeUnpaidData(false));
  //       await dispatch(changeBookingType('TakeAway'));
  //       await dispatch(changeTokenOnly(false));
  //       await dispatch(ChangeTotalAmount([]));
  //       await dispatch(changeAllProductTokenAvailable(false));
  //       await dispatch(ChangeOverAllDiscSales(null));
  //       await dispatch(ChangeOverAllDiscEstimate(null));
  //       await dispatch(changeSelProdWiseEst([]));
  //     }
  //   } else if (item?.BookingTypeName !== 'Dine In' && OrderType === 'Hold') {
  //     const UpdatedData = tableData?.filter(
  //       (cartItem) =>
  //         !(
  //           cartItem?.ProdId === item?.ProdId &&
  //           cartItem?.InwardDtlId === item?.InwardDtlId &&
  //           cartItem?.OrderRate === item?.OrderRate &&
  //           cartItem?.BookingTypeName === item?.BookingTypeName
  //         )
  //     );

  //     if (OfferCheckedInSetup && preferenceOffer) {
  //       await applyOffer(UpdatedData);
  //     } else {
  //       dispatch(changeOrderCardDetails(UpdatedData));
  //     }

  //     await dispatch(
  //       ChangeTotalAmount(
  //         GlobalExtraCharge?.filter((extra) => {
  //           if (BookingType === 'Dine In') {
  //             // Remove extra charges linked to the removed product
  //             return !(extra.ProdId === item?.ProdId && !extra.SalesId);
  //           } else if (BookingType === 'TakeAway') {
  //             // Remove extra charges only if SalesId is not present
  //             return extra.ProdId !== item?.ProdId;
  //           }
  //           return true; // Keep everything else
  //         })
  //       )
  //     );
  //     // if the quantity of the item is 1, remove the item from the cart
  //     if (tableData?.length <= 1) {
  //       await dispatch(changeReorderHoldDetails({}));
  //       await dispatch(changeReorderProductDetails([]));
  //       await dispatch(changeUnpaidData(false));
  //       await dispatch(changeBookingType('TakeAway'));
  //       await dispatch(changeTokenOnly(false));
  //       await dispatch(changeAllProductTokenAvailable(false));
  //       await dispatch(ChangeOverAllDiscSales(null));
  //       await dispatch(ChangeOverAllDiscEstimate(null));
  //       await dispatch(changeSelProdWiseEst([]));
  //       await dispatch(ChangeTotalAmount([]));
  //     }
  //   } else if (item?.BookingTypeName === 'Dine In') {
  //     const UpdatedData = tableData?.filter(
  //       (cartItem) =>
  //         !(
  //           cartItem?.ProdId === item?.ProdId &&
  //           cartItem?.InwardDtlId === item?.InwardDtlId &&
  //           cartItem?.OrderRate === item?.OrderRate &&
  //           cartItem?.BookingTypeName === item?.BookingTypeName &&
  //           !cartItem?.SalesId
  //         )
  //     );

  //     if (OfferCheckedInSetup && preferenceOffer) {
  //       await applyOffer(UpdatedData);
  //     } else {
  //       dispatch(changeOrderCardDetails(UpdatedData));
  //     }
  //     await dispatch(
  //       ChangeTotalAmount(
  //         GlobalExtraCharge?.filter((extra) => {
  //           if (BookingType === 'Dine In') {
  //             // Remove extra charges linked to the removed product
  //             return !(extra.ProdId === item?.ProdId && !extra.SalesId);
  //           } else if (BookingType === 'TakeAway') {
  //             // Remove extra charges only if SalesId is not present
  //             return extra.ProdId !== item?.ProdId;
  //           }
  //           return true; // Keep everything else
  //         })
  //       )
  //     ); // if the quantity of the item is 1, remove the item from the cart
  //     if (tableData?.length <= 1) {
  //       await dispatch(changeReorderHoldDetails({}));
  //       await dispatch(changeReorderProductDetails([]));
  //       await dispatch(changeUnpaidData(false));
  //       await dispatch(ChangeSelectedCustDisable(false));
  //       await dispatch(changeSelectedOption(false));
  //       await dispatch(changeBookingType('TakeAway'));
  //       await dispatch(changeTokenOnly(false));
  //       await dispatch(changeAllProductTokenAvailable(false));
  //       await dispatch(ChangeOverAllDiscSales(null));
  //       await dispatch(ChangeOverAllDiscEstimate(null));
  //       await dispatch(changeSelProdWiseEst([]));
  //       await dispatch(ChangeTotalAmount([]));
  //     }
  //   }
  // };

  useEffect(() => {
    // setTriggerAnimation(true);
    if (tableData?.length === 0) {
      dispatch(ClearOfferAppliedProducts());
    }
    if (!isMobile) {
      const customerDisplayWindow = getCustomerDisplayWindow();
      if (customerDisplayWindow && !customerDisplayWindow.closed) {
        const updatedData = {
          userData: tableData,
        };
        customerDisplayWindow.postMessage(updatedData, '*');
      }
      const timer = setTimeout(() => {
        setTriggerAnimation(false);
      }, 400);
      return () => clearTimeout(timer);
    }
  }, [tableData]);
  useEffect(() => {
    setPreviousdataLength(PreviousOrderLength);
  }, [PreviousOrderLength]);
  const OpenEditTotalAmount = () => {
    setOpenEditTotalAmt(true);
  };
  const handleEditTotalAmountCancel = () => {
    setOpenEditTotalAmt(false);
  };
  const handleImeiDetails = (value) => {
    setOpenImeiDetail(true);
    setModaldata(value);
  };
  const handleImeiDetailClose = () => {
    setOpenImeiDetail(false);
  };

  const handleEditQuantity = (value) => {
    console.log(value, 'value');

    if (OtherServicesglobal && value.Type == 'OS' && value.ServiceType == 'I') {
      setEditQuantity(false);
    } else {
      setEditQuantity(true);
      setModaldata(value);
      setIndex(value?.localId);
    }
  };

  const handleEditQuantityCancel = () => {
    setEditQuantity(false);
  };

  return (
    <div className="BSBilling3-tablediv">
      <table className="BSBill-Table3">
        <thead>
          <tr
            className="BSBill-Table3-throw"
            style={{
              color: SelectedBillColor?.['FontColor'],
              backgroundColor: SelectedBillColor?.['BackgroundColor'],
              fontFamily: SelectedFont,
            }}
          >
            {tableOptions?.map((item) => (
              <>
                {item.OptionName == 'Sl.No' && BookingTypeBoth && (
                  <th
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '13px',
                      width: '15px',
                      padding: '1px',
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="Serial Number">{''}</Tooltip>
                    ) : (
                      <div>{''}</div>
                    )}
                  </th>
                )}
                {item.OptionName == 'Sl.No' && (
                  <th
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '13px',
                      width: '10px',
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="Serial Number">Sl.No</Tooltip>
                    ) : (
                      <div>Sl.No</div>
                    )}
                  </th>
                )}
                {item.OptionName == 'Item' && (
                  <th
                    className="billtable3th"
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="Item Name">Item</Tooltip>
                    ) : (
                      <div> Item </div>
                    )}
                  </th>
                )}
                {item.OptionName == 'MRP' && (
                  <th
                    className="billtable3th"
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                      width: '20px',
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="MRP">MRP</Tooltip>
                    ) : (
                      <div>MRP</div>
                    )}
                  </th>
                )}
                {item.OptionName == 'Discount' && (
                  <th
                    className="billtable3th"
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                      width: '20px',
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="Discount">₹/%</Tooltip>
                    ) : (
                      <div>₹/% </div>
                    )}
                  </th>
                )}
                {item.OptionName == 'Quantity' && (
                  <th
                    className="billtable3th"
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                      width: '20px',
                    }}
                    // onClick={tableData?.length > 0 ? OpenEditTotalAmount : ""}
                    onClick={() => {
                      if (tableData?.length > 0) {
                        OpenEditTotalAmount();
                      }
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="Quantity">Qty</Tooltip>
                    ) : (
                      <div>Qty</div>
                    )}
                  </th>
                )}
                {item.OptionName == 'Rate' && (
                  <th
                    className="billtable3th"
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                      width: '20px',
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="Rate">Rt</Tooltip>
                    ) : (
                      <div> Rt </div>
                    )}
                  </th>
                )}
                {item.OptionName == 'Amount' && (
                  <th
                    className="billtable3th"
                    style={{
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                      width: '20px',
                    }}
                  >
                    {!isMobile ? (
                      <Tooltip title="Amount">Amt</Tooltip>
                    ) : (
                      <div>Amt</div>
                    )}
                  </th>
                )}

                {item.OptionName == 'Delete' && (
                  <th
                    className="billtable3th"
                    style={{
                      width: '10px',
                      fontFamily: SelectedFont,
                      fontWeight: '600',
                      fontSize: '16px',
                    }}
                  >
                    {tableData?.length > 0 ? (
                      <Popconfirm
                        title="Delete the items"
                        description="Are you sure you want to clear these items?"
                        okText="Yes"
                        placement="leftTop"
                        cancelText="No"
                        onConfirm={() => {
                          Clearall();
                        }}
                      >
                        <div className="del-all-btn">
                          {' '}
                          {!isMobile ? (
                            <Tooltip title="Delete All" placement="left">
                              {' '}
                              <AiFillDelete />{' '}
                            </Tooltip>
                          ) : (
                            <div>
                              {' '}
                              <AiFillDelete />{' '}
                            </div>
                          )}
                        </div>
                      </Popconfirm>
                    ) : (
                      <div className="del-all-btn">
                        {!isMobile ? (
                          <Tooltip title="Delete" placement="left">
                            <AiFillDelete />
                          </Tooltip>
                        ) : (
                          <div>
                            {' '}
                            <AiFillDelete />{' '}
                          </div>
                        )}
                      </div>
                    )}
                  </th>
                )}
              </>
            ))}
          </tr>
        </thead>

        {/* For Reorder TakeWay */}
        {OldtableDataTakeAway?.length > 0 && (
          <tbody className="table3body">
            {OldtableDataTakeAway?.map((item, index) => (
              <tr
                key={index}
                className={`${item?.SalesId && OrderType !== 'Hold'
                  ? 'BSBill-Table3-content-Disabled'
                  : 'BSBill-Table3-content'
                  } 
            
               `}
                style={{
                  fontFamily: SelectedFont ? SelectedFont : '',

                  backgroundColor:
                    BillOrderPre === 'Y'
                      ? item?.SalesId && OrderType !== 'Hold'
                        ? 'rgb(243, 248, 213)'
                        : triggerAnimation &&
                          index === 0 &&
                          !item?.SalesId &&
                          tableDataTakeAway?.length >= PreviousdataLength
                          ? 'wheat'
                          : triggerAnimation &&
                            index === 0 &&
                            tableDataTakeAway?.length >= PreviousdataLength &&
                            !HoldOrderDtl &&
                            !UnpaidData
                            ? 'wheat'
                            : 'inherit'
                      : 'none',
                  background:
                    item?.SalesId && OrderType !== 'Hold'
                      ? 'rgb(243, 248, 213)'
                      : GlobEstBooking === 'ParEst' &&
                        GlobProdwisedata?.includes(
                          item?.InwardDtlId + ' ' + item?.BookingTypeName
                        )
                        ? '#b2d1f7'
                        : index % 2 === 0
                          ? 'white'
                          : SelectedBillColor?.['OverallBackgroundColor']
                            ? SelectedBillColor?.['OverallBackgroundColor']
                            : '#d6d6d6',
                  animation:
                    BillOrderPre === 'Y' && !BookingTypeBoth
                      ? triggerAnimation &&
                        index === 0 &&
                        !item?.SalesId &&
                        tableDataTakeAway?.length >= PreviousdataLength &&
                        !HoldOrderDtl &&
                        !UnpaidData
                        ? 'splashAnimation 0.5s ease-in-out'
                        : 'none'
                      : 'none',
                }}
              >
                {tableOptions?.map((tableitem) => (
                  <>
                    {BookingTypeBoth &&
                      index == 0 &&
                      tableitem.OptionName == 'Sl.No' && (
                        <td
                          rowspan={tableData.length}
                          style={{ backgroundColor: '#CFB59D' }}
                        >
                          <img width="30px" alt="" src={TakeAwayIcon} />
                        </td>
                      )}

                    {tableitem.OptionName == 'Sl.No' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '0px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {index + 1}
                      </td>
                    )}
                    {tableitem.OptionName == 'Item' && (
                      <>
                        <td
                          className="Table3-items for-combo"
                          style={{ fontFamily: 'Poppins' }}
                          onClick={() =>
                            item.FullProductIdentifierDtls?.length > 0 ||
                              item.ProductIdentifierDtls?.length > 0
                              ? handleImeiDetails(item)
                              : editField && handleEditQuantity(item)
                          }
                        >
                          {item?.ProdName}
                          &nbsp;{' '}
                          {item?.BrandName !== null ? item?.BrandName : ''}
                          {item?.Type != 'C' && (
                            <>
                              <p
                                className="Tbl3-Variant"
                                style={{ fontFamily: 'Poppins' }}
                              >
                                (
                                {!item?.ProdVariantName?.toLowerCase()?.includes(
                                  'variant'
                                ) && <span>{item?.ProdVariantName} </span>}
                                {item?.Size}
                                {item?.SinglePc == 'Y' ? 'PCS' : item?.UomName})
                              </p>
                              {item?.OfferMessage &&
                                !Array.isArray(item.OfferMessage) && (
                                  <p
                                    className={`offermessageTag ${!isMobile ? 'desktop' : ''}`}
                                  >
                                    {item.OfferMessage?.split('>')?.[0] +
                                      `> ${item?.OrderQty} Eligible Free`}
                                  </p>
                                )}
                            </>
                          )}
                          {item?.Type === 'C' && (
                            <div
                              className="Tbl3-Variant"
                              style={{ fontFamily: 'Poppins' }}
                            >
                              {item.ProdDetail?.map((prod, index) => (
                                <p key={index}>
                                  {prod.ProdName} - {prod.Size} {prod.UomName}
                                </p>
                              ))}
                            </div>
                          )}
                          {productBasedExtraCharges?.find(
                            (find) => find.ProdId === item.ProdId
                          ) !== undefined && (
                              <div
                                style={{
                                  fontSize: '10px',
                                  fontWeight: '500',
                                  whiteSpace: 'nowrap',
                                }}
                              >
                                Extra Charges :{' '}
                                {
                                  productBasedExtraCharges?.find(
                                    (find) => find.ProdId === item.ProdId
                                  )?.TotalAmt
                                }
                              </div>
                            )}
                        </td>
                      </>
                    )}
                    {tableitem.OptionName == 'MRP' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '0px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.MRP}
                      </td>
                    )}
                    {tableitem.OptionName == 'Discount' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          width: '40px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.Type != 'C'
                          ? item.Offer && item.Offer > 0
                            ? item.Offer
                            : '-'
                          : item?.OfferPrice && item?.OfferPrice > 0
                            ? item?.OfferType === 'F'
                              ? `₹${safeRound(item.OfferPrice)}`
                              : `${item.OfferPrice}%`
                            : '-'}
                      </td>
                    )}
                    {tableitem.OptionName == 'Quantity' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '40px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.OrderQty}
                      </td>
                    )}
                    {tableitem.OptionName == 'Rate' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '40px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {allowDecimal
                          ? Number(item?.OrderRate || 0).toFixed(2)
                          : Number(item?.OrderRate || 0)}
                      </td>
                    )}
                    {tableitem.OptionName == 'Amount' && (
                      <td
                        className="Table3-item-price"
                        style={{ width: '60px', fontFamily: 'Poppins' }}
                        onClick={() => {
                          // if (editField) {
                          //   handleEditQuantity(item);
                          // }
                          if (GetCustId) {
                            handleCustomerProductPriceHistory(item);
                          }
                        }}
                      >
                        {allowDecimal
                          ? Number(
                            item?.TotalAmt - (item?.Offer || 0) || 0
                          ).toFixed(2)
                          : Number(item?.TotalAmt - (item?.Offer || 0) || 0)}
                      </td>
                    )}
                    {tableitem.OptionName == 'Delete' && (
                      <td className="Table3-editicon">
                        <AiOutlineClose
                          onClick={() => removeFromCart(item)}
                          style={{ color: '#FF4D4F', cursor: 'pointer' }}
                        />
                      </td>
                    )}
                  </>
                ))}
              </tr>
            ))}

            {EditQuantity && OldtableDataTakeAway?.length > 0 && (
              <BSBillingEditQuantity
                handleEditQuantityCancel={handleEditQuantityCancel}
                BSBillingEditQuantity={EditQuantity}
                Productdata={Modaldata}
                Index={Index}
                shortKeyMethod={shortKeyMethod}
              />
            )}
          </tbody>
        )}

        {/* Reorder DineIn */}
        {OldtableDataDinein?.length > 0 && (
          <tbody className="table3body">
            {OldtableDataDinein?.map((item, index) => (
              <tr
                key={OldtableDataTakeAway?.length + index}
                className={`${item?.SalesId
                  ? 'BSBill-Table3-content-Disabled'
                  : 'BSBill-Table3-content'
                  } 
            
               `}
                style={{
                  fontFamily: SelectedFont ? SelectedFont : '',

                  backgroundColor:
                    BillOrderPre === 'Y'
                      ? item?.SalesId
                        ? 'rgb(243, 248, 213)'
                        : BookingType === 'Dine In' &&
                          triggerAnimation &&
                          OldtableDataTakeAway?.length + index === 0 &&
                          !item?.SalesId &&
                          tableDataDinein?.length >= PreviousdataLength
                          ? 'wheat'
                          : BookingType !== 'Dine In' &&
                            triggerAnimation &&
                            OldtableDataTakeAway?.length + index === 0 &&
                            tableDataDinein?.length >= PreviousdataLength &&
                            !HoldOrderDtl &&
                            !UnpaidData
                            ? 'wheat'
                            : 'inherit'
                      : 'none',
                  background: item?.SalesId
                    ? 'rgb(243, 248, 213)'
                    : GlobEstBooking === 'ParEst' &&
                      GlobProdwisedata?.includes(
                        item?.InwardDtlId + ' ' + item?.BookingTypeName
                      )
                      ? '#b2d1f7'
                      : (OldtableDataTakeAway?.length + index) % 2 === 0
                        ? 'white'
                        : SelectedBillColor?.['OverallBackgroundColor']
                          ? SelectedBillColor?.['OverallBackgroundColor']
                          : '#d6d6d6',
                  animation:
                    BillOrderPre === 'Y' && !BookingTypeBoth
                      ? triggerAnimation &&
                        OldtableDataTakeAway?.length + index === 0 &&
                        !item?.SalesId &&
                        tableDataDinein?.length >= PreviousdataLength &&
                        !HoldOrderDtl &&
                        !UnpaidData
                        ? 'splashAnimation 0.5s ease-in-out'
                        : 'none'
                      : 'none',
                }}
              >
                {tableOptions?.map((tableitem) => (
                  <>
                    {BookingTypeBoth &&
                      index == 0 &&
                      tableitem.OptionName == 'Sl.No' && (
                        <td
                          rowspan={tableData.length}
                          style={{ backgroundColor: '#A2C3CD' }}
                        >
                          <img width="30px" alt="" src={dineInIcon} />
                        </td>
                      )}

                    {tableitem.OptionName == 'Sl.No' && (
                      <td
                        style={{
                          width: '0px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {OldtableDataTakeAway?.length + index + 1}
                      </td>
                    )}
                    {tableitem.OptionName == 'Item' && (
                      <>
                        <td
                          className="Table3-items for-combo"
                          style={{ fontFamily: 'Poppins' }}
                          onClick={() => {
                            if (editField) {
                              handleEditQuantity(item);
                            }
                          }}
                        >
                          {item?.ProdName}
                          &nbsp;{' '}
                          {item?.BrandName !== null ? item?.BrandName : ''}
                          {item?.Type != 'C' && (
                            <>
                              <p
                                className="Tbl3-Variant"
                                style={{ fontFamily: 'Poppins' }}
                              >
                                (
                                {!item?.ProdVariantName?.toLowerCase()?.includes(
                                  'variant'
                                ) && <span>{item?.ProdVariantName} </span>}
                                {item?.Size}
                                {item?.SinglePc == 'Y' ? 'PCS' : item?.UomName})
                              </p>
                              {item?.OfferMessage &&
                                !Array.isArray(item.OfferMessage) && (
                                  <p
                                    className={`offermessageTag ${!isMobile ? 'desktop' : ''}`}
                                  >
                                    {item.OfferMessage?.split('>')?.[0] +
                                      `> ${item?.OrderQty} Eligible Free`}
                                  </p>
                                )}
                            </>
                          )}
                          {item?.Type === 'C' && (
                            <div
                              className="Tbl3-Variant"
                              style={{ fontFamily: 'Poppins' }}
                            >
                              {item.ProdDetail?.map((prod, index) => (
                                <p key={index}>
                                  {prod.ProdName} - {prod.Size} {prod.UomName}
                                </p>
                              ))}
                            </div>
                          )}
                          {productBasedExtraCharges?.find(
                            (find) => find.ProdId === item.ProdId
                          ) !== undefined && (
                              <div
                                style={{
                                  fontSize: '10px',
                                  fontWeight: '500',
                                  whiteSpace: 'nowrap',
                                }}
                              >
                                Extra Charges :{' '}
                                {
                                  productBasedExtraCharges?.find(
                                    (find) => find.ProdId === item.ProdId
                                  )?.TotalAmt
                                }
                              </div>
                            )}
                        </td>
                      </>
                    )}
                    {tableitem.OptionName == 'MRP' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '0px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.MRP}
                      </td>
                    )}
                    {tableitem.OptionName == 'Discount' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          width: '40px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.Type != 'C'
                          ? item.Offer && item.Offer > 0
                            ? item.Offer
                            : '-'
                          : item?.OfferPrice && item?.OfferPrice > 0
                            ? item?.OfferType === 'F'
                              ? `₹${safeRound(item.OfferPrice)}`
                              : `${item.OfferPrice}%`
                            : '-'}
                      </td>
                    )}
                    {tableitem.OptionName == 'Quantity' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '40px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {item?.OrderQty}
                      </td>
                    )}
                    {tableitem.OptionName == 'Rate' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '40px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item);
                          }
                        }}
                      >
                        {allowDecimal
                          ? Number(item?.OrderRate || 0).toFixed(2)
                          : Number(item?.OrderRate || 0)}
                      </td>
                    )}
                    {tableitem.OptionName == 'Amount' && (
                      <td
                        className="Table3-item-price"
                        style={{ width: '60px', fontFamily: 'Poppins' }}
                        onClick={() => {
                          // if (editField) {
                          //   handleEditQuantity(item);
                          // }
                          if (GetCustId) {
                            handleCustomerProductPriceHistory(item);
                          }
                        }}
                      >
                        {allowDecimal
                          ? Number(
                            item?.TotalAmt - (item?.Offer || 0) || 0
                          ).toFixed(2)
                          : Number(item?.TotalAmt - (item?.Offer || 0) || 0)}
                      </td>
                    )}

                    {tableitem.OptionName == 'Delete' && (
                      <td className="Table3-editicon">
                        <AiOutlineClose
                          onClick={() => removeFromCart(item)}
                          style={{ color: '#FF4D4F', cursor: 'pointer' }}
                        />
                      </td>
                    )}
                  </>
                ))}
              </tr>
            ))}

            {OldtableDataDinein?.length > 0 && EditQuantity && (
              <BSBillingEditQuantity
                handleEditQuantityCancel={handleEditQuantityCancel}
                BSBillingEditQuantity={EditQuantity}
                Productdata={Modaldata}
                Index={Index}
                shortKeyMethod={shortKeyMethod}
              />
            )}
          </tbody>
        )}
        {/* TakeWay */}

        {tableDataTakeAway?.length > 0 && (
          <tbody className="table3body">
            {tableDataTakeAway?.map((item, index) => (
              <tr
                key={
                  OldtableDataDinein?.length +
                  OldtableDataTakeAway?.length +
                  index
                }
                className={`${BookingType === 'Dine In' && item?.SalesId
                  ? 'BSBill-Table3-content-Disabled'
                  : 'BSBill-Table3-content'
                  } 
            
               `}
                style={{
                  fontFamily: SelectedFont,

                  backgroundColor:
                    BillOrderPre === 'Y'
                      ? BookingType === 'Dine In' && item?.SalesId
                        ? 'rgb(243, 248, 213)'
                        : BookingType === 'Dine In' &&
                          triggerAnimation &&
                          OldtableDataDinein?.length +
                          OldtableDataTakeAway?.length +
                          index ===
                          0 &&
                          !item?.SalesId &&
                          tableDataTakeAway?.length >= PreviousdataLength
                          ? 'wheat'
                          : BookingType !== 'Dine In' &&
                            triggerAnimation &&
                            OldtableDataDinein?.length +
                            OldtableDataTakeAway?.length +
                            index ===
                            0 &&
                            tableDataTakeAway?.length >= PreviousdataLength &&
                            !HoldOrderDtl &&
                            !UnpaidData
                            ? 'wheat'
                            : (OldtableDataDinein?.length +
                              OldtableDataTakeAway?.length +
                              index) %
                              2 ===
                              0
                              ? 'white'
                              : SelectedBillColor?.['OverallBackgroundColor']
                                ? SelectedBillColor?.['OverallBackgroundColor']
                                : '#d6d6d6'
                      : (OldtableDataDinein?.length +
                        OldtableDataTakeAway?.length +
                        index) %
                        2 ===
                        0
                        ? 'white'
                        : SelectedBillColor?.['OverallBackgroundColor']
                          ? SelectedBillColor?.['OverallBackgroundColor']
                          : '#d6d6d6',
                  background:
                    BookingType === 'Dine In' && item?.SalesId
                      ? 'rgb(243, 248, 213)'
                      : GlobEstBooking === 'ParEst' &&
                        GlobProdwisedata?.includes(
                          item?.InwardDtlId + ' ' + item?.BookingTypeName
                        )
                        ? '#b2d1f7'
                        : (OldtableDataDinein?.length +
                          OldtableDataTakeAway?.length +
                          index) %
                          2 ===
                          0
                          ? 'white'
                          : SelectedBillColor?.['OverallBackgroundColor']
                            ? SelectedBillColor?.['OverallBackgroundColor']
                            : '#d6d6d6',
                  animation:
                    BillOrderPre === 'Y' && !BookingTypeBoth
                      ? triggerAnimation &&
                        OldtableDataDinein?.length +
                        OldtableDataTakeAway?.length +
                        index ===
                        0 &&
                        !item?.SalesId &&
                        tableDataTakeAway?.length >= PreviousdataLength &&
                        !HoldOrderDtl &&
                        !UnpaidData
                        ? 'splashAnimation 0.5s ease-in-out'
                        : 'none'
                      : 'none',
                }}
              >
                {tableOptions?.map((tableitem) => (
                  <>
                    {BookingTypeBoth &&
                      index == 0 &&
                      tableitem.OptionName == 'Sl.No' && (
                        <td
                          rowspan={tableData.length}
                          style={{ backgroundColor: '#CFB59D' }}
                        >
                          <img width="30px" alt="" src={TakeAwayIcon} />
                        </td>
                      )}

                    {tableitem.OptionName == 'Sl.No' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '0px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item, index);
                          }
                        }}
                      >
                        {OldtableDataDinein?.length +
                          OldtableDataTakeAway?.length +
                          index +
                          1}
                      </td>
                    )}
                    {tableitem.OptionName == 'Item' && (
                      <>
                        <td
                          className="Table3-items for-combo"
                          style={{ fontFamily: 'Poppins' }}
                          onClick={() =>
                            item.FullProductIdentifierDtls?.length > 0 ||
                              item.ProductIdentifierDtls?.length > 0
                              ? handleImeiDetails(item)
                              : editField && handleEditQuantity(item, index)
                          }
                        >
                          {item?.Type !== 'OS'
                            ? item.ProdName
                            : item.ServiceName}
                          &nbsp;{' '}
                          {item?.BrandName !== null ? item?.BrandName : ''}
                          {item?.Type != 'C' && (
                            <>
                              <p
                                className="Tbl3-Variant"
                                style={{ fontFamily: 'Poppins' }}
                              >
                                {item?.Type !== 'OS' && (
                                  <>
                                    {!item?.ProdVariantName?.toLowerCase()?.includes(
                                      'variant'
                                    ) && <span>{item?.ProdVariantName} </span>}
                                    {item?.Size}
                                    {item?.SinglePc == 'Y'
                                      ? 'PCS'
                                      : item?.UomName}
                                  </>
                                )}
                              </p>
                              {item?.OfferMessage &&
                                !Array.isArray(item.OfferMessage) && (
                                  <p
                                    className={`offermessageTag ${!isMobile ? 'desktop' : ''}`}
                                  >
                                    {item.OfferMessage?.split('>')?.[0] +
                                      `> ${item?.OrderQty} Eligible Free`}
                                  </p>
                                )}
                            </>
                          )}
                          {item?.Type === 'C' && (
                            <div
                              className="Tbl3-Variant"
                              style={{ fontFamily: 'Poppins' }}
                            >
                              {item.ProdDetail?.map((prod, index) => (
                                <p key={index}>
                                  {prod.ProdName} - {prod.Size} {prod.UomName}
                                </p>
                              ))}
                            </div>
                          )}
                          {productBasedExtraCharges?.find(
                            (find) => find.ProdId === item.ProdId
                          ) !== undefined && (
                              <div
                                style={{
                                  fontSize: '10px',
                                  fontWeight: '500',
                                  whiteSpace: 'nowrap',
                                }}
                              >
                                Extra Charges :{' '}
                                {
                                  productBasedExtraCharges?.find(
                                    (find) => find.ProdId === item.ProdId
                                  )?.TotalAmt
                                }
                              </div>
                            )}
                        </td>
                      </>
                    )}
                    {tableitem.OptionName == 'MRP' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '0px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item, index);
                          }
                        }}
                      >
                        {item?.MRP}
                      </td>
                    )}
                    {tableitem.OptionName == 'Discount' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          width: '40px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item, index);
                          }
                        }}
                      >
                        {item?.Type != 'C'
                          ? item.Offer && item.Offer > 0
                            ? item.Offer
                            : '-'
                          : item?.OfferPrice && item?.OfferPrice > 0
                            ? item?.OfferType === 'F'
                              ? `₹${safeRound(item.OfferPrice)}`
                              : `${item.OfferPrice}%`
                            : '-'}
                      </td>
                    )}

                    {tableitem.OptionName == 'Quantity' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '40px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item, index);
                          }
                        }}
                      >
                        {item?.OrderQty}
                      </td>
                    )}
                    {tableitem.OptionName == 'Rate' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '40px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item, index);
                          }
                        }}
                      >
                        {allowDecimal
                          ? Number(item?.OrderRate || 0).toFixed(2)
                          : Number(item?.OrderRate || 0)}
                      </td>
                    )}
                    {tableitem.OptionName == 'Amount' && (
                      <td
                        className="Table3-item-price"
                        style={{ width: '60px', fontFamily: 'Poppins' }}
                        onClick={() => {
                          // if (editField) {
                          //   handleEditQuantity(item, index);
                          // }
                          if (GetCustId) {
                            handleCustomerProductPriceHistory(item);
                          }
                        }}
                      >
                        {allowDecimal
                          ? Number(
                            item?.TotalAmt - (item?.Offer || 0) || 0
                          ).toFixed(2)
                          : Number(item?.TotalAmt - (item?.Offer || 0) || 0)}
                      </td>
                    )}

                    {tableitem.OptionName == 'Delete' && (
                      <td className="Table3-editicon">
                        <AiOutlineClose
                          onClick={() => removeFromCart(item)}
                          style={{ color: '#FF4D4F', cursor: 'pointer' }}
                        />
                      </td>
                    )}
                  </>
                ))}
              </tr>
            ))}

            {tableDataTakeAway?.length > 0 && EditQuantity && (
              <BSBillingEditQuantity
                handleEditQuantityCancel={handleEditQuantityCancel}
                BSBillingEditQuantity={EditQuantity}
                Productdata={Modaldata}
                Index={Index}
                shortKeyMethod={shortKeyMethod}
              />
            )}
          </tbody>
        )}
        {/* DineIn */}
        {tableDataDinein?.length > 0 && (
          <tbody className="table3body">
            {tableDataDinein?.map((item, index) => (
              <tr
                key={
                  OldtableDataTakeAway?.length +
                  OldtableDataDinein?.length +
                  tableDataTakeAway?.length +
                  index
                }
                className={`${BookingType === 'Dine In' && item?.SalesId
                  ? 'BSBill-Table3-content-Disabled'
                  : 'BSBill-Table3-content'
                  } 
            
               `}
                style={{
                  fontFamily: SelectedFont,

                  backgroundColor:
                    BillOrderPre === 'Y' && !BookingTypeBoth
                      ? BookingType === 'Dine In' &&
                        item?.SalesId &&
                        !BookingTypeBoth
                        ? 'rgb(243, 248, 213)'
                        : BookingType === 'Dine In' &&
                          triggerAnimation &&
                          OldtableDataTakeAway?.length +
                          OldtableDataDinein?.length +
                          tableDataTakeAway?.length +
                          index ===
                          0 &&
                          !item?.SalesId &&
                          tableDataDinein?.length >= PreviousdataLength
                          ? 'wheat'
                          : BookingType !== 'Dine In' &&
                            triggerAnimation &&
                            OldtableDataTakeAway?.length +
                            OldtableDataDinein?.length +
                            tableDataTakeAway?.length +
                            index ===
                            0 &&
                            tableDataDinein?.length >= PreviousdataLength &&
                            !HoldOrderDtl &&
                            !UnpaidData
                            ? 'wheat'
                            : 'inherit'
                      : 'none',
                  background:
                    BookingType === 'Dine In' &&
                      item?.SalesId &&
                      !BookingTypeBoth
                      ? 'rgb(243, 248, 213)'
                      : GlobEstBooking === 'ParEst' &&
                        GlobProdwisedata?.includes(
                          item?.InwardDtlId + ' ' + item?.BookingTypeName
                        )
                        ? '#b2d1f7'
                        : (OldtableDataTakeAway?.length +
                          OldtableDataDinein?.length +
                          tableDataTakeAway?.length +
                          index) %
                          2 ===
                          0
                          ? 'white'
                          : SelectedBillColor?.['OverallBackgroundColor']
                            ? SelectedBillColor?.['OverallBackgroundColor']
                            : '#d6d6d6',
                  animation:
                    BillOrderPre === 'Y' && !BookingTypeBoth
                      ? triggerAnimation &&
                        OldtableDataTakeAway?.length +
                        OldtableDataDinein?.length +
                        tableDataTakeAway?.length +
                        index ===
                        0 &&
                        !item?.SalesId &&
                        tableDataDinein?.length >= PreviousdataLength &&
                        !HoldOrderDtl &&
                        !UnpaidData
                        ? 'splashAnimation 0.5s ease-in-out'
                        : 'none'
                      : 'none',
                }}
              >
                {tableOptions?.map((tableitem) => (
                  <>
                    {BookingTypeBoth &&
                      index == 0 &&
                      tableitem.OptionName == 'Sl.No' && (
                        <td
                          rowspan={tableData.length}
                          style={{ backgroundColor: '#A2C3CD' }}
                        >
                          <img width="30px" alt="" src={dineInIcon} />
                        </td>
                      )}

                    {tableitem.OptionName == 'Sl.No' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '0px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item, index);
                          }
                        }}
                      >
                        {OldtableDataTakeAway?.length +
                          OldtableDataDinein?.length +
                          tableDataTakeAway?.length +
                          index +
                          1}
                      </td>
                    )}
                    {tableitem.OptionName == 'Item' && (
                      <>
                        <td
                          className="Table3-items for-combo"
                          style={{ fontFamily: 'Poppins' }}
                          onClick={() => {
                            if (editField) {
                              handleEditQuantity(item, index);
                            }
                          }}
                        >
                          {item?.ProdName}
                          &nbsp;{' '}
                          {item?.BrandName !== null ? item?.BrandName : ''}
                          {item?.Type != 'C' && (
                            <>
                              <p
                                className="Tbl3-Variant"
                                style={{ fontFamily: 'Poppins' }}
                              >
                                (
                                {!item?.ProdVariantName?.toLowerCase()?.includes(
                                  'variant'
                                ) && <span>{item?.ProdVariantName} </span>}
                                {item?.Size}
                                {item?.SinglePc == 'Y' ? 'PCS' : item?.UomName})
                              </p>
                              {item?.OfferMessage &&
                                !Array.isArray(item.OfferMessage) && (
                                  <p
                                    className={`offermessageTag ${!isMobile ? 'desktop' : ''}`}
                                  >
                                    {item.OfferMessage?.split('>')?.[0] +
                                      `> ${item?.OrderQty} Eligible Free`}
                                  </p>
                                )}
                            </>
                          )}
                          {item?.Type === 'C' && (
                            <div
                              className="Tbl3-Variant"
                              style={{ fontFamily: 'Poppins' }}
                            >
                              {item.ProdDetail?.map((prod, index) => (
                                <p key={index}>
                                  {prod.ProdName} - {prod.Size} {prod.UomName}
                                </p>
                              ))}
                            </div>
                          )}
                          {productBasedExtraCharges?.find(
                            (find) => find.ProdId === item.ProdId
                          ) !== undefined && (
                              <div
                                style={{
                                  fontSize: '10px',
                                  fontWeight: '500',
                                  whiteSpace: 'nowrap',
                                }}
                              >
                                Extra Charges :{' '}
                                {
                                  productBasedExtraCharges?.find(
                                    (find) => find.ProdId === item.ProdId
                                  )?.TotalAmt
                                }
                              </div>
                            )}
                        </td>
                      </>
                    )}
                    {tableitem.OptionName == 'MRP' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '0px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item, index);
                          }
                        }}
                      >
                        {item?.MRP}
                      </td>
                    )}
                    {tableitem.OptionName == 'Discount' && (
                      <td
                        className="Table3-Dis"
                        style={{
                          width: '40px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item, index);
                          }
                        }}
                      >
                        {item?.Type != 'C'
                          ? item.Offer && item.Offer > 0
                            ? item.Offer
                            : '-'
                          : item?.OfferPrice && item?.OfferPrice > 0
                            ? item?.OfferType === 'F'
                              ? `₹${safeRound(item.OfferPrice)}`
                              : `${item.OfferPrice}%`
                            : '-'}
                      </td>
                    )}
                    {tableitem.OptionName == 'Quantity' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '40px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item, index);
                          }
                        }}
                      >
                        {item?.OrderQty}
                      </td>
                    )}
                    {tableitem.OptionName == 'Rate' && (
                      <td
                        className="Table-3_qty"
                        style={{
                          width: '40px',
                          fontFamily: 'Poppins',
                        }}
                        onClick={() => {
                          if (editField) {
                            handleEditQuantity(item, index);
                          }
                        }}
                      >
                        {allowDecimal
                          ? Number(item?.OrderRate || 0).toFixed(2)
                          : Number(item?.OrderRate || 0)}
                      </td>
                    )}
                    {tableitem.OptionName == 'Amount' && (
                      <td
                        className="Table3-item-price"
                        style={{ width: '60px', fontFamily: 'Poppins' }}
                        onClick={() => {
                          // if (editField) {
                          //   handleEditQuantity(item);
                          // }
                          if (GetCustId) {
                            handleCustomerProductPriceHistory(item);
                          }
                        }}
                      >
                        {allowDecimal
                          ? Number(
                            item?.TotalAmt - (item?.Offer || 0) || 0
                          ).toFixed(2)
                          : Number(item?.TotalAmt - (item?.Offer || 0) || 0)}
                      </td>
                    )}

                    {tableitem.OptionName == 'Delete' && (
                      <td className="Table3-editicon">
                        <AiOutlineClose
                          onClick={() => removeFromCart(item)}
                          style={{ color: '#FF4D4F', cursor: 'pointer' }}
                        />
                      </td>
                    )}
                  </>
                ))}
              </tr>
            ))}

            {tableDataDinein?.length > 0 && EditQuantity && (
              <BSBillingEditQuantity
                handleEditQuantityCancel={handleEditQuantityCancel}
                BSBillingEditQuantity={EditQuantity}
                Productdata={Modaldata}
                Index={Index}
                shortKeyMethod={shortKeyMethod}
              />
            )}
          </tbody>
        )}
      </table>
      {OpenEditTotalAmt && (
        <BSEditTotalAmt
          EditTotalOpen={OpenEditTotalAmt}
          EditTotalClose={handleEditTotalAmountCancel}
        />
      )}
      {OpenImeiDetail && (
        <BSImeiDetails
          DeviceDetails={OpenImeiDetail}
          handleDeviceDetailClose={handleImeiDetailClose}
          ProductDetail={Modaldata}
        />
      )}
      {(customerPriceHistoryOpen && GetCustId) &&
        <CustomerPriceHistory
          open={customerPriceHistoryOpen}
          custId={GetCustId}
          setCustomerPriceHistoryOpen={setCustomerPriceHistoryOpen}
          customerProduct={customerProduct}
          setCustomerProduct={setCustomerProduct}
          selectedCustomer={selectedCustomer}
        />
      }
    </div>
  );
};

export default BSBillingTable3;
