import React, { useEffect, useRef, useState, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { AiFillHome } from 'react-icons/ai';
import { MenuOutlined } from '@ant-design/icons';
import { Popover, Badge, Tooltip, Button, Popconfirm } from 'antd';
import {
  getEditFavItems,
  PreferenceData,
  getPreferenceData,
  GlobalCustId,
  GlobalOrderCardDetails,
  GlobalBookingType,
  GlobalBookingTypeBoth,
  FeatureAddon,
  changeCombosearch,
  GlobalCombosearch,
  Comboget,
  changeEstimateBooking,
  changeSelectedOption,
  changeSelectedCustId,
  changeCustomerID,
  changealldata,
  GlobalOrderType,
  GlobalEstimateBooking,
  GlobalOrderStatus,
  Changedragging,
  Globaldragging,
  changeBtoBQuickProductTransfer,
  GlobalBtoBQuickProductTransfer,
  changeOrderCardDetails,
  GlobalFeatAddOnData,
  GlobalOtherSevices,
  changeOtherServices,
  GlobalComboRedirectionToDefaultLayoutForParking,
  changeComboRedirectionToDefaultLayoutForParking,
  GlobalCommonPaymentOptions,
  GlobalSelCustId,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
import BSNavBarSearch from '../UtillComponents/BSNavBarSearch';
import BSNavBarPrinter from '../UtillComponents/BSNavBarPrinter';
import BSNavBarHand from '../UtillComponents/BSNavBarHand';
import BSNavBarTable from '../UtillComponents/BSNavBarTable';
import BSNavBarHandbag from '../UtillComponents/BSNavBarHandbag';
import BSNavBarOffer from '../UtillComponents/BSNavBarOffer/BSNavBarOffer.jsx';
import BSNavBarAddons from '../UtillComponents/BSNavBarAddons';
import BSNavBarAddUser from '../UtillComponents/BSNavBarAddUser';
import BSNavBarQuickAdd from '../UtillComponents/BSNavBarQuickAdd';
import BSNavBarWeightScale from '../UtillComponents/BSNavBarWeightScale';
import BSNavBarFavItems from '../UtillComponents/BSNavBarFavItems';
import BSNavBarPreOrder from '../../Components/UtillComponents/BSNavBarPreOrder.jsx';
import BSMembership from '../UtillComponents/BSMembership.jsx';
import '../../../../Styles/BookingScreen/Components/BSNavbar/BSNavbar2.scss';
import { clearSession, sessionStore } from '../../../../Services/Others';
import FeaturesFunctionalities from '../BookingFunctionality/FeaturesFunctionalities.jsx';
import BSCustomerSelect from '../UtillComponents/BSSelectCustomer.jsx';
import PozoUserIcon from '../UtillComponents/Pozo retail icons/PozoUserIcon.jsx';
import {
  ApplicationPreferences,
  GenerateLogout,
  GlobalCompBranchData,
  getCompBranchData,
} from '../../../../Features/BrachLogin/BranchLogin.js';
import BSPrinterSetting from '../UtillComponents/BSPrinterSetting.jsx';
import BSNavBarEstimate from '../UtillComponents/BSNavBarEst.jsx';
import BSNavBarComboSearch from '../UtillComponents/BSNavBarComboSearch.jsx';
import { setCustomerDisplayWindow } from '../../../../Features/customerDisplayWindow/customerDisplayWindow';
import {
  GlobalPreOrderPendingCount,
  PreOrderGet,
  changePreOrderPendingCount,
  changepreOrder,
  changePreOrderAdditem,
  changepreOrderList,
} from '../../../../Features/BookingScreen/PreOrder/PreOrder.js';
import { getCustomerDisplayWindow } from '../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
import PozoAddCustomerIcon from '../UtillComponents/Pozo retail icons/PozoAddCustomerIcon.jsx';
import PaymentFailedSales from '../../../Payment/PaymentFailedDetails/PaymentFailedSales.jsx';
import PozoComboProductIcon from '../UtillComponents/Pozo retail icons/PozoComboProductIcon.jsx';
import CustomerDisplayicon from '../UtillComponents/Pozo retail icons/PozoCustomerDisplayicon.jsx';
import PozoPaymentFailesIcon from '../UtillComponents/Pozo retail icons/PozoFailedPaymentsIcon.jsx';
import TooltipWrapper from '../../../../Components/Tooltip/Tooltip';
import { Global_OfferStatus } from '../../../../Features/Offer/Offer.js';
import { IoMdClose } from 'react-icons/io';
import { isMobile } from 'react-device-detect';
import {
  getPrintSelectionComponentData,
  getTemplate,
  getTemplateData,
  StoredSessionData,
} from '../../../../Features/ThemeChange/ThemeChange.js';
import PozoPreOrderIcon from '../UtillComponents/Pozo retail icons/PozoPreOrderIcon.jsx';
import { GlobalBookingStatus } from '../../../../Features/Payment/PaymentReceivedRetail/PaymentReceivedRetail.js';
import { getEmpAccess } from '../../../../Features/AppPage/CenterPage.js';
import { useAuth } from '../../../../AuthContext.jsx';
import { TfiHandDrag } from 'react-icons/tfi';
import BSNavBarDragItems from '../UtillComponents/BSNavBarDragItems.jsx';
import { PiSignOutLight } from 'react-icons/pi';
import {
  getUserProfile,
  userDataByUserId,
} from '../../../../Features/UserAccount/userData.js';
import { FaUserLarge } from 'react-icons/fa6';
import { BiSolidPhoneCall } from 'react-icons/bi';
import PozoSwapIcon from '../UtillComponents/Pozo retail icons/PozoSwapIcon.jsx';
import { CgSearchLoading } from 'react-icons/cg';
import UserRelieveManager from '../../Template/RealivingUser.jsx';
import { FaParking } from 'react-icons/fa';
import BSNavBarUserInfo from './BSNavBarUserInfo';
import { OtherServicesCardlistdata } from '../../../../Features/OtherServices/OtherServices.js';
import BSNavBarWholeSale from '../UtillComponents/BSNavBarWholeSale.jsx';
import BSMobilePrintSettings from '../UtillComponents/BSMobilePrintSettings.jsx';
import BSScanTemplate from '../UtillComponents/BSScanTemplate.jsx';
import VerfiedProducts from './verfiedProduct/VerfiedProducts';
import BranchName from '../../Template/BranchName.jsx';
import MultipleSearch from '../UtillComponents/MultipleSearch.jsx';
import { DefaultModal } from '../../../../Components/Modal/DefaultModal.jsx';
const subDirectory = import.meta.env.ENV_BASE_URL;
const commonUrl = import.meta.env.ENV_COMMON_BASE_URL;

const BSNavbar2 = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [Navmenu, setNavmenu] = useState(false);
  const [isAccOpen, setAccIsOpen] = useState(false);
  const [addcustomer, setAddCustomer] = useState(false);
  const [hold, setHold] = useState(false);
  // const [ComboDropDown, setComboDropDown] = useState();
  const { action, selectedProducts } = useSelector(
    GlobalBtoBQuickProductTransfer
  );
  const preOrderPendingCount = useSelector(GlobalPreOrderPendingCount);
  const FeatureAddonData = useSelector(GlobalFeatAddOnData);

  // const [FeatureAddonData, setFeatureAddonData] = useState([]);
  const [paymentfeataddon, setpaymentfeataddon] = useState(false);
  const CompBranchData = useSelector(GlobalCompBranchData);
  const appPreferences = useSelector(ApplicationPreferences);
  const commonModulePreference = appPreferences?.find(
    (preference) => preference?.PreferredCatName === 'Common Module'
  )?.PreferenceCatDetails;
  const sportsAppPreference = commonModulePreference?.find(
    (preference) =>
      preference?.PreferredSubCatName === 'SportsApp' &&
      preference?.PreferredStatus === 'Y'
  );
  const bookingTypePreference = appPreferences?.find(
    (preference) => preference?.PreferredCatName === 'Booking Type'
  )?.PreferenceCatDetails;
  const dinePreference = bookingTypePreference?.find(
    (type) =>
      type?.PreferredSubCatName?.toLowerCase() === 'dine in' &&
      type?.PreferredStatus === 'Y'
  );
  const takeAwayPreference = bookingTypePreference?.find(
    (type) =>
      type?.PreferredSubCatName?.toLowerCase() === 'take away' &&
      type?.PreferredStatus === 'Y'
  );

  const OtherServicesglobal = useSelector(GlobalOtherSevices);
  const comboRedirectionToDefaultLayoutForParking = useSelector(
    GlobalComboRedirectionToDefaultLayoutForParking
  );

  const [OpenFailData, SetOpenFailData] = useState(false);
  const tableData = useSelector(GlobalOrderStatus);
  const SessionData = useSelector(StoredSessionData);
  const AppId = SessionData?.AppId;
  const CompId = SessionData?.CompId;
  const BranchId = SessionData?.BranchId;
  const UserId = SessionData?.UserId;
  const UserType = SessionData?.UserType;
  const SettingDataSelector = useSelector(PreferenceData);
  const BookingType = useSelector(GlobalBookingType);
  const BookingTypeBoth = useSelector(GlobalBookingTypeBoth);
  const GlobaluseOptions = useSelector(GlobalCommonPaymentOptions);
  const SelCustId = useSelector(GlobalSelCustId);
  const Estimation = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
    (item) => item.SettingIdName === 'Estimation'
  );
  const SalesMode = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
    (item) => item.SettingIdName === 'Sales Mode'
  );
  const ScanLayoutScreen = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
    (item) => item.SettingIdName === 'ScanLayout'
  );
  const Comboglobal = useSelector(GlobalCombosearch);
  const OrderType = useSelector(GlobalOrderType);
  const GlobEstBooking = useSelector(GlobalEstimateBooking);
  const OrderOfferStatus = useSelector(Global_OfferStatus);
  const BSLayout1Data = useSelector(getTemplateData);
  const BookingStatus = useSelector(GlobalBookingStatus);
  const CheckBookingStatus =
    BookingStatus?.find((item) => item.ScreenType === 'Booking')
      ?.ScreenStatus ?? 'Open';
  const navbarOptions = BSLayout1Data?.BookingNavbar?.[1];
  const PreferenceDatas = useSelector(PreferenceData);
  const userProfileData = useSelector(userDataByUserId);
  const [preOrderOpen, setPreOrderOpen] = useState(false);
  const [preOrderhiseandShow, setpreOrderhiseandShow] = useState(false);
  const [open, setOpen] = useState(false);
  const [empData, setEmpData] = useState();
  const [addnewAccess, setaddnewAccess] = useState(true);
  const { SadminuserAccess } = useAuth();
  const [OtherServiceStatus, setOtherServiceStatus] = useState(false);
  const [isHoldEnable, setisisHoldEnable] = useState(false);
  const [multiple, setMultiple] = useState(false);
  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Sales'
  );
  const divRef = useRef(null);

  const Isdragging = useSelector(Globaldragging);

  const handleClickOutside = (event) => {
    if (divRef.current && !divRef.current.contains(event.target)) {
      setAccIsOpen(false);
    }
  };
  const VerifyTheProducts = PreferenceDatas?.[0]?.SettingDtlDetails?.find(
    (item) =>
      item.SettingIdName === 'VerifyProduct' && item?.SettingValue === 'Y'
  );
  useEffect(() => {
    handleOtherData();
    BadgePendingApi();
    // if (UserType === "Employee") {
    //   fetchApi()
    // }
    document.addEventListener('click', handleClickOutside, true);
    return () => {
      document.removeEventListener('click', handleClickOutside, true);
    };
  }, []);
  useEffect(() => {
    getPaymentOptionFeature();
  }, [GlobaluseOptions, SelCustId]);
  const getPaymentOptionFeature = async () => {
    const filterSalesPayment = GlobaluseOptions?.filter(
      (item) => item?.FlowName?.toLowerCase() === 'sales'
    );

    let filterPayCounter = filterSalesPayment?.[0]?.OptionDetails?.filter(
      (item) => item?.OptionName?.toLowerCase() === 'pay at the counter'
    );

    // If customer NOT selected → remove credit mode
    if (!SelCustId) {
      filterPayCounter = filterPayCounter?.map((option) => ({
        ...option,
        ModeDetails: option?.ModeDetails?.filter(
          (mode) => mode?.ModeName?.toLowerCase() !== 'credit'
        ),
      }));
    }

    setisisHoldEnable(filterPayCounter?.[0]?.ModeDetails?.length > 0);
  };
  useEffect(() => {
    fetchEditFavItems();
    dispatch(
      getPreferenceData({ CompId: CompId, AppId: AppId, BranchId: BranchId })
    );
    fetchBranchData();
    dispatch(getUserProfile({ UserId: UserId, ActiveStatus: 'A' })).unwrap();
  }, [CompId, AppId, BranchId, UserType, UserId]);

  // useEffect(() => {
  //   if (BranchId) {
  //     Combodata();
  //   }
  // }, [BranchId, AppId, CompId]);

  useEffect(() => {
    if (
      UserType !== 'Super Admin' &&
      UserType !== 'Super Admin User' &&
      UserId
    ) {
      getFeatureAddonData();
    }
  }, [FeatureAddonData]);
  useEffect(() => {
    let hasAccess = false;

    if (UserType === 'Admin' || UserType === 'Super Admin') {
      hasAccess = true;
    } else if (UserType === 'Employee') {
      hasAccess = empData?.AddAccess === 'Y';
    } else if (UserType === 'Super Admin User') {
      hasAccess = SAAccessCommonMaster?.AddAccess === 'Y';
    }

    setaddnewAccess(!hasAccess);
  }, [empData, SAAccessCommonMaster, UserType]);
  const fetchApi = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      EmpId: UserId,
    };
    let response = await dispatch(getEmpAccess(data)).unwrap();
    let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter(
      (item) => item.ConfigName === 'Sales'
    );
    setEmpData(datas?.[0]);
  };
  const fetchEditFavItems = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
    };
    await dispatch(getEditFavItems(data)).unwrap();
  };
  const fetchBranchData = async () => {
    if (UserType === 'Super Admin' || UserType === 'Super Admin User') {
      await dispatch(
        getCompBranchData({ CompId: CompId, AppId: AppId })
      ).unwrap();
    } else if (UserType === 'Admin' || UserType === 'Admin User') {
      await dispatch(
        getCompBranchData({ AppId: AppId, UserId: UserId, CompId: CompId })
      ).unwrap();
    }
  };

  const handleOtherData = async (e) => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
    };
    let response = await dispatch(OtherServicesCardlistdata(data)).unwrap();
    if (response?.data?.statusCode === 1) {
      setOtherServiceStatus(true);
    } else {
      setOtherServiceStatus(false);
    }
  };
  const getFeatureAddonData = async () => {
    // let featureAddon = await dispatch(
    //   FeatureAddon({ AppId: AppId, UserId: UserId })
    // ).unwrap();
    // if (featureAddon?.data?.statusCode === 1) {
    //   setFeatureAddonData(featureAddon?.data?.data?.[0]?.FeatAddonHdr?.[0]);
    const hasPaymentFeatures = FeatureAddonData?.FeatureDtls.some(
      (item) =>
        item.FeatureAddonName === 'Payment Gateway' ||
        item.FeatureAddonName === 'Payment Device'
    );
    setpaymentfeataddon(hasPaymentFeatures);
    // } else {
    //   setFeatureAddonData([]);
    // }
  };

  // const openPreOrder = async () => {
  const openPreOrder = async (e) => {
    if (e == 'small-screen') {
      setPreOrderOpen(true);
      if (!preOrderhiseandShow) {
        setpreOrderhiseandShow(true);
      } else {
        setpreOrderhiseandShow(false);
      }

      // setpreOrderhiseandShow(!preOrderhiseandShow)
    } else {
      setPreOrderOpen((prevState) => !prevState);
      if (preOrderOpen) {
        const customerDisplayWindow = getCustomerDisplayWindow();
        if (customerDisplayWindow && !customerDisplayWindow.closed) {
          const updatedRemovedData = {
            userData: [],
            ExtraCharges: [],
            paymentMethod: 'Cash',
            type: 'remove',
            keyValue: 'customer',
          };
          customerDisplayWindow.postMessage(updatedRemovedData, '*');
        } else {
          console.error(
            'Customer display window is not available or has been closed.'
          );
        }
        await dispatch(changepreOrder(false));
        await dispatch(changeEstimateBooking('Sales'));
        await dispatch(changePreOrderAdditem('AddDetails'));
        await dispatch(changealldata(null));
        await dispatch(changepreOrderList(null));
        await dispatch(changeCustomerID(null));
        await dispatch(changeSelectedCustId(null));
        await dispatch(changeSelectedOption(null));
      }
    }
  };

  const BadgePendingApi = async () => {
    let Data = {
      compId: CompId,
      branchId: BranchId,
      appId: AppId,
      deliveryStatus: 'P',
    };
    let PendingResponse = await dispatch(PreOrderGet(Data)).unwrap();
    if (PendingResponse?.data?.statusCode === 1) {
      await dispatch(
        changePreOrderPendingCount(PendingResponse?.data?.data?.length)
      );
    }
  };
  const NavmenuOpenClose = () => {
    setNavmenu(!Navmenu);
  };

  const UserAcc = useCallback(() => {
    setAccIsOpen((prev) => !prev);
  }, []);

  const BacktoLogin = () => {
    clearSession('BranchId');
    navigate(`${subDirectory}app-page/branch-login`);
  };

  // const Logout = () => {
  //   closeCustomerDisplayWindow()
  //   clearSession()
  //   window.location.replace(commonUrl);

  // }
  //mohan
  const Logout = async () => {
    const status = 'N'; // replace with your actual status
    const res = await dispatch(GenerateLogout({ UserId, status })).unwrap();
    if (res?.data?.statusCode === 1) {
      clearSession();
      await sessionStore('Mode', 'Logout');
      window.location.replace(commonUrl);
    }
  };

  const handleHome = () => {
    navigate(`${subDirectory}app-page/home`);
    dispatch(Changedragging(false));
  };

  const handleAddCustomerCancel = () => {
    setAddCustomer(false);
  };

  const handleHoldCancel = () => {
    setHold(false);
  };

  const paymentFailedStatusFun = async () => {
    SetOpenFailData(!OpenFailData);
  };
  const openNewTab = async () => {
    const initialData = { Paymentgateway: false };
    let screenDetails;

    if ('getScreenDetails' in window) {
      try {
        screenDetails = await window.getScreenDetails();
      } catch (error) {
        console.error('Error accessing screen details:', error);
      }
    }

    // Select second monitor if available, otherwise use primary screen
    const secondScreen = screenDetails?.screens.find(
      (screen) => screen !== screenDetails.currentScreen
    );
    const targetScreen = secondScreen || window.screen;

    const customerDisplayWindow = window.open(
      `${subDirectory}customer-display`,
      'CustomerDisplayWindow',
      `width=${targetScreen.width},height=${targetScreen.height},left=${targetScreen.left || 0},top=${targetScreen.top || 0},scrollbars=yes,resizable=yes`
    );

    if (customerDisplayWindow && !customerDisplayWindow.closed) {
      setCustomerDisplayWindow(customerDisplayWindow);

      customerDisplayWindow.onload = () => {
        setTimeout(() => {
          // Ensure it moves & resizes correctly
          customerDisplayWindow.moveTo(
            targetScreen.left || 0,
            targetScreen.top || 0
          );
          customerDisplayWindow.resizeTo(
            targetScreen.width,
            targetScreen.height
          );

          // Try fullscreen (Needs user interaction)
          try {
            customerDisplayWindow.document.documentElement.requestFullscreen();
          } catch (err) {
            console.warn('Fullscreen request failed:', err);
          }

          // Send initial data
          customerDisplayWindow.postMessage(initialData, '*');
        }, 500);
      };
    } else {
      console.error('Customer display window failed to open.');
    }
  };

  const handleClick = async () => {
    if (Comboglobal == false) {
      await dispatch(changeCombosearch(true));
    } else {
      await dispatch(changeCombosearch(false));
    }
  };

  // const Combodata = async () => {
  //   let data = {
  //     AppId: AppId,
  //     CompId: CompId,
  //     BranchId: BranchId,
  //   };

  //   let Response = await dispatch(Comboget(data)).unwrap();
  //   if (Response?.data?.statusCode == 1) {
  //     setComboDropDown(Response?.data?.data);
  //   }
  // };
  const handleOpenChange = () => {
    setOpen(!open);
  };

  const preOrderHandleclose = async () => {
    setPreOrderOpen(false);
    await dispatch(changepreOrder(false));
    setpreOrderhiseandShow(false);
  };
  const handlepreOrderhiseandShow = async () => {
    setpreOrderhiseandShow(!preOrderhiseandShow);
  };

  const searchOption = navbarOptions?.find(
    (item) => item?.OptionName === 'Search' && Comboglobal === false
  );
  const showModal = () => {
    dispatch(changeOrderCardDetails([]));
    dispatch(
      changeBtoBQuickProductTransfer({
        selectedProducts: [],
        action: !action,
      })
    );
  };

  const handleEditProfile = async () => {
    navigate(`${subDirectory}app-page/redirect-userprofile`);
  };

  //  -------------------------------------------------------------------------------------------------------------------------------------------------

  const handleotherservices = async () => {
    if (OtherServicesglobal && comboRedirectionToDefaultLayoutForParking) {
      dispatch(changeComboRedirectionToDefaultLayoutForParking(false));
      await dispatch(getTemplate({ CompId, BranchId, AppId })).unwrap();
    }
    dispatch(changeOtherServices(!OtherServicesglobal));
    dispatch(changeOrderCardDetails([]));
  };

  return (
    <div className="BSBillingNavBar2" style={{ backgroundColor: 'white' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
        <div>
          <Popconfirm
            title="Are you sure you want to go home?"
            onConfirm={handleHome}
            okText="Yes"
            cancelText="No"
          >
            <AiFillHome
              style={{ color: '#1292EE', fontSize: '30px' }}
              className="BSBillingNav2-toggle-icon"
            />
          </Popconfirm>
        </div>{' '}
        <div className="salesStoreName">
          <BranchName />
        </div>
        {(addcustomer || hold) && (
          <FeaturesFunctionalities
            handleAddCustomerCancel={handleAddCustomerCancel}
            addcustomer={addcustomer}
            handleHoldCancel={handleHoldCancel}
            modalOpen={hold}
          />
        )}
        {OtherServiceStatus && (
          <div
            style={{
              fontSize: '1.5rem',
              color: 'rgb(18, 146, 238)',
              position: 'sticky',
            }}
          >
            <TooltipWrapper title="Other Services" isMobile={isMobile}>
              <div onClick={handleotherservices}>
                <FaParking
                  fill={OtherServicesglobal === true ? '#52C41A' : '#1292EE'}
                />
              </div>
            </TooltipWrapper>
          </div>
        )}
      </div>
      {/* Multiple search  */}
      <Tooltip title={'Multiple Search'}>
        <div className="MultiSearchIconDiv2">
          <CgSearchLoading onClick={() => setMultiple(true)} />
        </div>
      </Tooltip>
      <div className="BSBillingNav2div2">
        {searchOption &&
          !Comboglobal &&
          !OtherServicesglobal &&
          !sportsAppPreference && (
            <div
              className="BSBillingNavBar2-SearchBar"
              style={{
                pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
              }}
            >
              <BSNavBarSearch nosearch={true} OrderType={OrderType} />
            </div>
          )}

        {Comboglobal === true && !OtherServicesglobal && (
          <BSNavBarComboSearch SessionData={SessionData} />
        )}

        {/* {ComboDropDown?.length >= 1 && !OtherServicesglobal && (
          <div style={{ fontSize: '1.5rem', color: 'rgb(18, 146, 238)' }}>
            <TooltipWrapper title="Combo Product" isMobile={isMobile}>
              <div
                onClick={handleClick}
                className="BSBillingNavBar1-AllIcons"
                style={{
                  width: '1.49rem',
                  margin: '10px',
                  pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
                  cursor: 'pointer',
                }}
              >
                <PozoComboProductIcon
                  fill={Comboglobal === true ? '#52C41A' : '#1292EE'}
                />
              </div>
            </TooltipWrapper>
          </div>
        )} */}
        {OpenFailData && (
          <PaymentFailedSales
            paymentFailedStatusFun={paymentFailedStatusFun}
            OpenFailData={OpenFailData}
          />
        )}

        {navbarOptions?.map((item) => (
          <>
            <div className="BSBillingNavBar2-AllIcons">
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ display: 'flex', flexGrow: '1' }}>
                  <>
                    {item?.OptionName == 'RePrint' && !OtherServicesglobal && (
                      <TooltipWrapper
                        title="RePrint (Alt+R)"
                        isMobile={isMobile}
                      >
                        <div
                          style={{
                            pointerEvents:
                              OrderType === 'Failed' ? 'none' : 'auto',
                          }}
                        >
                          <BSPrinterSetting />
                        </div>
                      </TooltipWrapper>
                    )}
                  </>

                  {!OtherServicesglobal && (
                    <>
                      {item?.OptionName == 'Hold' &&
                        OrderType != 'Failed' &&
                        OrderType != 'Reorder' &&
                        CheckBookingStatus != 'Close' &&
                        isHoldEnable &&
                        !addnewAccess && (
                          <div>
                            <BSNavBarHand />
                          </div>
                        )}

                      {item?.OptionName == 'QuickAdd' && (
                        <div
                          style={{
                            pointerEvents:
                              OrderType === 'Failed' ? 'none' : 'auto',
                          }}
                        >
                          <BSNavBarQuickAdd />
                        </div>
                      )}
                    </>
                  )}
                </div>
              </div>

              {!OtherServicesglobal && (
                <>
                  {item?.OptionName == 'QuickAdd' && dinePreference && (
                    <div style={{ padding: '1rem 1rem' }}>
                      {' '}
                      <hr style={{ height: '20px' }} />{' '}
                    </div>
                  )}

                  {(dinePreference || takeAwayPreference) && (
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <div>
                        {item?.OptionName == 'DineIn' &&
                          dinePreference &&
                          !BookingTypeBoth &&
                          PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
                            (item) => item.SettingIdName === 'DineIn'
                          )?.SettingValue === 'Y' && (
                            <div
                              style={{
                                pointerEvents:
                                  OrderType === 'Failed' || addnewAccess
                                    ? 'none'
                                    : 'auto',
                              }}
                            >
                              <BSNavBarTable />
                            </div>
                          )}
                        {item?.OptionName == 'TakeAway' &&
                          takeAwayPreference && (
                            <div
                              style={{
                                pointerEvents:
                                  OrderType === 'Failed' ? 'none' : 'auto',
                              }}
                            >
                              <BSNavBarHandbag />
                            </div>
                          )}
                      </div>
                    </div>
                  )}

                  {item?.OptionName == 'TakeAway' && takeAwayPreference && (
                    <div style={{ padding: '1rem 1rem' }}>
                      {' '}
                      <hr style={{ height: '20px' }} />{' '}
                    </div>
                  )}

                  <div>
                    {item?.OptionName === 'Offer' &&
                      GlobEstBooking !== 'OvrAllEst' &&
                      GlobEstBooking !== 'ParEst' &&
                      GlobEstBooking === 'Sales' &&
                      PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
                        (item) => item.SettingIdName === 'Offer'
                      )?.SettingValue === 'Y' && (
                        <div
                          style={{
                            pointerEvents:
                              OrderType === 'Failed' ? 'none' : 'auto',
                          }}
                        >
                          <BSNavBarOffer />
                        </div>
                      )}
                    {item?.OptionName == 'ExtraCharge' && (
                      <div
                        style={{
                          pointerEvents:
                            OrderType === 'Failed' ? 'none' : 'auto',
                        }}
                      >
                        <BSNavBarAddons />
                      </div>
                    )}
                    {item?.OptionName == 'AddCustomer' && !preOrderOpen && (
                      <>
                        <div style={{ display: 'flex', gap: '1rem' }}>
                          <BSCustomerSelect TopName={'navbar-top'} />
                          <BSNavBarAddUser />
                        </div>
                      </>
                    )}
                  </div>
                </>
              )}
            </div>
          </>
        ))}
        {FeatureAddonData?.FeatureDtls?.find(
          (item) => item?.FeatureAddonName?.toLowerCase() === 'weight scale'
        ) &&
          !OtherServicesglobal && (
            <div
              style={{
                pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
              }}
            >
              <BSNavBarWeightScale />
            </div>
          )}

        {!OtherServicesglobal && (
          <>
            {FeatureAddonData?.FeatureDtls?.find(
              (item) => item?.FeatureAddonName?.toLowerCase() === 'preorder'
            ) && (
              <div
                className="BSBillingNavBar2-AllIcons"
                style={{
                  pointerEvents:
                    tableData || OrderType === 'Failed' ? 'none' : 'auto',
                  opacity: tableData ? 0.5 : 1,
                }}
              >
                <TooltipWrapper title={'Pre Booking'} isMobile={isMobile}>
                  <Badge
                    count={preOrderPendingCount}
                    offset={[-5, 10]}
                    size="small"
                  >
                    <PozoPreOrderIcon
                      className="BSBillingNav-icon"
                      fill={preOrderOpen ? '#52C41A' : '#1292EE'}
                      onClick={() => {
                        openPreOrder();
                      }}
                      HandleClose={preOrderHandleclose}
                    />
                  </Badge>
                </TooltipWrapper>
              </div>
            )}
          </>
        )}
        {preOrderOpen && (
          <div className="smallScreenclose">
            <BSNavBarPreOrder HandleClose={preOrderHandleclose} />
          </div>
        )}
        {sportsAppPreference && <BSMembership />}
        {!OtherServicesglobal && (
          <>
            {Estimation?.SettingValue === 'Y' &&
              BookingType !== 'Dine In' &&
              !BookingTypeBoth &&
              !OrderOfferStatus && (
                <div
                  className="BSBillingNavBar2-AllIcons"
                  style={{
                    pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
                  }}
                >
                  <BSNavBarEstimate />
                </div>
              )}
          </>
        )}
        {SalesMode?.SettingValue === 'Y' && !OtherServicesglobal && (
          <BSNavBarWholeSale />
        )}
        {!OtherServicesglobal && ScanLayoutScreen?.SettingValue === 'Y' && (
          <BSScanTemplate />
        )}

        {!OtherServicesglobal && (
          <>
            {!sportsAppPreference && (
              <div
                className="favIcon"
                style={{
                  pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
                }}
              >
                <BSNavBarFavItems />
              </div>
            )}
            <div
              className="favIcon"
              style={{
                pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
              }}
            >
              {/* <TfiHandDrag onClick={() => dispatch(Changedragging(!Isdragging))} style={{ color: Isdragging ? "green" : "#1292ee",fontSize:"25px" }} /> */}

              <BSNavBarDragItems />
            </div>
          </>
        )}

        {FeatureAddonData?.FeatureDtls?.find(
          (item) => item?.FeatureAddonName?.toLowerCase() === 'customer display'
        ) && (
          <TooltipWrapper title="Customer Display" isMobile={isMobile}>
            {/* <div onClick={openNewTab} style={{ display: "flex", alignItems: "center", cursor: "pointer" }} className="BSBillingNavBar2-AllIcons">
              <FaDisplay />
            </div> */}
            <div
              onClick={openNewTab}
              className="BSBillingNavBar1-AllIcons"
              style={{ width: '1.3rem', margin: '10px', cursor: 'pointer' }}
            >
              <CustomerDisplayicon />
            </div>
          </TooltipWrapper>
        )}
        {VerifyTheProducts && (
          <TooltipWrapper title={'Verfied Products'} isMobile={isMobile}>
            <div>
              <VerfiedProducts />
            </div>
          </TooltipWrapper>
        )}
        {paymentfeataddon && !OtherServicesglobal && (
          <TooltipWrapper title="Failed Payment" isMobile={isMobile}>
            <div
              onClick={() => {
                paymentFailedStatusFun();
              }}
              className="BSBillingNavBar1-AllIcons"
              style={{ width: '1.4rem', cursor: 'pointer' }}
            >
              <PozoPaymentFailesIcon />
            </div>
          </TooltipWrapper>
        )}

        {!OtherServicesglobal && (
          <div>
            <BSNavBarUserInfo
              isOpen={isAccOpen}
              divRef={divRef}
              CompBranchData={CompBranchData}
              BacktoLogin={BacktoLogin}
              userProfileData={userProfileData}
              handleEditProfile={handleEditProfile}
              UserRelieveManager={<UserRelieveManager />}
              Logout={Logout}
            />
          </div>
        )}
        {/* small screen nav bar */}
        {Navmenu && (
          <>
            <div className="BSBillingnav2-Smallscreen">
              <div className="BSBillingNavBar2-AllIcons-column">
                {OtherServiceStatus && (
                  <div
                    style={{ fontSize: '1.5rem', color: 'rgb(18, 146, 238)' }}
                  >
                    <TooltipWrapper title="Other Services" isMobile={isMobile}>
                      <div onClick={handleotherservices}>
                        <FaParking
                          fill={
                            OtherServicesglobal === true ? '#52C41A' : '#1292EE'
                          }
                        />
                      </div>
                    </TooltipWrapper>
                  </div>
                )}

                {OpenFailData && (
                  <PaymentFailedSales
                    paymentFailedStatusFun={paymentFailedStatusFun}
                    OpenFailData={OpenFailData}
                  />
                )}
                {/* {ComboDropDown?.length >= 1 && !OtherServicesglobal && (
                  <div
                    style={{ fontSize: '1.5rem', color: 'rgb(18, 146, 238)' }}
                  >
                    <TooltipWrapper title="Combo Product" isMobile={isMobile}>
                      <div
                        onClick={handleClick}
                        style={{
                          width: '1.49rem',
                          pointerEvents:
                            OrderType === 'Failed' ? 'none' : 'auto',
                          cursor: 'pointer',
                        }}
                      >
                        <PozoComboProductIcon
                          fill={Comboglobal === true ? '#52C41A' : '#1292EE'}
                        />
                      </div>
                    </TooltipWrapper>
                  </div>
                )} */}
                {navbarOptions?.map((item) => (
                  <>
                    {item?.OptionName == 'RePrint' && !OtherServicesglobal && (
                      <div
                        style={{
                          pointerEvents:
                            OrderType === 'Failed' ? 'none' : 'auto',
                        }}
                      >
                        <BSPrinterSetting />
                      </div>
                    )}
                    {!OtherServicesglobal && (
                      <>
                        {item?.OptionName == 'Hold' &&
                          OrderType != 'Failed' &&
                          OrderType != 'Reorder' &&
                          CheckBookingStatus != 'Close' &&
                          isHoldEnable &&
                          !addnewAccess && (
                            <div className="BSBillingNavBar2-hand">
                              <BSNavBarHand />
                            </div>
                          )}
                        {/* {item?.OptionName == 'Quick Transfer' && (
                      <div
                        style={{
                          pointerEvents:
                            OrderType === 'Failed' ? 'none' : 'auto',
                        }}
                      >
                        <Tooltip title="Quick Transfer" placement="top">
                          <Button
                            type="primary"
                            shape="circle"
                            icon={<SwapIcon />}
                            size="small"
                            onClick={showModal}
                          />
                        </Tooltip>
                      </div>
                    )} */}
                        {item?.OptionName == 'QuickAdd' && (
                          <div
                            style={{
                              pointerEvents:
                                OrderType === 'Failed' ? 'none' : 'auto',
                            }}
                          >
                            <BSNavBarQuickAdd />
                          </div>
                        )}
                        {item?.OptionName == 'DineIn' &&
                          dinePreference &&
                          PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
                            (item) => item.SettingIdName === 'DineIn'
                          )?.SettingValue === 'Y' && (
                            <div
                              style={{
                                pointerEvents:
                                  OrderType === 'Failed' || addnewAccess
                                    ? 'none'
                                    : 'auto',
                              }}
                            >
                              <BSNavBarTable />
                            </div>
                          )}
                        {item?.OptionName == 'TakeAway' && (
                          <div
                            style={{
                              pointerEvents:
                                OrderType === 'Failed' ? 'none' : 'auto',
                            }}
                          >
                            <BSNavBarHandbag />
                          </div>
                        )}
                        {item?.OptionName === 'Offer' &&
                          GlobEstBooking !== 'OvrAllEst' &&
                          GlobEstBooking !== 'ParEst' &&
                          GlobEstBooking === 'Sales' &&
                          PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
                            (item) => item.SettingIdName === 'Offer'
                          )?.SettingValue === 'Y' && (
                            <div
                              style={{
                                pointerEvents:
                                  OrderType === 'Failed' ? 'none' : 'auto',
                              }}
                            >
                              <BSNavBarOffer />
                            </div>
                          )}
                        {item?.OptionName == 'ExtraCharge' && (
                          <div
                            style={{
                              pointerEvents:
                                OrderType === 'Failed' ? 'none' : 'auto',
                            }}
                          >
                            <BSNavBarAddons />
                          </div>
                        )}

                        {item?.OptionName == 'AddCustomer' && (
                          <Popover
                            content={
                              <div
                                style={{
                                  display: 'flex',
                                  alignItems: 'center',
                                  columnGap: '0.5rem',
                                }}
                              >
                                <BSCustomerSelect TopName={'navbar-top'} />
                                <BSNavBarAddUser />
                              </div>
                            }
                            trigger="click"
                            placement="left"
                            open={open}
                            onOpenChange={handleOpenChange}
                          >
                            <div>
                              <PozoAddCustomerIcon className="BSBillingNav-icon" />
                            </div>
                          </Popover>
                        )}
                      </>
                    )}
                  </>
                ))}
                {!OtherServicesglobal && (
                  <>
                    {FeatureAddonData?.FeatureDtls?.find(
                      (item) =>
                        item?.FeatureAddonName?.toLowerCase() === 'Weight Scale'
                    ) && (
                      <div
                        style={{
                          pointerEvents:
                            OrderType === 'Failed' ? 'none' : 'auto',
                        }}
                      >
                        <BSNavBarWeightScale />
                      </div>
                    )}
                    {!OtherServicesglobal && (
                      <>
                        {FeatureAddonData?.FeatureDtls?.find(
                          (item) =>
                            item?.FeatureAddonName?.toLowerCase() === 'preorder'
                        ) && (
                          <div
                            style={{
                              pointerEvents:
                                tableData || OrderType === 'Failed'
                                  ? 'none'
                                  : 'auto',
                              opacity: tableData ? 0.5 : 1,
                            }}
                          >
                            <TooltipWrapper
                              title={'Pre Booking'}
                              isMobile={isMobile}
                            >
                              <Badge
                                count={preOrderPendingCount}
                                offset={[-5, 10]}
                                size="small"
                              >
                                <PozoPreOrderIcon
                                  className="BSBillingNav-icon"
                                  fill={preOrderOpen ? '#52C41A' : '#1292EE'}
                                  onClick={() => {
                                    openPreOrder('small-screen');
                                  }}
                                />
                              </Badge>
                            </TooltipWrapper>
                          </div>
                        )}
                      </>
                    )}
                    {preOrderOpen && (
                      <BSNavBarPreOrder
                        preOrderhiseandShow={handlepreOrderhiseandShow}
                        preOrderhideshow={preOrderhiseandShow}
                        HandleClose={preOrderHandleclose}
                      />
                    )}
                    {sportsAppPreference && <BSMembership />}
                    {Estimation?.SettingValue === 'Y' &&
                      !OrderOfferStatus &&
                      BookingType !== 'Dine In' &&
                      !BookingTypeBoth && (
                        <div
                          style={{
                            pointerEvents:
                              OrderType === 'Failed' ? 'none' : 'auto',
                          }}
                        >
                          <BSNavBarEstimate />
                        </div>
                      )}
                    {SalesMode?.SettingValue === 'Y' &&
                      !OtherServicesglobal && <BSNavBarWholeSale />}
                    {!OtherServicesglobal &&
                      ScanLayoutScreen?.SettingValue === 'Y' && (
                        <BSScanTemplate />
                      )}
                    {!sportsAppPreference && (
                      <div
                        style={{
                          pointerEvents:
                            OrderType === 'Failed' ? 'none' : 'auto',
                        }}
                      >
                        <BSNavBarFavItems type="small-screen" />
                      </div>
                    )}
                    <div
                      style={{
                        pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
                      }}
                    >
                      <BSNavBarDragItems type="small-screen" />
                    </div>
                    {FeatureAddonData?.FeatureDtls?.find(
                      (item) =>
                        item?.FeatureAddonName?.toLowerCase() ===
                        'customer display'
                    ) && (
                      <TooltipWrapper
                        title="Customer Display"
                        isMobile={isMobile}
                      >
                        {/* <div onClick={openNewTab} style={{ display: "flex", alignItems: "center", cursor: "pointer" }}>
                      <FaDisplay />
                    </div> */}
                        <div
                          onClick={openNewTab}
                          style={{ width: '1.3rem', cursor: 'pointer' }}
                        >
                          <CustomerDisplayicon />
                        </div>
                      </TooltipWrapper>
                    )}
                    {VerifyTheProducts && (
                      <TooltipWrapper
                        title={'Verfied Products'}
                        isMobile={isMobile}
                      >
                        <div>
                          <VerfiedProducts />
                        </div>
                      </TooltipWrapper>
                    )}
                    {paymentfeataddon && (
                      <TooltipWrapper
                        title="Failed Payment"
                        isMobile={isMobile}
                      >
                        <div
                          onClick={() => {
                            paymentFailedStatusFun();
                          }}
                          style={{ width: '1.4rem', cursor: 'pointer' }}
                        >
                          <PozoPaymentFailesIcon />
                        </div>
                      </TooltipWrapper>
                    )}
                  </>
                )}
              </div>
            </div>
          </>
        )}
        {isMobile && (
          <div
            style={{
              color: 'rgb(33, 150, 243)',
            }}
          >
            <BSMobilePrintSettings />
          </div>
        )}
        {!OtherServicesglobal && (
          <TooltipWrapper title="User Profile" isMobile={isMobile}>
            <div>
              <PozoUserIcon
                className="BSBillingNav-icon"
                onClick={UserAcc}
                style={{ color: '#1292EE', fontSize: '21px' }}
              />
            </div>
          </TooltipWrapper>
        )}
      </div>

      <div className="BSBillingnav2-threedots" onClick={NavmenuOpenClose}>
        <MenuOutlined />
      </div>

      <DefaultModal
        open={multiple}
        title="Multiple Search"
        footer={false}
        width={350}
        handleCancel={() => setMultiple(false)}
        destroyOnClose={true}
        children={
          <>
            <MultipleSearch close={setMultiple} />
          </>
        }
      />
    </div>
  );
};
export default BSNavbar2;
