import React, { useEffect, useRef, useState, useCallback } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import moment from 'moment';
import { Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { BiBarcodeReader } from 'react-icons/bi';
import { GoTriangleRight } from 'react-icons/go';
import { IoIosSearch } from 'react-icons/io';
import { FiSearch } from 'react-icons/fi';
import defaultimage from '../../../../Images/defaultItemImg.png';
import { Form, AutoComplete } from 'antd';
import { CloseSquareFilled } from '@ant-design/icons';
import '../../../../Styles/BookingScreen/Template/BSLayout7/BSC1Search.scss';
import {
  changeSearchedData,
  ChangeWSProduct,
  ChangeNewQrProduct,
  getProductsearch,
  GlobalOrderCardDetails,
  changeOrderCardDetails,
  GlobalBookingType,
  getPreferenceData,
  GlobalWSProduct,
  GlobalSearchData,
  GlobalNewQrProduct,
  changeHoldOrderDtl,
  changePreviousOrderLength,
  Globalcombofocus,
  GlobalfocusStatusCustMouse,
  GlobalSelCustId,
  GlobalPrintStatus,
  changeCombofocus,
  GlobalCompoPaymentIconStatus,
  GlobalReorderHoldDetails,
  GlobalWeightScalePort,
  GlobalWeightScaleWeight,
  changeothersdata,
  GlobalUnpaidData,
  GlobalCreditFocus,
  GlobalBookingTypeBoth,
  GlobalOrderType,
  GlobalReorderProductDetails,
  FeatureAddon,
  GlobalCompoPreOrderDtlStatus,
  GlobalDropDownStatus,
  GlobalPreOrderSearchStatus,
  GlobalFocusKioskPay,
  GlobalSelOption,
  PreferenceData,
  GlobalFeatAddOnData,
  GlobalSelectedDatas,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
import {
  changepreOrderList,
  GlobalPreOrderList,
  GlobalPreOrderListedit,
  GlobalPreOrderAdditem,
} from '../../../../Features/BookingScreen/PreOrder/PreOrder.js';
import { Messages } from '../../../../Components/Notifications/Messages';
import FormHeader from '../../../PageComponents/FormHeader';
import { DefaultModal } from '../../../../Components/Modal/DefaultModal';
import { Tables } from '../../../../Components/Tables/Table';
import FeaturesFunctionalities from '../BookingFunctionality/FeaturesFunctionalities';
import { gettableData } from '../../../../Features/PreferenceMaster/PreferenceMaster';
import { isMobile } from 'react-device-detect';
import BarcodeScanner from '../UtillComponents/BarcodeScanner.jsx';
import {
  getTemplateData,
  StoredSessionData,
} from '../../../../Features/ThemeChange/ThemeChange.js';
import { v4 as uuidv4 } from 'uuid';
import { GlobalAddCustomerDetails } from '../../../../Features/BookingScreen/Customer/addCustomer.js';

import BSNavBarWeightScale from '../UtillComponents/BSNavBarWeightScale.jsx';

export default function BSC1Search(props) {
  const dispatch = useDispatch();

  const searchPromiseRef = useRef(null);
  const debounceTimerRef = useRef(null);
  const SessionData = useSelector(StoredSessionData);
  const BranchId = SessionData?.BranchId;
  const AppId = SessionData?.AppId;
  const CompId = SessionData?.CompId;
  const formRef = useRef();
  const Globalfocus = useSelector(Globalcombofocus);
  const GlobalPreOrderData = useSelector(GlobalPreOrderList);
  const CartOrderDetails = useSelector(GlobalOrderCardDetails);
  const BookingType = useSelector(GlobalBookingType);
  const WSProductdata = useSelector(GlobalWSProduct);
  const ProductSearch = useSelector(GlobalSearchData);
  const SelectedDatas = useSelector(GlobalSelectedDatas, shallowEqual);
  const NewQrProductData = useSelector(GlobalNewQrProduct);
  const ReportholdData = useSelector(GlobalReorderHoldDetails);
  const WeightScalePort = useSelector(GlobalWeightScalePort);
  const ReorderProductData = useSelector(GlobalReorderProductDetails);
  const WeightScaleWeight = useSelector(GlobalWeightScaleWeight);
  const PreOrderSearchStatus = useSelector(GlobalPreOrderSearchStatus);
  const KioskFocusStatus = useSelector(GlobalFocusKioskPay);
  const FeatureAddonData = useSelector(GlobalFeatAddOnData);

  const preferenceDatas = useSelector(PreferenceData);

  const BSComboData = props?.hasOwnProperty('data') ? props['data'] : null;
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [qtydata, setQtydata] = useState();
  const [modelQty, setModelQty] = useState(false);
  const [modelstock, setModelstock] = useState(false);
  const [ModalVarient, setModalVarient] = useState(false);
  const [QtyIndex, setQtyIndex] = useState(0);
  const [repeatedModel, setRepeatedModel] = useState(false);
  const [VarientIndex, setVarientIndex] = useState(0);
  const [ProductList, setProductList] = useState([]);

  const [addFirst, setAddFirst] = useState(false);
  console.log(addFirst, 'addFirstaddFirst');
  const [SelectedProduct, setSelectedProduct] = useState({});
  const [expModel, setexpModel] = useState(false);
  const [prodexpir, setProdexpir] = useState(false);
  const [expVarModel, setexpVarModel] = useState(false);
  const [expStockModel, setexpStockModel] = useState(false);
  const [Item, setItem] = useState();
  const [VarItem, setVarItem] = useState();
  const [StockItem, setStockItem] = useState();
  const [StockPreferenceDetail, setStockPreferenceDetail] = useState();
  const [QuickAdd, setQuickAdd] = useState(false);
  const inputRef = useRef(null);
  const containerRef = useRef(null);
  // QR code tracking
  const [lastScannedQr, setLastScannedQr] = useState(null);

  const [currentSessionQr, setCurrentSessionQr] = useState(null);
  const focusStatusCustMouse = useSelector(GlobalfocusStatusCustMouse);
  const CompoPaymentIconStatus = useSelector(GlobalCompoPaymentIconStatus);
  const CompoPreOrderDtlStatus = useSelector(GlobalCompoPreOrderDtlStatus);
  const DropDownStatus = useSelector(GlobalDropDownStatus);
  const CustChangeDropDown = useSelector(GlobalSelCustId);
  const printStatus = useSelector(GlobalPrintStatus);
  const [screenWidth, setScreenWidth] = useState(window.innerWidth);
  const [preFocus, setpreFocus] = useState(false);
  const OrderType = useSelector(GlobalOrderType);
  const [autoCompleteVisible, setAutoCompleteVisible] = useState(
    preFocus && screenWidth > 768 && OrderType != 'Failed' ? true : false
  );
  const CreditFocus = useSelector(GlobalCreditFocus);
  const [onePeiceFlow, setOnePeiceFlow] = useState(false);
  const [expQtyModel, setExpQtyModel] = useState(false);
  const [qtyExpData, setQtyExpData] = useState();
  console.log('h');

  const PreOrderAdditem = useSelector(GlobalPreOrderAdditem);
  // const [FeatureAddonData, setFeatureAddonData] = useState([]);
  const [openScanner, setOpenScanner] = useState(false);
  const scannerRef = useRef();
  const updateScreenSize = () => {
    setScreenWidth(window.innerWidth);
  };
  const [ExpiredProduct, setExpiredProduct] = useState();
  console.log(ExpiredProduct, 'ExpiredProduct');

  const isSelectingRef = useRef(false);

  //dhana
  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.shiftKey && event.code === 'KeyS') {
        if (
          document.activeElement.tagName !== 'INPUT' &&
          document.activeElement.tagName !== 'TEXTAREA'
        ) {
          event.preventDefault(); // Stops "S" from being typed
          inputRef?.current?.focus();
        }
      }
    };

    const handleClickOutside = () => {
      inputRef?.current?.blur();
    };

    window.addEventListener('keydown', handleKeyPress);
    window.addEventListener('mousedown', handleClickOutside);

    return () => {
      window.removeEventListener('keydown', handleKeyPress);
      window.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);
  //dhana

  useEffect(() => {
    focusPreferenceData();
  }, []);

  useEffect(() => {
    const first =
      preferenceDatas?.[0]?.['SettingDtlDetails']?.find(
        (item) => item.SettingIdName === 'BillItemsOrder'
      )?.SettingValue === 'Y';
    setAddFirst(first);
  }, [preferenceDatas]);

  function safeRound(amountStr) {
    if (amountStr == null) return '0.00';
    const cleaned = String(amountStr).replace(/[^0-9.-]+/g, '');
    const num = Number(cleaned);
    return isNaN(num) ? '0.00' : num.toFixed(2);
  }
  const focusPreferenceData = async () => {
    const filteredDatas = preferenceDatas?.[0]?.SettingDtlDetails?.filter(
      (item) =>
        item.SettingIdName === 'SearchFocus' && item.SettingValue === 'N'
    );
    console.log('focusPreferenceData', filteredDatas);
    filteredDatas?.length > 0 ? setpreFocus(false) : setpreFocus(true);
  };

  useEffect(() => {
    updateScreenSize();
    window.addEventListener('resize', updateScreenSize);
    return () => {
      window.removeEventListener('resize', updateScreenSize);
    };
  }, []);
  useEffect(() => {
    if (preFocus && screenWidth < 768) {
      setAutoCompleteVisible(true);
    }
  }, [screenWidth]);
  useEffect(() => {
    preFocus && screenWidth > 768 && inputRef?.current?.focus();
  }, [CustChangeDropDown]);
  useEffect(() => {
    if (CreditFocus) {
      setAutoCompleteVisible(false);
    } else {
      preFocus && screenWidth > 768 && setAutoCompleteVisible(true);
    }
  }, [CreditFocus]);
  useEffect(() => {
    if (PreOrderSearchStatus) {
      setAutoCompleteVisible(false);
    } else {
      preFocus && screenWidth > 768 && setAutoCompleteVisible(true);
    }
  }, [PreOrderSearchStatus]);

  useEffect(() => {
    preFocus && screenWidth > 768 && setAutoCompleteVisible(true);
    preFocus && screenWidth > 768 && inputRef?.current?.focus();
  }, [printStatus]);
  // useEffect(() => {
  //     if (QuickAdd) {
  //         setAutoCompleteVisible(false);
  //     } else {
  //         preFocus && screenWidth > 768 && setAutoCompleteVisible(true);
  //     }
  // }, [QuickAdd]);
  useEffect(() => {
    if (
      QuickAdd ||
      CompoPaymentIconStatus ||
      focusStatusCustMouse ||
      modelQty ||
      modelstock ||
      ModalVarient ||
      KioskFocusStatus
    ) {
      setAutoCompleteVisible(false);
    } else {
      preFocus && screenWidth > 768 && setAutoCompleteVisible(true);
      preFocus && screenWidth > 768 && inputRef?.current?.focus();
    }
  }, [
    QuickAdd,
    CompoPaymentIconStatus,
    focusStatusCustMouse,
    modelQty,
    modelstock,
    ModalVarient,
    KioskFocusStatus,
  ]);
  useEffect(() => {
    if (!CompoPreOrderDtlStatus && !DropDownStatus) {
      preFocus && screenWidth > 768 && setAutoCompleteVisible(true);
      preFocus && screenWidth > 768 && inputRef?.current?.focus();
    } else {
      setAutoCompleteVisible(false);
    }
  }, [CompoPreOrderDtlStatus]);

  useEffect(() => {
    preFocus && screenWidth > 768 && inputRef?.current?.focus();
  }, [CartOrderDetails]);
  // useEffect(() => {
  //     if (!CompoPaymentIconStatus) {
  //         preFocus && screenWidth > 768 && setAutoCompleteVisible(true);
  //         // inputRef.current.click();
  //         preFocus && screenWidth > 768 && inputRef?.current?.focus();
  //     } else {
  //         setAutoCompleteVisible(false);
  //     }
  // }, [CompoPaymentIconStatus]);

  // useEffect(() => {
  //     if (focusStatusCustMouse) {
  //         setAutoCompleteVisible(false);
  //     } else {
  //         preFocus && screenWidth > 768 && setAutoCompleteVisible(true);
  //     }
  // }, [focusStatusCustMouse]);

  useEffect(() => {
    setAutoCompleteVisible(Globalfocus ? false : true);
    if (!Globalfocus) {
      preFocus && screenWidth > 768 && inputRef?.current?.focus();
    }
  }, [Globalfocus]);
  useEffect(() => {
    if (!preFocus) {
      setAutoCompleteVisible(false);
    } else {
      setAutoCompleteVisible(true);
    }
  }, [preFocus]);

  useEffect(() => {
    const handleDocumentClick = (event) => {
      if (
        containerRef.current &&
        event.target !== inputRef?.current &&
        !isDescendant(containerRef?.current, event?.target) &&
        // isDescendant(document.documentElement, event.target) &&
        autoCompleteVisible &&
        !Globalfocus &&
        !QuickAdd &&
        screenWidth > 768 &&
        preFocus &&
        !CreditFocus &&
        !CompoPreOrderDtlStatus &&
        !focusStatusCustMouse &&
        !KioskFocusStatus
      ) {
        inputRef?.current?.focus();
      }
    };

    document.addEventListener('click', handleDocumentClick);

    return () => {
      document.removeEventListener('click', handleDocumentClick);
    };
  }, [
    inputRef,
    Globalfocus,
    autoCompleteVisible,
    QuickAdd,
    screenWidth,
    preFocus,
    CreditFocus,
    CompoPreOrderDtlStatus,
    CartOrderDetails,
    KioskFocusStatus,
  ]);

  useEffect(() => {
    if (autoCompleteVisible) {
      dispatch(changeCombofocus(false));
      preFocus && screenWidth > 768 && inputRef?.current?.focus();
    }
  }, [autoCompleteVisible]);

  const isDescendant = (parent, child) => {
    let node = child.parentNode;
    while (node !== null) {
      if (node === parent) {
        return true;
      }
      node = node.parentNode;
    }
    return false;
  };
  const handleFocus = () => {
    preFocus && screenWidth > 768 && setAutoCompleteVisible(true);
  };

  useEffect(() => {
    if (autoCompleteVisible) {
      preFocus && screenWidth > 768 && inputRef?.current?.focus();
    }
  }, [autoCompleteVisible]);

  const OnfocusTrue = () => {
    preFocus && screenWidth > 768 && setAutoCompleteVisible(true);
    preFocus && screenWidth > 768 && inputRef?.current?.focus();
  };

  useEffect(() => {
    getPreferenceStock();
  }, []);

  useEffect(() => {
    if (Object.keys(NewQrProductData)?.length > 0) {
      let addQrProductData = { ...NewQrProductData };
      addQrProductData['OrderRate'] = addQrProductData['SellPrice'];
      addQrProductData['OrderQty'] = addQrProductData['Quantity'];
      addQrProductData['BookingTypeName'] = BookingType;
      AddOrderDetails(addQrProductData);
    }
  }, [NewQrProductData]);
  useEffect(() => {
    if (Object.keys(SelectedProduct)?.length > 0) {
      ProductSelected(SelectedProduct);
    }
  }, [SelectedProduct]);

  const stopScannerFromParent = () => {
    if (scannerRef.current) {
      scannerRef?.current?.stopScanner(); // Call stopScanner from the child component
    }
  };

  const handleQrcode = () => {
    setOpenScanner((prev) => !prev);
    if (!openScanner && scannerRef.current) {
      scannerRef.current.reinitializeCamera(); // Call the function to reinitialize the camera
    }
  };

  const handleQrData = async (value, err) => {
    if (err && err?.error) {
      setMessageData(err?.error);
      setMessageType('error');
    }
    await searchdata(value);
    setOpenScanner(false); // Close the modal after scanning
    stopScannerFromParent();
  };



  // Clear QR tracker function
  const clearQrTracker = () => {
    setLastScannedQr(null);
    setCurrentSessionQr(null);
  };

  const ProductNameOnChange = (data) => {
    if (isSelectingRef.current) {
      isSelectingRef.current = false;
      setProductList([]);
      return; // ⛔ skip search logic
    }
    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }
    debounceTimerRef.current = setTimeout(async () => {
      if (searchPromiseRef.current) {
        searchPromiseRef.current.abort();
      }

      await dispatch(changeSearchedData(data));

      // If same QR as current session, just add quantity
      if (currentSessionQr === data) {
        if (lastScannedQr) {
          const updatedProduct = {
            ...lastScannedQr,
            OrderQty: (lastScannedQr.OrderQty || 1) + 1,
            Quantity: (lastScannedQr.Quantity || 1) + 1
          };
          ProductSelected(updatedProduct);
        }
        return;
      }

      try {
        // 🚀 Call API for new session QR code
        searchPromiseRef.current = dispatch(
          getProductsearch({
            CompId,
            BranchId,
            AppId,
            ProdName: data,
          })
        );

        const ProductListNew = await searchPromiseRef.current.unwrap();

        if (ProductListNew?.statusCode === 1) {
          const ApiSearchData = ProductListNew?.data?.[0];

          if (
            ApiSearchData?.QrBasedSearch === 'Y' ||
            ApiSearchData?.OnePcQRBased === 'Y'
          ) {
            setCurrentSessionQr(data);
            setLastScannedQr(ApiSearchData);

            ProductSelected(ApiSearchData);
            setQuickAdd(false);
          } else if (!ApiSearchData.ProdId && ApiSearchData?.AppId == 0) {
            setQuickAdd(true);
          } else {
            setProductList(ProductListNew?.data);
          }
        } else if (data?.length > 5) {
          setQuickAdd(true);
        } else {
          setProductList(null);
        }
      } catch (error) {
        // ❌ Ignore abort errors
        if (error?.name !== 'AbortError' && error?.name !== 'CanceledError') {
          console.error('Search error:', error);
        }
      }
    }, 400); // 👈 debounce delay
  };

  const getPreferenceStock = async () => {
    const PreferenceStckDtl = preferenceDatas?.[0]?.SettingDtlDetails;
    const StockPreference = PreferenceStckDtl.find(
      (item) => item.SettingIdName === 'StockSelection'
    );

    setStockPreferenceDetail(StockPreference);
    const expiredDate =
      PreferenceStckDtl?.find(
        (item) => item.SettingIdName === 'ExpiredSelection'
      )?.SettingValue === 'Y';
    setExpiredProduct(expiredDate);
  };

  const ProductOnSelect = async (data) => {
    isSelectingRef.current = true;
    let ProdNamedata = ProductList?.find((item) => item.ProdName === data);
    setSelectedProduct(ProdNamedata);
  };
  const ProductSelected = (item) => {
    if (item.OverAllExpStatus == 'Y') {
      setexpModel(true);
      setItem(item);
    } else {
      setQtydata(item);
      let count = item?.ProductDetail?.length;
      if (count > 1) {
        Quantity();
      } else {
        setQtyIndex(0);
        SingleQuantity(item, onePeiceFlow);
        // SingleQuantity(item, item?.OnePcQRBased == 'Y');
      }
    }
  };
  const returnQtyCount = (ProdId, item, orderDetails) => {
    if (onePeiceFlow) {
      let ItemQuantity = item?.ProdVariantDetails?.reduce(
        (accumulator, card) => {
          return accumulator + parseInt(card.OverAllPcs || 0);
        },
        0
      );
      let SelectedProduct = ReorderProductData?.filter(
        (a) => a?.ProdId === ProdId
      );
      let totalSelectedProductQty = SelectedProduct?.reduce(
        (accumulator, card) => {
          return (
            accumulator +
            parseInt(
              card?.StockAvailable === 'Y'
                ? card.SinglePc !== 'Y'
                  ? card.OrderQty * card.NoOfPcs
                  : card.OrderQty
                : 0
            )
          );
        },
        0
      );
      let getCurrentProdDtl = orderDetails?.filter((a) => a?.ProdId === ProdId);
      let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
        return (
          accumulator +
          parseInt(
            card?.StockAvailable === 'Y'
              ? card.SinglePc !== 'Y'
                ? card.OrderQty * card.NoOfPcs
                : card.OrderQty
              : 0
          )
        );
      }, 0);
      let OverallProdQty = totalOrderQty - totalSelectedProductQty;
      if (
        parseInt(ItemQuantity) >
        parseInt(
          Object.keys(ReportholdData)?.length > 0 && totalOrderQty
            ? OverallProdQty
            : getCurrentProdDtl
              ? totalOrderQty
              : 0
        )
      ) {
        let count =
          parseInt(ItemQuantity) -
          parseInt(
            Object.keys(ReportholdData)?.length > 0 && totalOrderQty
              ? OverallProdQty
              : getCurrentProdDtl
                ? totalOrderQty
                : 0
          );

        return parseInt(count);
      } else {
        let count = 0;
        return count;
      }
    } else {
      let ItemQuantity = item?.ProdVariantDetails?.reduce(
        (accumulator, card) => {
          return accumulator + parseInt(card.OverAllQty || 0);
        },
        0
      );
      let SelectedProduct = ReorderProductData?.filter(
        (a) => a?.ProdId === ProdId
      );
      let totalSelectedProductQty = SelectedProduct?.reduce(
        (accumulator, card) => {
          return (
            accumulator +
            parseInt(
              card?.StockAvailable === 'Y'
                ? card.SinglePc !== 'Y'
                  ? card.OrderQty
                  : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
                    ? 0
                    : card.OrderQty % card.NoOfPcs === 0
                      ? Math.floor(card.OrderQty / card.NoOfPcs)
                      : Math.floor(card.OrderQty / card.NoOfPcs) + 1
                : 0
            )
          );
        },
        0
      );
      let getCurrentProdDtl = orderDetails?.filter((a) => a?.ProdId === ProdId);
      let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
        return (
          accumulator +
          parseInt(
            card?.StockAvailable === 'Y'
              ? card.SinglePc !== 'Y'
                ? card.OrderQty
                : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
                  ? 0
                  : card.OrderQty % card.NoOfPcs === 0
                    ? Math.floor(card.OrderQty / card.NoOfPcs)
                    : Math.floor(card.OrderQty / card.NoOfPcs) + 1
              : 0
          )
        );
      }, 0);
      let OverallProdQty = totalOrderQty - totalSelectedProductQty;
      if (
        parseInt(ItemQuantity) >
        parseInt(
          Object.keys(ReportholdData)?.length > 0 && totalOrderQty
            ? OverallProdQty
            : getCurrentProdDtl
              ? totalOrderQty
              : 0
        )
      ) {
        let count =
          parseInt(ItemQuantity) -
          parseInt(
            Object.keys(ReportholdData)?.length > 0 && totalOrderQty
              ? OverallProdQty
              : getCurrentProdDtl
                ? totalOrderQty
                : 0
          );

        return parseInt(count);
      } else {
        let count = 0;
        return count;
      }
    }
  };

  const returnCountStock = (
    ProdId,
    currentQty,
    orderDetails,
    InwardDtlId,
    onepcavailable
  ) => {
    if (onepcavailable === 'Y') {
      let SelectedProduct = ReorderProductData?.filter(
        (a) => a?.ProdId === ProdId && a?.InwardDtlId === InwardDtlId
      );
      let totalSelectedProductQty = SelectedProduct?.reduce(
        (accumulator, card) => {
          return (
            accumulator +
            parseInt(
              card?.StockAvailable === 'Y'
                ? card.SinglePc !== 'Y'
                  ? card.OrderQty * card.NoOfPcs
                  : card.OrderQty
                : 0
            )
          );
        },
        0
      );
      let getCurrentProdDtl = orderDetails?.filter(
        (a) => a?.ProdId === ProdId && a?.InwardDtlId === InwardDtlId
      );
      let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
        return (
          accumulator +
          parseInt(
            card?.StockAvailable === 'Y'
              ? card.SinglePc !== 'Y'
                ? card.OrderQty * card.NoOfPcs
                : card.OrderQty
              : 0
          )
        );
      }, 0);

      let OverallProdQty = totalOrderQty - totalSelectedProductQty;
      if (
        parseInt(currentQty) >
        parseInt(
          Object.keys(ReportholdData)?.length > 0 && totalOrderQty
            ? OverallProdQty
            : getCurrentProdDtl
              ? totalOrderQty
              : 0
        )
      ) {
        let count =
          parseInt(currentQty) -
          parseInt(
            Object.keys(ReportholdData)?.length > 0 && totalOrderQty
              ? OverallProdQty
              : getCurrentProdDtl
                ? totalOrderQty
                : 0
          );
        return parseInt(count);
      } else {
        let count = 0;
        return count;
      }
    } else {
      let SelectedProduct = ReorderProductData?.filter(
        (a) => a?.ProdId === ProdId && a?.InwardDtlId === InwardDtlId
      );
      let totalSelectedProductQty = SelectedProduct?.reduce(
        (accumulator, card) => {
          return (
            accumulator +
            parseInt(
              card?.StockAvailable === 'Y'
                ? card.SinglePc !== 'Y'
                  ? card.OrderQty
                  : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
                    ? 0
                    : card.OrderQty % card.NoOfPcs === 0
                      ? Math.floor(card.OrderQty / card.NoOfPcs)
                      : Math.floor(card.OrderQty / card.NoOfPcs) + 1
                : 0
            )
          );
        },
        0
      );
      let getCurrentProdDtl = orderDetails?.filter(
        (a) => a?.ProdId === ProdId && a?.InwardDtlId === InwardDtlId
      );

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

      let OverallProdQty = totalOrderQty - totalSelectedProductQty;
      if (
        parseInt(currentQty) >
        parseInt(
          Object.keys(ReportholdData)?.length > 0 && totalOrderQty
            ? OverallProdQty
            : getCurrentProdDtl
              ? totalOrderQty
              : 0
        )
      ) {
        let count =
          parseInt(currentQty) -
          parseInt(
            Object.keys(ReportholdData)?.length > 0 && totalOrderQty
              ? OverallProdQty
              : getCurrentProdDtl
                ? totalOrderQty
                : 0
          );
        return parseInt(count);
      } else {
        let count = 0;
        return count;
      }
    }
  };

  const returnVariantStock = (
    ProdId,
    currentQty,
    orderDetails,
    ProdVariantName
  ) => {
    // let ReorderProdetails = BookingType === "Dine In" && !UnpaidData ? ReportholdData?.OrderDtlDetails
    //   : BookingType === "Dine In" && UnpaidData ? ReportholdData?.productDetails
    //     : ReportholdData?.productDetails
    if (onePeiceFlow) {
      let SelectedProduct = ReorderProductData?.filter(
        (a) => a?.ProdId === ProdId && a?.ProdVariantName === ProdVariantName
      );
      let totalSelectedProductQty = SelectedProduct?.reduce(
        (accumulator, card) => {
          return (
            accumulator +
            parseInt(
              card?.StockAvailable === 'Y'
                ? card.SinglePc !== 'Y'
                  ? card.OrderQty * card.NoOfPcs
                  : card.OrderQty
                : 0
            )
          );
        },
        0
      );
      let getCurrentProdDtl = orderDetails?.filter(
        (a) => a?.ProdId === ProdId && a?.ProdVariantName === ProdVariantName
      );
      let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
        return (
          accumulator +
          parseInt(
            card?.StockAvailable === 'Y'
              ? card.SinglePc !== 'Y'
                ? card.OrderQty * card.NoOfPcs
                : card.OrderQty
              : 0
          )
        );
      }, 0);

      if (
        parseInt(currentQty) >
        parseInt(
          Object.keys(ReportholdData)?.length > 0 && totalOrderQty
            ? totalOrderQty - totalSelectedProductQty
            : getCurrentProdDtl
              ? totalOrderQty
              : 0
        )
      ) {
        let count =
          parseInt(currentQty) -
          parseInt(
            Object.keys(ReportholdData)?.length > 0 && totalOrderQty
              ? totalOrderQty - totalSelectedProductQty
              : getCurrentProdDtl
                ? totalOrderQty
                : 0
          );
        return parseInt(count);
      } else {
        let count = 0;
        return count;
      }
    } else {
      let SelectedProduct = ReorderProductData?.filter(
        (a) => a?.ProdId === ProdId && a?.ProdVariantName === ProdVariantName
      );
      let totalSelectedProductQty = SelectedProduct?.reduce(
        (accumulator, card) => {
          return (
            accumulator +
            parseInt(
              card?.StockAvailable === 'Y'
                ? card.SinglePc !== 'Y'
                  ? card.OrderQty
                  : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
                    ? 0
                    : card.OrderQty % card.NoOfPcs === 0
                      ? Math.floor(card.OrderQty / card.NoOfPcs)
                      : Math.floor(card.OrderQty / card.NoOfPcs) + 1
                : 0
            )
          );
        },
        0
      );
      let getCurrentProdDtl = orderDetails?.filter(
        (a) => a?.ProdId === ProdId && a?.ProdVariantName === ProdVariantName
      );
      let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
        return (
          accumulator +
          parseInt(
            card?.StockAvailable === 'Y'
              ? card.SinglePc !== 'Y'
                ? card.OrderQty
                : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
                  ? 0
                  : card.OrderQty % card.NoOfPcs === 0
                    ? Math.floor(card.OrderQty / card.NoOfPcs)
                    : Math.floor(card.OrderQty / card.NoOfPcs) + 1
              : 0
          )
        );
      }, 0);

      if (
        parseInt(currentQty) >
        parseInt(
          Object.keys(ReportholdData)?.length > 0 && totalOrderQty
            ? totalOrderQty - totalSelectedProductQty
            : getCurrentProdDtl
              ? totalOrderQty
              : 0
        )
      ) {
        let count =
          parseInt(currentQty) -
          parseInt(
            Object.keys(ReportholdData)?.length > 0 && totalOrderQty
              ? totalOrderQty - totalSelectedProductQty
              : getCurrentProdDtl
                ? totalOrderQty
                : 0
          );
        return parseInt(count);
      } else {
        let count = 0;
        return count;
      }
    }
  };
  const StockDate = (date) => {
    let dateVal = moment(date, ['YYYY-MM-DDTHH:mm:ss']).format('DD-MM-YYYY');
    return dateVal;
  };

  const varientcolumns = [
    {
      title: 'Variant Name',
      dataIndex: 'VarientName',
      key: 'VarientName',
      align: 'left',
      render: (_, record, index) => (
        <span
          style={
            record.StockCount > 0 ||
              record.StockCount === 'Stock Not Maintained'
              ? { color: '#000', cursor: 'pointer' }
              : { color: '#f49898', cursor: 'not-allowed' }
          }
        >
          {record.VarientName}
        </span>
      ),
      onCell: (record) => {
        return {
          onClick: () => {
            if (
              record.StockCount > 0 ||
              record.StockCount === 'Stock Not Maintained'
            ) {
              Stockfun(record);
            }
          },
        };
      },
    },
    {
      title: 'Stock Count',
      dataIndex: 'StockCount',
      key: 'StockCount',
      align: 'Right',
      render: (_, record, index) => (
        <span
          style={
            record.StockCount > 0 ||
              record.StockCount === 'Stock Not Maintained'
              ? { color: '#000', cursor: 'pointer' }
              : { color: '#f49898', cursor: 'not-allowed' }
          }
        >
          {record.StockCount}
        </span>
      ),
      onCell: (record) => {
        return {
          onClick: () => {
            if (
              record.StockCount > 0 ||
              record.StockCount === 'Stock Not Maintained'
            ) {
              Stockfun(record);
            }
          },
        };
      },
    },
    {
      title: 'Amount',
      dataIndex: 'Amount',
      key: 'Amount',
      align: 'right',
      render: (_, record, index) => (
        <span
          style={
            record.StockCount > 0 ||
              record.StockCount === 'Stock Not Maintained'
              ? { color: '#000', cursor: 'pointer' }
              : { color: '#f49898', cursor: 'not-allowed' }
          }
        >
          {safeRound(record.Amount)}
        </span>
      ),
      onCell: (record) => {
        return {
          onClick: () => {
            if (
              record.StockCount > 0 ||
              record.StockCount === 'Stock Not Maintained'
            ) {
              Stockfun(record);
            }
          },
        };
      },
    },
    // {
    //   title:'Stock Quantity',
    //   dataIndex:'StockCount',
    //   key:'StockCount',
    //   align: 'right',
    //   onCell: (record) => {
    //     return {
    //       onClick: () => {
    //         if (record.StockCount > 0 || record.StockCount==='Stock Not Maintained') {
    //           Stockfun(record);
    //         }
    //       },
    //     };
    // },
    // }
  ];
  const stockcolumns = [
    {
      title: 'Batch No',
      dataIndex: 'Batch No',
      key: 'Batch No',
      align: 'center',
      render: (text, record, index) => (
        <span
          style={
            record.StockCount > 0
              ? { color: '#000', cursor: 'pointer' }
              : { color: '#f49898', cursor: 'not-allowed' }
          }
        >
          {record?.['Batch No']}
        </span>
      ),
      onCell: (record) => {
        return {
          onClick: () => {
            if (record.StockCount > 0) {
              StockSelected(record);
            }
          },
        };
      },
    },
    {
      title: 'Stock Count',
      dataIndex: 'StockCount',
      key: 'StockCount',
      align: 'center',
      render: (_, record, index) => (
        <span
          style={
            record.StockCount > 0
              ? { color: '#000', cursor: 'pointer' }
              : { color: '#f49898', cursor: 'not-allowed' }
          }
        >
          {record.StockCount}
        </span>
      ),
      onCell: (record) => {
        return {
          onClick: () => {
            if (record.StockCount > 0) {
              StockSelected(record);
            }
          },
        };
      },
    },
    {
      title: 'Stock Date',
      dataIndex: 'Stock Date',
      key: 'Stock Date',
      align: 'center',
      render: (_, record, index) => (
        <span
          style={
            record.StockCount > 0
              ? { color: '#000', cursor: 'pointer' }
              : { color: '#f49898', cursor: 'not-allowed' }
          }
        >
          {record?.['Stock Date']}
        </span>
      ),
      onCell: (record) => {
        return {
          onClick: () => {
            if (record.StockCount > 0) {
              StockSelected(record);
            }
          },
        };
      },
    },
    {
      title: 'Exp Date',
      dataIndex: 'ExpDate',
      key: 'ExpDate',
      align: 'center',
      render: (_, record, index) => (
        <span
          style={
            record.StockCount > 0
              ? { color: '#000', cursor: 'pointer' }
              : { color: '#f49898', cursor: 'not-allowed' }
          }
        >
          {record.ExpDate}
        </span>
      ),
      onCell: (record) => {
        return {
          onClick: () => {
            if (record.StockCount > 0) {
              StockSelected(record);
            }
          },
        };
      },
    },
    {
      title: 'Price',
      dataIndex: 'Price',
      key: 'Price',
      align: 'center',
      render: (text) => <span>{safeRound(text)}</span>,
      onCell: (record) => {
        return {
          onClick: () => {
            if (record.StockCount > 0) {
              StockSelected(record);
            }
          },
        };
      },
    },
  ];

  const qtydataSource = [];
  qtydata?.ProductDetail?.map((item, index) => {
    qtydataSource.push({
      key: index,
      Quantity: item?.Size + ' ' + item?.UomName,
      Amount: item?.ProdVariantDetails?.[0]?.StockDetails?.[0]?.SellPrice,
    });
  });
  const varientdataSource = [];
  qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.map((item, index) => {
    varientdataSource.push({
      key: index,
      VarientName: item?.ProdVariantName,
      Amount: onePeiceFlow
        ? item?.StockDetails?.[0]?.OnePcsPrice
        : item?.StockDetails?.[0]?.SellPrice,
      StockCount:
        qtydata?.ProductDetail?.[0]?.StockAvailable === 'Y'
          ? returnVariantStock(
            qtydata?.ProductDetail?.[QtyIndex]?.ProdId,
            item?.OverAllQty,
            CartOrderDetails,
            item?.ProdVariantName
          )
          : 'Stock Not Maintained',
    });
  });

  const stockdataSource = [];
  qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
    VarientIndex
  ]?.StockDetails?.map((item, index) => {
    const expDate = new Date(item?.ExpDate);

    stockdataSource.push({
      key: index,
      'Batch No': item?.BatchRef,
      StockCount: onePeiceFlow
        ? returnCountStock(
          item?.ProdId,
          item?.BalanceQty,
          CartOrderDetails,
          item?.InwardDtlId
        ) * item?.NoOfPcs
        : returnCountStock(
          item?.ProdId,
          item?.BalanceQty,
          CartOrderDetails,
          item?.InwardDtlId
        ),
      'Stock Date': StockDate(item?.InwardDate),
      Price: onePeiceFlow ? item?.OnePcsPrice : item?.SellPrice,
      ExpDate:
        expDate != 'Invalid Date' || null || undefined || ''
          ? StockDate(item?.ExpDate)
          : '-',
    });
  });

  const CloseModal = () => {
    setModelQty(false);
    setRepeatedModel(false);
    setProdexpir(false);
    setOnePeiceFlow(false);
  };
  const CloseModal1 = () => {
    setModelstock(false);
    setRepeatedModel(false);
    setProdexpir(false);
    setOnePeiceFlow(false);
  };
  const CloseVarientModal = () => {
    setModalVarient(false);
    setRepeatedModel(false);
    setProdexpir(false);
    setOnePeiceFlow(false);
  };

  const Quantity = () => {
    setModelQty(true);
  };
  const SingleQuantity = (item, onePcs) => {
    let count = item?.ProductDetail?.[0]?.ProdVariantDetails.length;
    if (count > 1) {
      setModalVarient(true);
    } else {
      setVarientIndex(0);
      SingleStockfun(item, onePcs);
    }
  };

  const SingleStockfun = (item, onePcs) => {
    let count =
      item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
        ?.StockDetails?.length;
    if (StockPreferenceDetail?.SettingValue === 'Y') {
      if (count > 1) {
        setModelstock(true);
      } else {
        let Isincart = CartOrderDetails?.find(
          (cartItem) =>
            cartItem?.ProdId === item?.ProductDetail?.[QtyIndex]?.ProdId &&
            cartItem?.InwardDtlId ===
            item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
              VarientIndex
            ]?.StockDetails?.[0]?.InwardDtlId &&
            cartItem?.OrderRate ===
            item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
              VarientIndex
            ]?.StockDetails?.[0]?.SellPrice &&
            !cartItem?.SalesId
        );

        if (onePcs) {
          let Isincartonepc = CartOrderDetails?.filter(
            (cartItem) =>
              cartItem?.ProdId === item?.ProductDetail?.[QtyIndex]?.ProdId &&
              cartItem?.InwardDtlId ===
              item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
                VarientIndex
              ]?.StockDetails?.[0]?.InwardDtlId &&
              // (cartItem?.OrderRate === item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.StockDetails?.[0]?.SellPrice)
              !cartItem?.SalesId
          );
          let totalOrderQty = Isincartonepc?.reduce((accumulator, card) => {
            return (
              accumulator +
              parseInt(
                card?.StockAvailable === 'Y'
                  ? card.SinglePc !== 'Y'
                    ? card.OrderQty * card.NoOfPcs
                    : card.OrderQty
                  : 0
              )
            );
          }, 0);
          if (Isincartonepc && Isincartonepc?.[0]?.StockAvailable === 'Y') {
            if (Isincartonepc?.[0]?.OverAllPcs > totalOrderQty) {
              dataTransfer(item, 0, 0, 0, onePcs);
            } else {
              dataTransfer(item, 0, 0, 1, onePcs);
            }
          } else {
            dataTransfer(item, 0, 0, 0, onePcs);
          }
        } else {
          if (Isincart && Isincart?.StockAvailable === 'Y') {
            if (Isincart?.BalanceQty > Isincart?.OrderQty) {
              dataTransfer(item, 0, 0, 0, onePcs);
            } else {
              dataTransfer(item, 0, 0, 1, onePcs);
            }
          } else {
            dataTransfer(item, 0, 0, 0, onePcs);
          }
        }
      }
    } else {
      let Isincart = CartOrderDetails?.find(
        (cartItem) =>
          cartItem?.ProdId === item?.ProductDetail?.[QtyIndex]?.ProdId &&
          cartItem?.InwardDtlId ===
          item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[0]?.InwardDtlId &&
          cartItem?.OrderRate ===
          item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[0]?.SellPrice &&
          !cartItem?.SalesId
      );

      if (onePcs) {
        let Isincartonepc = CartOrderDetails?.filter(
          (cartItem) =>
            cartItem?.ProdId === item?.ProductDetail?.[QtyIndex]?.ProdId &&
            cartItem?.InwardDtlId ===
            item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
              VarientIndex
            ]?.StockDetails?.[0]?.InwardDtlId &&
            // (cartItem?.OrderRate === item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.StockDetails?.[0]?.SellPrice)
            !cartItem?.SalesId
        );
        let totalOrderQty = Isincartonepc?.reduce((accumulator, card) => {
          return (
            accumulator +
            parseInt(
              card?.StockAvailable === 'Y'
                ? card.SinglePc !== 'Y'
                  ? card.OrderQty * (card.NoOfPcs ? card.NoOfPcs : 1)
                  : card.OrderQty
                : 0
            )
          );
        }, 0);
        if (Isincartonepc && Isincartonepc?.[0]?.StockAvailable === 'Y') {
          if (Isincartonepc?.[0]?.OverAllPcs > totalOrderQty) {
            dataTransfer(item, 0, 0, 0, onePcs);
          } else {
            dataTransfer(item, 0, 0, 1, onePcs);
          }
        } else {
          dataTransfer(item, 0, 0, 0, onePcs);
        }
      } else {
        if (Isincart && Isincart?.StockAvailable === 'Y') {
          if (Isincart?.BalanceQty > Isincart?.OrderQty) {
            dataTransfer(item, 0, 0, 0, onePcs);
          } else {
            dataTransfer(item, 0, 0, 1, onePcs);
          }
        } else {
          dataTransfer(item, 0, 0, 0, onePcs);
        }
      }
    }
  };

  const Stockfun = (index) => {
    setVarientIndex(index.key);
    const variantDetails =
      qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[index.key] || {};
    const overallExpStatus = variantDetails.OverAllExpStatus;
    const count = variantDetails.StockDetails?.length || 0;

    if (StockPreferenceDetail?.SettingValue === 'Y') {
      if (count > 1) {
        if (
          overallExpStatus === 'N' ||
          (overallExpStatus === 'Y' && prodexpir)
        ) {
          setModalVarient(false);
          setModelstock(true);
          setVarItem(index.key);
          if (overallExpStatus === 'Y' && prodexpir) {
            setRepeatedModel(true);
          }
        } else if (overallExpStatus === 'Y' && ExpiredProduct) {
          setVarItem(index.key);
          setexpVarModel(true);
        }
      } else {
        if (
          overallExpStatus === 'N' ||
          (overallExpStatus === 'Y' && prodexpir)
        ) {
          let Isincart = CartOrderDetails?.find(
            (cartItem) =>
              cartItem?.ProdId === qtydata?.ProductDetail?.[QtyIndex]?.ProdId &&
              cartItem?.InwardDtlId ===
              qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
                index.key
              ]?.StockDetails?.[0]?.InwardDtlId &&
              cartItem?.OrderRate ===
              qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
                index.key
              ]?.StockDetails?.[0]?.SellPrice &&
              !cartItem?.SalesId
          );

          if (onePeiceFlow) {
            let Isincartonepc = CartOrderDetails?.filter(
              (cartItem) =>
                cartItem?.ProdId ===
                qtydata?.ProductDetail?.[QtyIndex]?.ProdId &&
                cartItem?.InwardDtlId ===
                qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
                  VarientIndex
                ]?.StockDetails?.[0]?.InwardDtlId &&
                // (cartItem?.OrderRate === item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.StockDetails?.[0]?.SellPrice)
                !cartItem?.SalesId
            );
            let totalOrderQty = Isincartonepc?.reduce((accumulator, card) => {
              return (
                accumulator +
                parseInt(
                  card?.StockAvailable === 'Y'
                    ? card.SinglePc !== 'Y'
                      ? card.OrderQty * (card.NoOfPcs ? card.NoOfPcs : 1)
                      : card.OrderQty
                    : 0
                )
              );
            }, 0);
            if (Isincartonepc && Isincartonepc?.[0]?.StockAvailable === 'Y') {
              if (Isincartonepc?.[0]?.OverAllPcs > totalOrderQty) {
                dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
              } else {
                dataTransfer(qtydata, QtyIndex, index.key, 1, onePeiceFlow);
              }
            } else {
              dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
            }
          } else {
            if (Isincart && Isincart?.StockAvailable === 'Y') {
              if (Isincart?.BalanceQty > Isincart?.OrderQty) {
                dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
              } else {
                dataTransfer(qtydata, QtyIndex, index.key, 1, onePeiceFlow);
              }
            } else {
              dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
            }
          }

          setModelQty(false);
          setVarItem(index.key);
          if (overallExpStatus === 'Y' && prodexpir) {
            setProdexpir(false);
            setRepeatedModel(true);
          }
        } else if (overallExpStatus === 'Y') {
          setVarItem(index.key);
          if (!ExpiredProduct) {
            expVerFun(index.key);
          } else {
            setexpVarModel(true);
          }
        }
      }
    } else {
      let Isincart = CartOrderDetails?.find(
        (cartItem) =>
          cartItem?.ProdId === qtydata?.ProductDetail?.[QtyIndex]?.ProdId &&
          cartItem?.InwardDtlId ===
          qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[index.key]
            ?.StockDetails?.[0]?.InwardDtlId &&
          cartItem?.OrderRate ===
          qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[index.key]
            ?.StockDetails?.[0]?.SellPrice &&
          !cartItem?.SalesId
      );

      if (onePeiceFlow) {
        let Isincartonepc = CartOrderDetails?.filter(
          (cartItem) =>
            cartItem?.ProdId === qtydata?.ProductDetail?.[QtyIndex]?.ProdId &&
            cartItem?.InwardDtlId ===
            qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
              VarientIndex
            ]?.StockDetails?.[0]?.InwardDtlId &&
            // (cartItem?.OrderRate === item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.StockDetails?.[0]?.SellPrice)
            !cartItem?.SalesId
        );
        let totalOrderQty = Isincartonepc?.reduce((accumulator, card) => {
          return (
            accumulator +
            parseInt(
              card?.StockAvailable === 'Y'
                ? card.SinglePc !== 'Y'
                  ? card.OrderQty * (card.NoOfPcs ? card.NoOfPcs : 1)
                  : card.OrderQty
                : 0
            )
          );
        }, 0);
        if (Isincartonepc && Isincartonepc?.[0]?.StockAvailable === 'Y') {
          if (Isincartonepc?.[0]?.OverAllPcs > totalOrderQty) {
            dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
          } else {
            dataTransfer(qtydata, QtyIndex, index.key, 1, onePeiceFlow);
          }
        } else {
          dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
        }
      } else {
        if (Isincart && Isincart?.StockAvailable === 'Y') {
          if (Isincart?.BalanceQty > Isincart?.OrderQty) {
            dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
          } else {
            dataTransfer(qtydata, QtyIndex, index.key, 1, onePeiceFlow);
          }
        } else {
          dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
        }
      }
      setModelQty(false);
    }
  };
  const VarientFun = (index) => {
    const QtyExpire = index?.ProdVariantDetails?.every(
      (item) => item.OverAllExpStatus === 'Y'
    );

    if (QtyExpire && ExpiredProduct) {
      setExpQtyModel(true);
      setQtyExpData(index);
    } else {
      let selectedProIndex = qtydata?.ProductDetail?.findIndex(
        (item) =>
          item?.ProdId === index?.ProdId &&
          item?.Size === index?.Size &&
          item?.UomName === index?.UomName &&
          item?.Brand === index?.Brand
      );

      setQtyIndex(selectedProIndex);
      let count =
        qtydata?.ProductDetail[selectedProIndex]?.ProdVariantDetails?.length;
      if (count > 1) {
        setModelQty(false);
        setModalVarient(true);
      } else {
        const item = { QtyIndex: selectedProIndex, VarientIndex: 0 };
        singleVarient(item);
        setModelQty(false);
      }
    }
  };
  const singleVarient = (item) => {
    let count =
      qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
        item?.VarientIndex
      ]?.StockDetails?.length;

    if (StockPreferenceDetail?.SettingValue === 'Y') {
      if (count > 1) {
        setModalVarient(false);
        setModelstock(true);
        // setVarientIndex(index.key)
      } else {
        let Isincart = CartOrderDetails?.find(
          (cartItem) =>
            cartItem?.ProdId ===
            qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdId &&
            cartItem?.InwardDtlId ===
            qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
              item?.VarientIndex
            ]?.StockDetails?.[0]?.InwardDtlId &&
            cartItem?.OrderRate ===
            qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
              item?.VarientIndex
            ]?.StockDetails?.[0]?.SellPrice &&
            !cartItem?.SalesId
        );

        if (onePeiceFlow) {
          let Isincartonepc = CartOrderDetails?.filter(
            (cartItem) =>
              cartItem?.ProdId ===
              qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdId &&
              cartItem?.InwardDtlId ===
              qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
                item?.VarientIndexs
              ]?.StockDetails?.[0]?.InwardDtlId &&
              // (cartItem?.OrderRate === item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.StockDetails?.[0]?.SellPrice)
              !cartItem?.SalesId
          );
          let totalOrderQty = Isincartonepc?.reduce((accumulator, card) => {
            return (
              accumulator +
              parseInt(
                card?.StockAvailable === 'Y'
                  ? card.SinglePc !== 'Y'
                    ? card.OrderQty * card.NoOfPcs
                    : card.OrderQty
                  : 0
              )
            );
          }, 0);
          if (Isincartonepc && Isincartonepc?.[0]?.StockAvailable === 'Y') {
            if (Isincartonepc?.[0]?.OverAllPcs > totalOrderQty) {
              dataTransfer(
                qtydata,
                item?.QtyIndex,
                item?.VarientIndex,
                0,
                onePeiceFlow
              );
            } else {
              dataTransfer(
                qtydata,
                item?.QtyIndex,
                item?.VarientIndex,
                1,
                onePeiceFlow
              );
            }
          } else {
            dataTransfer(
              qtydata,
              item?.QtyIndex,
              item?.VarientIndex,
              0,
              onePeiceFlow
            );
          }
        } else {
          if (Isincart && Isincart?.StockAvailable === 'Y') {
            if (Isincart?.BalanceQty > Isincart?.OrderQty) {
              dataTransfer(
                qtydata,
                item?.QtyIndex,
                item?.VarientIndex,
                0,
                onePeiceFlow
              );
            } else {
              dataTransfer(
                qtydata,
                item?.QtyIndex,
                item?.VarientIndex,
                1,
                onePeiceFlow
              );
            }
          } else {
            dataTransfer(
              qtydata,
              item?.QtyIndex,
              item?.VarientIndex,
              0,
              onePeiceFlow
            );
          }
        }
        setModelQty(false);
      }
    } else {
      let Isincart = CartOrderDetails?.find(
        (cartItem) =>
          cartItem?.ProdId ===
          qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdId &&
          cartItem?.InwardDtlId ===
          qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
            item?.VarientIndex
          ]?.StockDetails?.[0]?.InwardDtlId &&
          cartItem?.OrderRate ===
          qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
            item?.VarientIndex
          ]?.StockDetails?.[0]?.SellPrice &&
          !cartItem?.SalesId
      );

      if (onePeiceFlow) {
        let Isincartonepc = CartOrderDetails?.filter(
          (cartItem) =>
            cartItem?.ProdId ===
            qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdId &&
            cartItem?.InwardDtlId ===
            qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
              item?.VarientIndex
            ]?.StockDetails?.[0]?.InwardDtlId &&
            // (cartItem?.OrderRate === item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.StockDetails?.[0]?.SellPrice)
            !cartItem?.SalesId
        );
        let totalOrderQty = Isincartonepc?.reduce((accumulator, card) => {
          return (
            accumulator +
            parseInt(
              card?.StockAvailable === 'Y'
                ? card.SinglePc !== 'Y'
                  ? card.OrderQty * card.NoOfPcs
                  : card.OrderQty
                : 0
            )
          );
        }, 0);
        if (Isincartonepc && Isincartonepc?.[0]?.StockAvailable === 'Y') {
          if (Isincartonepc?.[0]?.OverAllPcs > totalOrderQty) {
            dataTransfer(
              qtydata,
              item?.QtyIndex,
              item?.VarientIndex,
              0,
              onePeiceFlow
            );
          } else {
            dataTransfer(
              qtydata,
              item?.QtyIndex,
              item?.VarientIndex,
              1,
              onePeiceFlow
            );
          }
        } else {
          dataTransfer(
            qtydata,
            item?.QtyIndex,
            item?.VarientIndex,
            0,
            onePeiceFlow
          );
        }
      } else {
        if (Isincart && Isincart?.StockAvailable === 'Y') {
          if (Isincart?.BalanceQty > Isincart?.OrderQty) {
            dataTransfer(
              qtydata,
              item?.QtyIndex,
              item?.VarientIndex,
              0,
              onePeiceFlow
            );
          } else {
            dataTransfer(
              qtydata,
              item?.QtyIndex,
              item?.VarientIndex,
              1,
              onePeiceFlow
            );
          }
        } else {
          dataTransfer(
            qtydata,
            item?.QtyIndex,
            item?.VarientIndex,
            0,
            onePeiceFlow
          );
        }
      }
      setModelQty(false);
    }
  };
  const StockSelected = (item) => {
    const stockDetails =
      qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
        ?.StockDetails?.[item.key] || {};
    const overallExpStatus = stockDetails?.OverAllExpStatus;

    if (overallExpStatus === 'N' || overallExpStatus === 'Y') {
      const firstStockDetails =
        qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[0]
          ?.StockDetails?.[item.key] || {};
      const firstOverallExpStatus = firstStockDetails.OverAllExpStatus;

      if (
        overallExpStatus === 'N' ||
        (firstOverallExpStatus === 'Y' && prodexpir)
      ) {
        dataTransfer(qtydata, QtyIndex, VarientIndex, item.key, onePeiceFlow);
      } else if (overallExpStatus === 'Y' && repeatedModel) {
        dataTransfer(qtydata, QtyIndex, VarientIndex, item.key, onePeiceFlow);
      } else {
        setexpStockModel(true);
        setStockItem(item.key);
      }
    }

    setProdexpir(false);
    setRepeatedModel(false);
  };

  useEffect(() => {
    if (Object.keys(WSProductdata)?.length > 0) {
      AddOrderDetails(WSProductdata);
    }
  }, [WSProductdata]);
  const dataTransfer = (a, QtyIndex, VarientIndex, stockIndex, onePcs) => {
    const isKgsProduct =
      (a?.ProductDetail?.[QtyIndex]?.UomName?.toLowerCase() === 'kgs' ||
        a?.ProductDetail?.[QtyIndex]?.UomName?.toLowerCase() ===
        'kg'?.toLowerCase()) &&
      a?.ProductDetail?.[QtyIndex]?.Size === '1';

    if (
      WeightScalePort === true &&
      isKgsProduct &&
      WeightScaleWeight > 0.005 &&
      WeightScaleWeight !== null
    ) {
      // if (
      //   (a?.ProductDetail?.[QtyIndex]?.UomName?.toLowerCase() ===
      //     'KGS'?.toLowerCase() ||
      //     a?.ProductDetail?.[QtyIndex]?.UomName?.toLowerCase() ===
      //       'KG'?.toLowerCase()) &&
      //   a?.ProductDetail?.[QtyIndex]?.Size === 1
      // ) {
      // if (WeightScaleWeight > 0 && WeightScaleWeight !== null) {
      let TotalOrderRate =
        parseFloat(
          onePcs
            ? (a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.OnePcsPrice /
              1000) *
            (parseFloat(WeightScaleWeight) * 1000)
            : a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.SellPrice / 1000
        ) *
        (parseFloat(WeightScaleWeight) * 1000);
      let data = {
        Type: a?.Type,
        OverallQuantity: a?.OverAllQty,
        ActiveStatus: a?.ProductDetail?.[QtyIndex]?.ActiveStatus,
        AvailableFrom: a?.ProductDetail?.[QtyIndex]?.AvailableFrom,
        AvailableTo: a?.ProductDetail?.[QtyIndex]?.AvailableTo,
        Cess: a?.ProductDetail?.[QtyIndex]?.Cess,
        HSNCode: a?.ProductDetail?.[QtyIndex]?.HSNCode,
        BrandName: a?.ProductDetail?.[QtyIndex]?.BrandName,
        // 'ManufDate': a?.ProductDetail?.[QtyIndex]?.ManufDate,
        OpeningQty: a?.ProductDetail?.[QtyIndex]?.OpeningQty,
        PartNumber: a?.ProductDetail?.[QtyIndex]?.PartNumber,
        ProdId: a?.ProductDetail?.[QtyIndex]?.ProdId,
        ProdLogo: a?.ProductDetail?.[QtyIndex]?.ProdLogo,
        ProdName: a?.ProductDetail?.[QtyIndex]?.ProdName,
        QRCode: a?.ProductDetail?.[QtyIndex]?.QRCode,
        QtyBasedPrice: a?.ProductDetail?.[QtyIndex]?.QtyBasedPrice,
        Rack: a?.ProductDetail?.[QtyIndex]?.Rack,
        Size: parseFloat(WeightScaleWeight),
        StockAvailable: a?.ProductDetail?.[QtyIndex]?.StockAvailable,
        TokenAvailable: a?.ProductDetail?.[QtyIndex]?.TokenAvailable,
        TaxId: a?.ProductDetail?.[QtyIndex]?.TaxId,
        TaxPercentage: a?.ProductDetail?.[QtyIndex]?.TaxPercentage,
        TaxName: a?.ProductDetail?.[QtyIndex]?.TaxIdName,
        UniqueId: a?.ProductDetail?.[QtyIndex]?.UniqueId,
        UomName: onePcs ? 'PCS' : a?.ProductDetail?.[QtyIndex]?.UomName,
        SinglePc: onePcs ? 'Y' : 'N',
        NoOfPcs:
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.NoOfPcs,
        ProdVariantName:
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.ProdVariantName,
        BalanceQty:
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.BalanceQty,
        BatchRef:
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.BatchRef,
        InwardDate:
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.InwardDate,
        InwardDtlId:
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.InwardDtlId,
        ExpDate:
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.ExpDate,
        InwardId:
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.InwardId,
        MRP: onePcs
          ? a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.OnePcsPrice
          : a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.MRP,
        OrderRate: parseFloat(TotalOrderRate).toFixed(2),
        SellingPrice: parseFloat(TotalOrderRate).toFixed(2),
        SuppId:
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.SuppId,
        SuppName:
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.SuppName,
        OverAllPcs:
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.OverAllPcs,
        Offer:
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.OfferPrice,
        BookingTypeName: BookingType,
        CounterName: a?.CounterName,
      };
      setModelQty(false);
      setModalVarient(false);
      setModelstock(false);
      setQtyIndex(0);
      setVarientIndex(0);
      setVarItem(0);
      (setItem(), setStockItem());
      dispatch(changeSearchedData(''));
      AddOrderDetails(data);
      // dispatch(changeWeightScaleWeight(null));
      setRepeatedModel(false);
      setProdexpir(false);
      setOnePeiceFlow(false);
      // } else {
      //   setMessageType('error');
      //   setMessageData('Please Connect WeightScale');
      // }
      // } else {
      //   setMessageType('error');
      //   setMessageData('Please Select 1Kg Product');
      // }
    } else {
      if (
        (onePcs &&
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.NoOfPcs > 0 &&
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.OnePcsPrice > 0) ||
        !onePcs ||
        (a?.ProductDetail?.[QtyIndex]?.StockAvailable !== 'Y' &&
          onePcs &&
          a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.OnePcsPrice > 0)
      ) {
        let data = {
          Type: a?.Type,
          OverallQuantity: a?.OverAllQty,
          ActiveStatus: a?.ProductDetail?.[QtyIndex]?.ActiveStatus,
          AvailableFrom: a?.ProductDetail?.[QtyIndex]?.AvailableFrom,
          AvailableTo: a?.ProductDetail?.[QtyIndex]?.AvailableTo,
          Cess: a?.ProductDetail?.[QtyIndex]?.Cess,
          HSNCode: a?.ProductDetail?.[QtyIndex]?.HSNCode,
          BrandName: a?.ProductDetail?.[QtyIndex]?.BrandName,
          // 'ManufDate': a?.ProductDetail?.[QtyIndex]?.ManufDate,
          OpeningQty: a?.ProductDetail?.[QtyIndex]?.OpeningQty,
          PartNumber: a?.ProductDetail?.[QtyIndex]?.PartNumber,
          ProdId: a?.ProductDetail?.[QtyIndex]?.ProdId,
          ProdLogo: a?.ProductDetail?.[QtyIndex]?.ProdLogo,
          ProdName: a?.ProductDetail?.[QtyIndex]?.ProdName,
          QRCode: a?.ProductDetail?.[QtyIndex]?.QRCode,
          QtyBasedPrice: a?.ProductDetail?.[QtyIndex]?.QtyBasedPrice,
          Rack: a?.ProductDetail?.[QtyIndex]?.Rack,
          Size: onePcs ? '1' : a?.ProductDetail?.[QtyIndex]?.Size,
          StockAvailable: a?.ProductDetail?.[QtyIndex]?.StockAvailable,
          TokenAvailable: a?.ProductDetail?.[QtyIndex]?.TokenAvailable,
          TaxId: a?.ProductDetail?.[QtyIndex]?.TaxId,
          TaxPercentage: a?.ProductDetail?.[QtyIndex]?.TaxPercentage,
          TaxName: a?.ProductDetail?.[QtyIndex]?.TaxIdName,
          UniqueId: a?.ProductDetail?.[QtyIndex]?.UniqueId,
          UomName: a?.ProductDetail?.[QtyIndex]?.UomName,
          SinglePc: onePcs ? 'Y' : 'N',
          NoOfPcs:
            a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.NoOfPcs,
          ProdVariantName:
            a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.ProdVariantName,
          BalanceQty:
            a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.BalanceQty,
          BatchRef:
            a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.BatchRef,
          InwardDate:
            a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.InwardDate,
          InwardDtlId:
            a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.InwardDtlId,
          ExpDate:
            a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.ExpDate,
          InwardId:
            a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.InwardId,
          MRP: onePcs
            ? a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.OnePcsPrice
            : a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.MRP,
          OrderRate: onePcs
            ? a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.OnePcsPrice
            : a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.SellPrice,
          SellingPrice: onePcs
            ? a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.OnePcsPrice
            : a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.SellPrice,
          SuppId:
            a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.SuppId,
          OverAllPcs:
            a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.OverAllPcs,
          SuppName:
            a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.SuppName,
          Offer:
            a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
              ?.StockDetails?.[stockIndex]?.OfferPrice,
          BookingTypeName: BookingType,
          CounterName: a?.CounterName,
        };

        setModelQty(false);
        setModalVarient(false);
        setModelstock(false);
        setQtyIndex(0);
        setVarientIndex(0);
        setVarItem(0);
        (setItem(), setStockItem());
        dispatch(changeSearchedData(''));
        AddOrderDetails(data);
        setOnePeiceFlow(false);
      } else {
        setMessageType('error');
        setMessageData(
          'Please add No.of pieces Inside the box in Product master'
        );
        formRef.current.resetFields(['ItemName']);
        setSelectedProduct({});
        setModelQty(false);
        setModalVarient(false);
        setModelstock(false);
        setQtyIndex(0);
        setVarientIndex(0);
        setVarItem(0);
        (setItem(), setStockItem());
        dispatch(changeSearchedData(''));
        setOnePeiceFlow(false);
      }
    }
  };
  const CalculateOverallQty = (item, filterItem) => {
    console.log(item, filterItem, 'totalQuantitytotalQuantity');
    const totalQuantity = filterItem?.reduce((accumulator, card) => {
      if (card?.StockAvailable !== 'Y') return accumulator;
      if (item?.SinglePc !== 'Y') {
        let quantity = 0;

        if (card?.SinglePc !== 'Y') {
          quantity = card.OrderQty;
        } else {
          if (card?.OverAllPcs % card?.NoOfPcs >= card?.OrderQty) {
            quantity = 0;
          } else {
            quantity = Math.ceil(card?.OrderQty / card?.NoOfPcs);
          }
        }
        return accumulator + parseInt(quantity);
      } else {
        let quantity = 0;

        if (card?.SinglePc !== 'Y') {
          quantity = card?.OrderQty * card?.NoOfPcs;
        } else {
          quantity = card?.OrderQty;
        }
        return accumulator + parseInt(quantity);
      }
    }, 0);
    console.log(
      item?.OverAllPcs,
      item?.BalanceQty,
      totalQuantity,
      'totalQuantity'
    );
    if (!item) return 0;
    return (
      (item?.SinglePc === 'Y' ? item?.OverAllPcs : item?.BalanceQty) -
      totalQuantity
    );
  };
  const AddOrderDetails = async (item) => {
    dispatch(changeHoldOrderDtl(false));
    dispatch(changePreviousOrderLength(CartOrderDetails?.length));
    const OtherOrderDatas = CartOrderDetails?.filter(
      (cartItem) =>
        !(
          cartItem?.ProdId === item?.ProdId &&
          cartItem?.InwardDtlId === item?.InwardDtlId &&
          cartItem?.OrderRate === item?.OrderRate &&
          cartItem?.BookingTypeName === item?.BookingTypeName
        ) && !cartItem?.SalesId
    );
    const OtherOrderDatawithsales = CartOrderDetails?.filter(
      (cartItem) => cartItem?.SalesId
    );
    const OtherorderDataforNormal = CartOrderDetails?.filter(
      (cartItem) =>
        !(
          cartItem?.ProdId === item?.ProdId &&
          cartItem?.InwardDtlId === item?.InwardDtlId &&
          cartItem?.OrderRate === item?.OrderRate &&
          cartItem?.BookingTypeName === item?.BookingTypeName &&
          !cartItem?.SalesId
        )
    );
    const isItemInCart = CartOrderDetails?.find(
      (cartItem) =>
        cartItem?.ProdId === item?.ProdId &&
        cartItem?.InwardDtlId === item?.InwardDtlId &&
        cartItem?.OrderRate === item?.OrderRate &&
        cartItem?.BookingTypeName === item?.BookingTypeName &&
        !cartItem?.SalesId
    ); // check if the item is already in the cart
    const isItemInCartfilter = CartOrderDetails?.filter(
      (cartItem) =>
        cartItem?.ProdId === item?.ProdId &&
        cartItem?.InwardDtlId === item?.InwardDtlId &&
        !(
          cartItem?.OrderRate === item?.OrderRate &&
          cartItem?.BookingTypeName === item?.BookingTypeName
        ) &&
        !cartItem?.SalesId
    ); // check if the item is already in the cart
    console.log(
      isItemInCartfilter,
      isItemInCart,
      'isItemInCartfilterisItemInCartfilter'
    );
    const isItemNotInDine = CartOrderDetails?.find(
      (cartItem) =>
        cartItem?.ProdId === item?.ProdId &&
        cartItem?.InwardDtlId === item?.InwardDtlId &&
        cartItem?.OrderRate === item?.OrderRate &&
        cartItem?.BookingTypeName === item?.BookingTypeName &&
        !cartItem?.SalesId
    ); // check if the item is already in the cart
    const isItemInCartHold = CartOrderDetails?.find(
      (cartItem) =>
        cartItem?.ProdId === item?.ProdId &&
        cartItem?.InwardDtlId === item?.InwardDtlId &&
        cartItem?.OrderRate === item?.OrderRate &&
        cartItem?.BookingTypeName === item?.BookingTypeName
    ); // check if the item is already in the cart
    const isItemInCartHoldfilter = CartOrderDetails?.filter(
      (cartItem) =>
        cartItem?.ProdId === item?.ProdId &&
        cartItem?.InwardDtlId === item?.InwardDtlId &&
        !(
          cartItem?.OrderRate === item?.OrderRate &&
          cartItem?.BookingTypeName === item?.BookingTypeName
        )
    ); // check if the item is already in the cart
    const holddataproduct = ReorderProductData?.filter(
      (cartItem) =>
        cartItem?.ProdId === item?.ProdId &&
        cartItem?.InwardDtlId === item?.InwardDtlId
    );
    let totalSelectedProductQty = holddataproduct?.reduce(
      (accumulator, card) => {
        return (
          accumulator +
          parseInt(
            card?.StockAvailable === 'Y'
              ? item?.SinglePc === 'Y'
                ? card.SinglePc !== 'Y'
                  ? card.OrderQty * card.NoOfPcs
                  : card.OrderQty
                : card.SinglePc !== 'Y'
                  ? card.OrderQty
                  : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
                    ? 0
                    : card.OrderQty % card.NoOfPcs === 0
                      ? Math.floor(card.OrderQty / card.NoOfPcs)
                      : Math.floor(card.OrderQty / card.NoOfPcs) + 1
              : 0
          )
        );
      },
      0
    );

    let OverallQuantityhold =
      CalculateOverallQty(isItemInCartHold, isItemInCartHoldfilter) +
      totalSelectedProductQty;
    console.log(
      CalculateOverallQty(isItemInCart, isItemInCartfilter),
      isItemInCart,
      totalSelectedProductQty,
      OverallQuantityhold,
      'calculate'
    );
    const OtherorderDataforNormalWithoutSalesId = CartOrderDetails?.filter(
      (cartItem) =>
        !(
          cartItem?.ProdId === item?.ProdId &&
          cartItem?.InwardDtlId === item?.InwardDtlId &&
          cartItem?.OrderRate === item?.OrderRate &&
          cartItem?.BookingTypeName === item?.BookingTypeName
        )
    );

    if (
      isItemInCart &&
      BookingType != 'Dine In' &&
      OrderType != 'Hold' &&
      OrderType != 'PreOrder'
    ) {
      if (
        (CalculateOverallQty(isItemInCart, isItemInCartfilter) >
          isItemInCart?.OrderQty &&
          isItemInCart?.StockAvailable === 'Y') ||
        isItemInCart?.StockAvailable !== 'Y'
      ) {
        const UpdatedCartItem =
        // if the item is already in the cart, increase the quantity of the item
        {
          ...isItemInCart,
          OrderQty: isItemInCart?.OrderQty + 1,
          TotalAmt: (isItemInCart?.OrderQty + 1) * isItemInCart?.OrderRate,
          TaxAmt: (
            ((isItemInCart?.OrderQty + 1) *
              isItemInCart?.OrderRate *
              isItemInCart?.TaxPercentage) /
            (100 + isItemInCart?.TaxPercentage)
          ).toFixed(2),
          WithoutTaxRate:
            (isItemInCart?.OrderQty + 1) * isItemInCart?.OrderRate -
            (
              ((isItemInCart?.OrderQty + 1) *
                isItemInCart?.OrderRate *
                isItemInCart?.TaxPercentage) /
              (100 + isItemInCart?.TaxPercentage)
            ).toFixed(2),
        };
        const UpdatedData = addFirst
          ? [UpdatedCartItem, ...OtherorderDataforNormal]
          : [...OtherorderDataforNormal, UpdatedCartItem];

        // if (OfferCheckedInSetup) {
        //   await applyOffer(UpdatedData);
        // } else {
        dispatch(changeOrderCardDetails(UpdatedData));
        // }
      } else {
        setMessageType('error');
        setMessageData('Stock Not Available');
        formRef.current.resetFields(['ItemName']);
        setSelectedProduct({});
      }
    } else if (isItemInCartHold && OrderType === 'Hold') {
      if (
        (OverallQuantityhold > isItemInCartHold?.OrderQty &&
          isItemInCartHold?.StockAvailable === 'Y') ||
        isItemInCartHold?.StockAvailable !== 'Y'
      ) {
        const UpdatedCartItem = {
          ...isItemInCartHold,
          OrderQty: isItemInCartHold?.OrderQty + 1,
          TotalAmt:
            (isItemInCartHold?.OrderQty + 1) * isItemInCartHold?.OrderRate,
          TaxAmt: (
            ((isItemInCartHold?.OrderQty + 1) *
              isItemInCartHold?.OrderRate *
              isItemInCartHold?.TaxPercentage) /
            (100 + isItemInCartHold?.TaxPercentage)
          ).toFixed(2),
          WithoutTaxRate:
            (isItemInCartHold?.OrderQty + 1) * isItemInCartHold?.OrderRate -
            (
              ((isItemInCartHold?.OrderQty + 1) *
                isItemInCartHold?.OrderRate *
                isItemInCartHold?.TaxPercentage) /
              (100 + isItemInCartHold?.TaxPercentage)
            ).toFixed(2),
        };
        // otherwise, return the cart item

        const UpdatedData = addFirst
          ? [UpdatedCartItem, ...OtherorderDataforNormalWithoutSalesId]
          : [...OtherorderDataforNormalWithoutSalesId, UpdatedCartItem];

        // if (OfferCheckedInSetup) {
        //   await applyOffer(UpdatedData);
        // } else {
        dispatch(changeOrderCardDetails(UpdatedData));
        // }
      } else {
        setMessageType('error');
        setMessageData('Stock Not Available');
        formRef.current.resetFields(['ItemName']);
        setSelectedProduct({});
      }
    } else if (
      isItemNotInDine &&
      BookingType == 'Dine In' &&
      OrderType != 'Hold'
    ) {
      if (
        (CalculateOverallQty(isItemInCart, isItemInCartfilter) >
          isItemNotInDine?.OrderQty &&
          isItemNotInDine?.StockAvailable === 'Y') ||
        isItemNotInDine?.StockAvailable !== 'Y'
      ) {
        const UpdatedCartItem = {
          ...isItemNotInDine,
          OrderQty: isItemNotInDine?.OrderQty + 1,
          TotalAmt:
            (isItemNotInDine?.OrderQty + 1) * isItemNotInDine?.OrderRate,
          TaxAmt: (
            ((isItemNotInDine?.OrderQty + 1) *
              isItemNotInDine?.OrderRate *
              isItemNotInDine?.TaxPercentage) /
            (100 + isItemNotInDine?.TaxPercentage)
          ).toFixed(2),
          WithoutTaxRate:
            (isItemNotInDine?.OrderQty + 1) * isItemNotInDine?.OrderRate -
            (
              ((isItemNotInDine?.OrderQty + 1) *
                isItemNotInDine?.OrderRate *
                isItemNotInDine?.TaxPercentage) /
              (100 + isItemNotInDine?.TaxPercentage)
            ).toFixed(2),
        };
        // otherwise, return the cart item

        const UpdatedData = addFirst
          ? [UpdatedCartItem, ...OtherOrderDatas, ...OtherOrderDatawithsales]
          : [...OtherOrderDatas, ...OtherOrderDatawithsales, UpdatedCartItem];

        // if (OfferCheckedInSetup) {
        //   await applyOffer(UpdatedData);
        // } else {
        dispatch(changeOrderCardDetails(UpdatedData));
        // }
      } else {
        setMessageType('error');
        setMessageData('Stock Not Available');
        formRef.current.resetFields(['ItemName']);
        setSelectedProduct({});
      }
    } else if (BookingType == 'PreOrder') {
      if (PreOrderAdditem == 'AddItems') {
        // GlobalPreOrderData
        let Duplicate = GlobalPreOrderData?.some(
          (e) =>
            e?.InwardDtlId == item.InwardDtlId && e?.SinglePc === item?.SinglePc
        );
        if (Duplicate) {
          setMessageData(' you have already Select The Product');
          setMessageType('warning');
        } else {
          await dispatch(
            changepreOrderList([
              ...(Array.isArray(GlobalPreOrderData) ? GlobalPreOrderData : []),
              {
                ...item,
                OrderQty: 1,
                TotalAmt: item?.OrderRate,
                TaxAmt: (
                  (item?.OrderRate * item?.TaxPercentage) /
                  (100 + item?.TaxPercentage)
                ).toFixed(2),
                WithoutTaxRate: (
                  item?.OrderRate -
                  (item?.OrderRate * item?.TaxPercentage) /
                  (100 + item?.TaxPercentage)
                ).toFixed(2),
              },
            ])
          );
        }
      } else {
        setMessageData(' you have got to Choose  Add item');
        setMessageType('warning');
      }
    } else {
      if (item?.OtherProduct === 'Others') {
        const UpdatedData = addFirst
          ? [
            {
              ...item,
              TotalAmt: item?.OrderQty * item?.OrderRate,
              TaxAmt: (
                (item?.OrderQty * item?.OrderRate * item?.TaxPercentage) /
                (100 + item?.TaxPercentage)
              ).toFixed(2),
              WithoutTaxRate: (
                item?.OrderQty * item?.OrderRate -
                (item?.OrderQty * item?.OrderRate * item?.TaxPercentage) /
                (100 + item?.TaxPercentage)
              ).toFixed(2),
              localId: uuidv4(),
            },
            ...CartOrderDetails,
          ]
          : [
            ...CartOrderDetails,
            {
              ...item,
              TotalAmt: item?.OrderQty * item?.OrderRate,
              TaxAmt: (
                (item?.OrderQty * item?.OrderRate * item?.TaxPercentage) /
                (100 + item?.TaxPercentage)
              ).toFixed(2),
              WithoutTaxRate: (
                item?.OrderQty * item?.OrderRate -
                (item?.OrderQty * item?.OrderRate * item?.TaxPercentage) /
                (100 + item?.TaxPercentage)
              ).toFixed(2),
              localId: uuidv4(),
            },
          ]; // if the item is not in the cart, add the item to the cart
        // if (OfferCheckedInSetup && preferenceOffer) {
        //   const withoutComboOffer_CardDetail = UpdatedData?.filter(
        //     (item) => item.Type !== 'C'
        //   );
        //   if (
        //     OrderOfferStatus ||
        //     (withoutComboOffer_CardDetail?.length > 0 && CustDetails)
        //   ) {
        //     await newapplyOffer(item, UpdatedData);
        //   }
        //   await applyOffer(UpdatedData);
        // } else {
        dispatch(changeOrderCardDetails(UpdatedData));
        // }
      } else {
        if (
          (item?.StockAvailable === 'Y' &&
            CalculateOverallQty(item, isItemInCartfilter) > 0) ||
          item?.StockAvailable === 'N'
        ) {
          const UpdatedData = addFirst
            ? [
              {
                ...item,
                OrderQty: 1,
                TotalAmt: item?.OrderRate,
                TaxAmt: (
                  (item?.OrderRate * item?.TaxPercentage) /
                  (100 + item?.TaxPercentage)
                ).toFixed(2),
                WithoutTaxRate: (
                  item?.OrderRate -
                  (item?.OrderRate * item?.TaxPercentage) /
                  (100 + item?.TaxPercentage)
                ).toFixed(2),
                localId: uuidv4(),
              },
              ...CartOrderDetails,
            ]
            : [
              ...CartOrderDetails,
              {
                ...item,
                OrderQty: 1,
                TotalAmt: item?.OrderRate,
                TaxAmt: (
                  (item?.OrderRate * item?.TaxPercentage) /
                  (100 + item?.TaxPercentage)
                ).toFixed(2),
                WithoutTaxRate: (
                  item?.OrderRate -
                  (item?.OrderRate * item?.TaxPercentage) /
                  (100 + item?.TaxPercentage)
                ).toFixed(2),
                localId: uuidv4(),
              },
            ]; // if the item is not in the cart, add the item to the cart
          // if (OfferCheckedInSetup && preferenceOffer) {
          //   await applyOffer(UpdatedData);
          // } else {
          dispatch(changeOrderCardDetails(UpdatedData));
          // }
        } else {
          setMessageType('error');
          setMessageData('Stock Not Available');
          formRef.current.resetFields(['ItemName']);
          setSelectedProduct({});
        } // if the item is not in the cart, add the item to the cart
      }
    }
    dispatch(changeothersdata({}));
    dispatch(ChangeNewQrProduct({}));

    formRef.current.resetFields(['ItemName']);
    setSelectedProduct({});
    dispatch(ChangeWSProduct({}));
  };
  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const handleQuickCancel = async () => {
    setQuickAdd(false);
    dispatch(changeSearchedData([]));
    formRef.current.resetFields(['ItemName']);
  };
  const expFun = (item) => {
    setProdexpir(true);
    setQtydata(item);
    let count = item?.ProductDetail?.length;
    if (count > 1) {
      Quantity();
    } else {
      SingleQuantity(item, onePeiceFlow);
    }
    setexpModel(false);
  };

  const expQtyFun = (index) => {
    const selectedProIndex = qtydata?.ProductDetail?.findIndex(
      (item) =>
        item?.ProdId === index?.ProdId &&
        item?.Size === index?.Size &&
        item?.UomName === index?.UomName &&
        item?.Brand === index?.Brand
    );

    if (selectedProIndex !== -1) {
      const count =
        qtydata?.ProductDetail[selectedProIndex]?.ProdVariantDetails?.length ||
        0;

      if (count > 1) {
        setModelQty(false);
        setModalVarient(true);
      } else {
        const item = { QtyIndex: selectedProIndex, VarientIndex: 0 };
        singleVarient(item);
        setModelQty(false);
      }
    }

    setQtyIndex(selectedProIndex);
    setRepeatedModel(true);
    setExpQtyModel(false);
  };

  const expVerFun = (item) => {
    let count =
      qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[item]
        ?.StockDetails?.length;
    if (count > 1) {
      setRepeatedModel(true);
      setModalVarient(false);
      setModelstock(true);
    } else {
      setRepeatedModel(true);
      dataTransfer(qtydata, QtyIndex, item, 0, onePeiceFlow);
      setModelQty(false);
    }
    setexpVarModel(false);
  };

  const expStockFun = (item) => {
    dataTransfer(qtydata, QtyIndex, VarientIndex, item, onePeiceFlow);
    setexpStockModel(false);
  };
  let brandMapping = {};
  // Group product details by Brand ID
  qtydata?.ProductDetail?.forEach((item) => {
    const brandId = item?.BrandName;
    if (!brandMapping[brandId]) {
      brandMapping[brandId] = [];
    }
    brandMapping[brandId].push(item);
  });
  const BrandCheckresult = qtydata?.ProductDetail?.every((product) => {
    return product.BrandName === null || product.BrandName === undefined;
  });
  const getMaxBrandWidth = () => {
    let maxBrandDataLength = 0;

    // Iterate through each brand and find the maximum length of the specified key
    Object.values(brandMapping).forEach((brand) => {
      const keyDataLength = brand.length;
      if (keyDataLength > maxBrandDataLength) {
        maxBrandDataLength = keyDataLength;
      }
    });

    // Set your width logic here based on the maxBrandDataLength
    const maxWidth = maxBrandDataLength >= 5 ? 750 : 'max-content';

    return maxWidth;
  };

  // Example usage for checking the length of 'ProdVariantDetails'
  const widthBasedOnProdVariantDetails = getMaxBrandWidth();

  return (
    <>
      <div
        className="BSC1Search-container"
        ref={containerRef}
        onFocus={handleFocus}
      >
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <div
          className="BSC1Search-div1"
          style={{ pointerEvents: OrderType === 'Failed' ? 'none' : 'auto' }}
          onClick={() => OnfocusTrue()}
        >
          <Form ref={formRef}>
            <Form.Item name="ItemName">
              <AutoComplete
                options={
                  Array.isArray(ProductList) &&
                  ProductList?.map((option) => ({
                    value: option.ProdName,
                    label: (
                      <div style={{ display: 'flex' }}>
                        <div
                          style={{
                            display: 'flex',
                            justifyContent: 'space-between',
                            width: '100%',
                          }}
                          onClick={() => {
                            setOnePeiceFlow(false);
                          }}
                        >
                          {option.ProdName}
                        </div>
                        <div>
                          {option.ProductDetail?.filter(
                            (item) => item.OnePcsAvailable == 'Y'
                          ).length !== 0 && (
                              <GoTriangleRight
                                style={{
                                  fontSize: '25px',
                                }}
                                onClick={() => {
                                  setOnePeiceFlow(true);
                                }}
                              />
                            )}
                        </div>
                      </div>
                    ),
                  }))
                }
                className="Search-auto-field"
                ref={inputRef}
                onChange={ProductNameOnChange}
                onSelect={ProductOnSelect}
                placeholder="Product Name (SHIFT + S)"
                allowClear={{
                  clearIcon: <CloseSquareFilled />,
                }}
                autoFocus={autoCompleteVisible}
                onFocus={handleFocus}
              />
            </Form.Item>
          </Form>
          {isMobile && screenWidth <= 768 && (
            <BiBarcodeReader
              className="BSC1Search-barcodeicon"
              onClick={() => handleQrcode()}
            // onClick={() => OnfocusTrue()}
            />
          )}

          <FiSearch
            className="BSC1Search-searchicon"
          // onClick={() => OnfocusTrue()}
          />
        </div>
        {ProductSearch?.length > 5 && QuickAdd && (
          <div>
            <FeaturesFunctionalities
              handleQuickAddCancel={handleQuickCancel}
              QuickAdd={QuickAdd}
              ProductSearch={true}
              ProductSearchType={'C'}
              cardData={SelectedDatas}
            />
          </div>
        )}
        {BSComboData == 'Combo1' &&
          FeatureAddonData?.FeatureDtls?.find(
            (item) => item?.FeatureAddonName?.toLowerCase() === 'weight scale'
          ) && <BSNavBarWeightScale Combo="combolayout" />}
      </div>
      <Modal
        title={
          <div style={{ display: 'flex', gap: '1rem', flexDirection: 'row' }}>
            <ExclamationCircleOutlined
              style={{ color: 'rgb(231 176 12)', fontSize: '30px' }}
            />
            <h4>Product Expires</h4>
          </div>
        }
        open={expModel}
        onOk={() => expFun(Item)}
        onCancel={() => setexpModel(false)}
        okText="Submit"
        cancelText="Don't Submit"
      ></Modal>
      <Modal
        title={
          <div style={{ display: 'flex', gap: '1rem', flexDirection: 'row' }}>
            <ExclamationCircleOutlined
              style={{ color: 'rgb(231 176 12)', fontSize: '30px' }}
            />
            <h3>Quantity Expires</h3>
          </div>
        }
        open={expQtyModel}
        onOk={() => expQtyFun(qtyExpData)}
        onCancel={() => {
          (setRepeatedModel(false), setProdexpir(false), setExpQtyModel(false));
        }}
        okText="Submit"
        cancelText="Don't Submit"
        maskTransitionName=""
        transitionName=""
      ></Modal>
      <Modal
        title={
          <div style={{ display: 'flex', gap: '1rem', flexDirection: 'row' }}>
            <ExclamationCircleOutlined
              style={{ color: 'rgb(231 176 12)', fontSize: '30px' }}
            />
            <h3>Variant Expires</h3>
          </div>
        }
        open={expVarModel}
        onOk={() => expVerFun(VarItem)}
        onCancel={() => {
          (setexpVarModel(false), setRepeatedModel(false), setProdexpir(false));
        }}
        okText="Submit"
        cancelText="Don't Submit"
      ></Modal>
      <Modal
        title={
          <div style={{ display: 'flex', gap: '1rem', flexDirection: 'row' }}>
            <ExclamationCircleOutlined
              style={{ color: 'rgb(231 176 12)', fontSize: '30px' }}
            />
            <h3>Stock Expires</h3>
          </div>
        }
        open={expStockModel}
        onOk={() => expStockFun(StockItem)}
        onCancel={() => {
          (setexpStockModel(false),
            setRepeatedModel(false),
            setProdexpir(false));
        }}
        okText="Submit"
        cancelText="Don't Submit"
      ></Modal>
      <DefaultModal
        title={
          <div className="EditQuantity-title">
            <FormHeader title={'Item Quantity'} />
          </div>
        }
        open={modelQty}
        width={widthBasedOnProdVariantDetails}
        footer={null}
        children={
          <div>
            <div className="EditQuantity-heading">
              <div className="EditQuantity-headingname">
                <p className="EditQuantity-itemname">Item Name:</p>
              </div>
              <div
                className="EditQuantity-headingproductname"
                style={{ marginLeft: '1rem' }}
              >
                <p className="EditQuantity-productname">{qtydata?.ProdName}</p>
              </div>
            </div>
            <div
              className={
                BrandCheckresult ? 'Card-modal-table' : 'Brand-Card-modal-table'
              }
            >
              {Object.keys(brandMapping)?.map((brandId) => (
                <div key={brandId} className="Brand-Card">
                  <div className="Brandname">
                    <h4>
                      {' '}
                      {brandId !== 'null' && brandId !== 'undefined'
                        ? brandId
                        : ''}
                    </h4>
                  </div>

                  <div className="BrandDetail">
                    {brandMapping[brandId]?.map((item, index) => (
                      <div key={index}>
                        <div
                          className={
                            returnQtyCount(
                              item?.ProdId,
                              item,
                              CartOrderDetails
                            ) > 0 || item?.StockAvailable !== 'Y'
                              ? 'ItemQtyCard'
                              : 'ItemQtyCard-disabled'
                          }
                          onClick={() => VarientFun(item)}
                        >
                          <div className="ItemQtyImgCard">
                            <img
                              src={
                                item?.ProdLogo &&
                                  item?.ProdLogo != null &&
                                  item?.ProdLogo != undefined
                                  ? item?.ProdLogo
                                  : defaultimage
                              }
                              width={'80px'}
                              height={'70px'}
                              alt={`Product ${index}`}
                            />
                          </div>

                          <div className="qtyDetail">
                            <p className="qtyUomName">
                              {item?.Size + ' ' + item?.UomName}
                            </p>
                            {returnQtyCount(
                              item?.ProdId,
                              item,
                              CartOrderDetails
                            ) > 0 || item?.StockAvailable !== 'Y' ? (
                              <p className="qtyprice">
                                <sup style={{ fontFamily: 'Gilroy' }}>₹</sup>
                                &nbsp;
                                {
                                  item?.ProdVariantDetails?.[0]
                                    ?.StockDetails?.[0]?.SellPrice
                                }
                              </p>
                            ) : (
                              ''
                            )}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                  {brandId !== 'null' && brandId !== 'undefined' ? (
                    <hr></hr>
                  ) : (
                    ''
                  )}
                </div>
              ))}

              {Object.keys(brandMapping).length === 0 && (
                <p>No product details available</p>
              )}
            </div>
          </div>
        }
        handleCancel={CloseModal}
      />
      <DefaultModal
        title={
          <div className="EditQuantity-title">
            <FormHeader title={'Item Stock'} />
          </div>
        }
        open={modelstock}
        // width={500}
        footer={null}
        children={
          <div>
            <div
              className="EditQuantity-heading"
              style={{
                display: 'flex',
                flexDirection: 'column',
                marginBottom: '3rem',
                alignItems: 'start',
              }}
            >
              <div style={{ display: 'flex' }}>
                <div className="EditQuantity-headingname">
                  <p className="EditQuantity-itemname">Item Name:</p>
                </div>
                <div
                  className="EditQuantity-headingproductname"
                  style={{ marginLeft: '1rem' }}
                >
                  <p className="EditQuantity-productname">
                    {qtydata?.ProdName}
                  </p>
                </div>
              </div>
              <div style={{ display: 'flex' }}>
                <div className="EditQuantity-headingname">
                  <p className="EditQuantity-itemname">Item Quantity:</p>
                </div>
                <div
                  className="EditQuantity-headingproductname"
                  style={{ marginLeft: '1rem' }}
                >
                  <p className="EditQuantity-productname">
                    {qtydata?.ProductDetail?.[QtyIndex]?.Size}{' '}
                    {onePeiceFlow
                      ? 'PCS'
                      : qtydata?.ProductDetail?.[QtyIndex]?.UomName}
                  </p>
                </div>
              </div>
            </div>
            <div className="Re-Print-table">
              <Tables columns={stockcolumns} data={stockdataSource} />
            </div>
          </div>
        }
        handleCancel={CloseModal1}
      />
      <DefaultModal
        title={
          <div className="EditQuantity-title">
            <FormHeader title={'Item Varients'} />
          </div>
        }
        open={ModalVarient}
        width={500}
        footer={null}
        children={
          <div>
            <div
              className="EditQuantity-heading"
              style={{
                display: 'flex',
                flexDirection: 'column',
                marginBottom: '3rem',
                alignItems: 'start',
              }}
            >
              <div style={{ display: 'flex' }}>
                <div className="EditQuantity-headingname">
                  <p className="EditQuantity-itemname">Item Name:</p>
                </div>
                <div
                  className="EditQuantity-headingproductname"
                  style={{ marginLeft: '1rem' }}
                >
                  <p className="EditQuantity-productname">
                    {qtydata?.ProdName}
                  </p>
                </div>
              </div>
              <div style={{ display: 'flex' }}>
                <div className="EditQuantity-headingname">
                  <p className="EditQuantity-itemname">Item Quantity:</p>
                </div>
                <div
                  className="EditQuantity-headingproductname"
                  style={{ marginLeft: '1rem' }}
                >
                  <p className="EditQuantity-productname">
                    {qtydata?.ProductDetail?.[QtyIndex]?.Size}{' '}
                    {onePeiceFlow
                      ? 'PCS'
                      : qtydata?.ProductDetail?.[QtyIndex]?.UomName}
                  </p>
                </div>
              </div>
            </div>
            <div className="Card-modal-table">
              <Tables columns={varientcolumns} data={varientdataSource} />
            </div>
          </div>
        }
        handleCancel={CloseVarientModal}
      />
      {isMobile && screenWidth <= 768 && (
        <DefaultModal
          title="Barcode Reader"
          width={800}
          open={openScanner}
          footer={false}
          handleCancel={handleQrData} // Close modal on cancel
        >
          {openScanner && (
            <BarcodeScanner
              ref={scannerRef}
              openScanner={openScanner}
              setOpenScanner={setOpenScanner}
              handleQrData={handleQrData}
              type="Search"
            />
          )}
        </DefaultModal>
      )}
    </>
  );
}
