import React, { useCallback, useEffect, useRef, useState, lazy } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { Badge, Popconfirm, Popover, Tooltip } from 'antd';
import {
  GlobalBookingType,
  GlobalBookingTypeBoth,
  PreferenceData,
  GlobalCombosearch,
  getPreferenceData,
  GlobalOrderCardDetails,
  changeEstimateBooking,
  GlobalOrderStatus,
  GlobalEstimateBooking,
  changeSelectedOption,
  changealldata,
  changeCustomerID,
  changeSelectedCustId,
  GlobalOrderType,
  Changedragging,
  changeBtoBQuickProductTransfer,
  GlobalBtoBQuickProductTransfer,
  changeOrderCardDetails,
  GlobalFeatAddOnData,
  GlobalOtherSevices,
  changeOtherServices,
  GlobalComboRedirectionToDefaultLayoutForParking,
  changeComboRedirectionToDefaultLayoutForParking,
  GlobalCommonPaymentOptions,
  GlobalSelCustId,
} from '../../../../Features/BookingScreen/BookingData/BookingData.js';
// js Files
import {
  GlobalPreOrderPendingCount,
  PreOrderGet,
  changePreOrderPendingCount,
  changepreOrder,
  changePreOrderAdditem,
  changepreOrderList,
} from '../../../../Features/BookingScreen/PreOrder/PreOrder.js';
import {
  ApplicationPreferences,
  GenerateLogout,
  GlobalCompBranchData,
  getCompBranchData,
} from '../../../../Features/BrachLogin/BranchLogin.js';
import { getCustomerDisplayWindow } from '../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
import { Global_OfferStatus } from '../../../../Features/Offer/Offer.js';
import {
  getTemplate,
  getTemplateData,
  StoredSessionData,
} from '../../../../Features/ThemeChange/ThemeChange.js';
import { GlobalBookingStatus } from '../../../../Features/Payment/PaymentReceivedRetail/PaymentReceivedRetail.js';
import { getEmpAccess } from '../../../../Features/AppPage/CenterPage.js';
import {
  getUserProfile,
  userDataByUserId,
} from '../../../../Features/UserAccount/userData.js';
import { OtherServicesCardlistdata } from '../../../../Features/OtherServices/OtherServices.js';
import { clearSession, sessionStore } from '../../../../Services/Others.js';
import { setCustomerDisplayWindow } from '../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
import BSMobilePrintSettings from '../UtillComponents/BSMobilePrintSettings.jsx';

// Jsx Files
const BSNavBarOffer = lazy(
  () => import('../UtillComponents/BSNavBarOffer/BSNavBarOffer.jsx')
);

const BSNavBarPreOrder = lazy(
  () => import('../../Components/UtillComponents/BSNavBarPreOrder.jsx')
);
const BSNavBarEstimate = lazy(
  () => import('../UtillComponents/BSNavBarEst.jsx')
);
const BSCustomerSelect = lazy(
  () => import('../UtillComponents/BSSelectCustomer.jsx')
);
const TimerClock = lazy(() => import('../BSCombo/BSTimer.jsx'));
const BSPrinterSetting = lazy(
  () => import('../UtillComponents/BSPrinterSetting.jsx')
);
const BSNavBarComboSearch = lazy(
  () => import('../UtillComponents/BSNavBarComboSearch.jsx')
);
const PaymentFailedSales = lazy(
  () => import('../../../Payment/PaymentFailedDetails/PaymentFailedSales.jsx')
);
const BSNavBarWholeSale = lazy(
  () => import('../UtillComponents/BSNavBarWholeSale.jsx')
);
const BSScanTemplate = lazy(
  () => import('../UtillComponents/BSScanTemplate.jsx')
);
const VerfiedProducts = lazy(
  () => import('./verfiedProduct/VerfiedProducts.jsx')
);
const BSMembership = lazy(() => import('../UtillComponents/BSMembership.jsx'));
const BranchName = lazy(() => import('../../Template/BranchName.jsx'));
const MultipleSearch = lazy(
  () => import('../UtillComponents/MultipleSearch.jsx')
);
const BSNavBarDragItems = lazy(
  () => import('../UtillComponents/BSNavBarDragItems.jsx')
);
const UserRelieveManager = lazy(
  () => import('../../Template/RealivingUser.jsx')
);
const FeaturesFunctionalities = lazy(
  () => import('../BookingFunctionality/FeaturesFunctionalities.jsx')
);

import { useAuth } from '../../../../AuthContext.jsx';
const BSNavBarAddons = lazy(
  () => import('../UtillComponents/BSNavBarAddons.jsx')
);

const BSNavBarQuickAdd = lazy(
  () => import('../UtillComponents/BSNavBarQuickAdd.jsx')
);
const BSNavBarAddUser = lazy(
  () => import('../UtillComponents/BSNavBarAddUser.jsx')
);
const BSNavBarSearch = lazy(
  () => import('../UtillComponents/BSNavBarSearch.jsx')
);

const BSNavBarWeightScale = lazy(
  () => import('../UtillComponents/BSNavBarWeightScale.jsx')
);
const BSNavBarFavItems = lazy(
  () => import('../UtillComponents/BSNavBarFavItems.jsx')
);
const BSNavBarHand = lazy(() => import('../UtillComponents/BSNavBarHand.jsx'));
const BSNavBarTable = lazy(
  () => import('../UtillComponents/BSNavBarTable.jsx')
);
const BSNavBarHandbag = lazy(
  () => import('../UtillComponents/BSNavBarHandbag.jsx')
);

// Icon Files

import PozoHomeIcon from '../UtillComponents/Pozo retail icons/PozoHomeIcon';
import PozoPreOrderIcon from '../UtillComponents/Pozo retail icons/PozoPreOrderIcon.jsx';
import PozoUserIcon from '../UtillComponents/Pozo retail icons/PozoUserIcon';
import PozoAddCustomerIcon from '../UtillComponents/Pozo retail icons/PozoAddCustomerIcon.jsx';
import CustomerDisplayicon from '../UtillComponents/Pozo retail icons/PozoCustomerDisplayicon.jsx';
import PozoPaymentFailesIcon from '../UtillComponents/Pozo retail icons/PozoFailedPaymentsIcon.jsx';
import PozoMenuIcon from '../UtillComponents/Pozo retail icons/PozoMenuIcon.jsx';

import TooltipWrapper from '../../../../Components/Tooltip/Tooltip';
import { IoMdClose } from 'react-icons/io';
import { TbSettingsSearch } from 'react-icons/tb';
import BSNavBarUserInfo from './BSNavBarUserInfo';
import { FaParking } from 'react-icons/fa';
import { isMobile } from 'react-device-detect';
import { DefaultModal } from '../../../../Components/Modal/DefaultModal.jsx';
import '../../../../Styles/BookingScreen/Components/BSNavbar/BSNavbar1.scss';
import { RiFullscreenExitFill, RiFullscreenFill } from 'react-icons/ri';

const subDirectory = import.meta.env.ENV_BASE_URL;
const commonUrl = import.meta.env.ENV_COMMON_BASE_URL;

const BSNavbar1 = (props) => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [Navmenu, setNavmenu] = useState(false);
  const [isAccOpen, setAccIsOpen] = useState(false);
  const [formattedDate, setFormattedDate] = useState('');

  // const [FeatureAddonData, setFeatureAddonData] = useState([]);
  const [paymentfeataddon, setpaymentfeataddon] = useState(false);
  const [addcustomer, setAddCustomer] = useState(false);
  const [hold, setHold] = useState(false);
  const [multiple, setMultiple] = useState(false);
  const BSLayout1Data = useSelector(getTemplateData);
  const navbarOptions = BSLayout1Data?.BookingNavbar?.[1];
  const PreferenceDatas = useSelector(PreferenceData);
  const OrderOfferStatus = useSelector(Global_OfferStatus);
  const { action, selectedProducts } = useSelector(
    GlobalBtoBQuickProductTransfer
  );
  const GlobaluseOptions = useSelector(GlobalCommonPaymentOptions);
  const SelCustId = useSelector(GlobalSelCustId);
  console.log(GlobaluseOptions, 'GlobaluseOptions');
  const CompBranchData = useSelector(GlobalCompBranchData);
  const tableData = useSelector(GlobalOrderStatus);
  const BookingType = useSelector(GlobalBookingType);
  const BookingTypeBoth = useSelector(GlobalBookingTypeBoth);
  const FeatureAddonData = useSelector(GlobalFeatAddOnData);
  const Estimation = PreferenceDatas?.[0]?.SettingDtlDetails?.find(
    (item) => item.SettingIdName === 'Estimation'
  );
  const SalesMode = PreferenceDatas?.[0]?.SettingDtlDetails?.find(
    (item) => item.SettingIdName === 'Sales Mode'
  );
  const ScanLayoutScreen = PreferenceDatas?.[0]?.SettingDtlDetails?.find(
    (item) => item.SettingIdName === 'ScanLayout'
  );
  const VerifyTheProducts = PreferenceDatas?.[0]?.SettingDtlDetails?.find(
    (item) =>
      item.SettingIdName === 'VerifyProduct' && item?.SettingValue === 'Y'
  );
  const Comboglobal = useSelector(GlobalCombosearch);
  const OtherServicesglobal = useSelector(GlobalOtherSevices);

  // const [ComboDropDown, setComboDropDown] = useState(true);
  const [preOrderOpen, setPreOrderOpen] = useState(false);
  const [isHoldEnable, setisisHoldEnable] = useState(false);
  const [preOrderhiseandShow, setpreOrderhiseandShow] = useState(false);
  const userProfileData = useSelector(userDataByUserId);
  const [open, setOpen] = useState(false);
  const preOrderPendingCount = useSelector(GlobalPreOrderPendingCount);
  const [OpenFailData, SetOpenFailData] = useState(false);
  const OrderType = useSelector(GlobalOrderType);
  const GlobEstBooking = useSelector(GlobalEstimateBooking);
  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 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 BookingStatus = useSelector(GlobalBookingStatus);
  const [OtherServiceStatus, setOtherServiceStatus] = useState(false);
  const CheckBookingStatus =
    BookingStatus?.find((item) => item.ScreenType === 'Booking')
      ?.ScreenStatus ?? 'Open';
  const [empData, setEmpData] = useState();
  const [addnewAccess, setaddnewAccess] = useState(true);
  const { SadminuserAccess } = useAuth();
  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Sales'
  );
  const comboRedirectionToDefaultLayoutForParking = useSelector(
    GlobalComboRedirectionToDefaultLayoutForParking
  );

  const divRef = useRef(null);
  const handleClickOutside = (event) => {
    if (divRef.current && !divRef.current.contains(event.target)) {
      setAccIsOpen(false);
    }
  };
  const [isFullscreen, setIsFullscreen] = useState(false);


  
  const handleFullscreen = useCallback(async () => {
    if (!isFullscreen) {
      try {
        await document.documentElement.requestFullscreen();
        setIsFullscreen(true);
      } catch (error) {
        console.error('Fullscreen error:', error);
      }
    } else {
      try {
        if (document.fullscreenElement) {
          await document.exitFullscreen();
        }
        setIsFullscreen(false);
      } catch (error) {
        console.error('Exit fullscreen error:', error);
      }
    }
  }, [isFullscreen]);

  useEffect(() => {
    if (!FeatureAddonData?.FeatureDtls?.length) return;

    const preorderFeature = FeatureAddonData.FeatureDtls.find(
      (item) => item?.FeatureAddonName?.toLowerCase() === 'preorder'
    );

    if (preorderFeature) {
      BadgePendingApi();
    }
  }, [FeatureAddonData]);

  useEffect(() => {
    handleOtherData();

    // 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(() => {
    if (UserType === 'Employee') {
      fetchApi();
    }
  }, [UserType]);
  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]);
  };
  useEffect(() => {
    const d = new Date();
    const formatted = new Intl.DateTimeFormat('en-GB', {
      day: 'numeric',
      month: 'short',
      year: 'numeric',
    }).format(d);
    setFormattedDate(formatted);
    dispatch(
      getPreferenceData({ CompId: CompId, AppId: AppId, BranchId: BranchId })
    );
    dispatch(getUserProfile({ UserId: UserId, ActiveStatus: 'A' })).unwrap();
    fetchBranchData();
  }, [UserId]);
  useEffect(() => {
    if (UserType !== 'Super Admin' && UserType !== 'Super Admin User') {
      getFeatureAddonData();
    }
  }, [FeatureAddonData]);

  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 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 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 NavmenuOpenClose = () => {
    setNavmenu(!Navmenu);
  };
  const UserAcc = useCallback(() => {
    setAccIsOpen((prev) => !prev);
  }, []);

  const background = '#ffff';

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

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

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

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

  //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 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 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 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 handleOpenChange = () => {
    setOpen(!open);
  };
  const preOrderHandleclose = async () => {
    setPreOrderOpen(false);
    await dispatch(changepreOrder(false));
    setpreOrderhiseandShow(false);
  };
  const handlepreOrderhiseandShow = async () => {
    setpreOrderhiseandShow(!preOrderhiseandShow);
  };
  const paymentFailedStatusFun = async () => {
    SetOpenFailData(!OpenFailData);
  };
  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(changeOrderCardDetails([]));
    dispatch(changeOtherServices(!OtherServicesglobal));
  };

  return (
    <div
      className="BSBillingNavBar1"
      style={{
        backgroundColor: background,
        color:
          background == 'white' && '#fff' && '#ffff' && 'rgb(1, 1, 1)'
            ? 'white'
            : 'black',
      }}
    >
      <Popconfirm
        title="Are you sure you want to go home?"
        onConfirm={handleHome}
        okText="Yes"
        cancelText="No"
      >
        <div>
          <TooltipWrapper
            title="Back to Home"
            placement="right"
            isMobile={isMobile}
          >
            <PozoHomeIcon
              style={{
                color: '#1292EE',
                fontSize: '28px',
                cursor: 'pointer',
              }}
              className="BSBillingNav2-toggle-icon"
            />
          </TooltipWrapper>
        </div>
      </Popconfirm>
      {(addcustomer || hold) && (
        <FeaturesFunctionalities
          handleAddCustomerCancel={handleAddCustomerCancel}
          addcustomer={addcustomer}
          handleHoldCancel={handleHoldCancel}
          modalOpen={hold}
        />
      )}
      <div className="BSBillingNav1div2">
        <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
          <div className="salesStoreName">
            <BranchName />
          </div>

          {OtherServiceStatus && (
            <div style={{ fontSize: '1.5rem', color: 'rgb(18, 146, 238)' }}>
              <TooltipWrapper title="Other Services" isMobile={isMobile}>
                <div
                  onClick={handleotherservices}
                  className="BSBillingNavBar1-AllIcons"
                  style={{
                    width: '1.49rem',
                    margin: '0',
                    pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
                    cursor: 'pointer',
                  }}
                >
                  <FaParking
                    fill={OtherServicesglobal === true ? '#52C41A' : '#1292EE'}
                  />
                </div>
              </TooltipWrapper>
            </div>
          )}
        </div>

        <div className="NavbarDivForSearch">
          {/* Multiple search  */}
          <Tooltip title={'Multiple Search'}>
            <div className="MultiSearchIconDiv">
              <TbSettingsSearch onClick={() => setMultiple(true)} />
            </div>
          </Tooltip>

          {!OtherServicesglobal && (
            <>
              {navbarOptions?.map((item) => (
                <>
                  {item?.OptionName == 'Search' &&
                    Comboglobal === false &&
                    !sportsAppPreference && (
                      <div
                        className="BSBillingNavBar1-Inputsearch-container"
                        style={{
                          pointerEvents:
                            OrderType === 'Failed' ? 'none' : 'auto',
                        }}
                      >
                        <BSNavBarSearch nosearch={true} OrderType={OrderType} />
                      </div>
                    )}
                </>
              ))}
              {Comboglobal === true && (
                <div className="Navbar1SearchCombo">
                  <BSNavBarComboSearch SessionData={SessionData} />
                </div>
              )}
            </>
          )}
        </div>

        {!OtherServicesglobal && (
          <>
            {OpenFailData && (
              <PaymentFailedSales
                paymentFailedStatusFun={paymentFailedStatusFun}
                OpenFailData={OpenFailData}
              />
            )}
          </>
        )}
        <div className="BSBillingNavBar1-AllIcons">
          {navbarOptions?.map((item) => (
            <>
              <>
                {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 className="BSBillingNavBar1-hand">
                        <BSNavBarHand />
                      </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' && takeAwayPreference && (
                    <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' && (
                    // CartOrderDetails?.length > 0 &&
                    <div
                      style={{
                        pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
                      }}
                    >
                      <BSNavBarAddons />
                    </div>
                  )}
                  {item?.OptionName == 'AddCustomer' && !preOrderOpen && (
                    <>
                      <BSCustomerSelect TopName={'navbar-top'} />
                      <BSNavBarAddUser />
                    </>
                  )}
                </>
              )}
            </>
          ))}

          {!OtherServicesglobal && (
            <>
              {FeatureAddonData?.FeatureDtls?.find(
                (item) =>
                  item?.FeatureAddonName?.toLowerCase() === 'weight scale'
              ) && (
                <div
                  style={{
                    pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
                  }}
                >
                  <BSNavBarWeightScale />
                </div>
              )}
              {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();
                        }}
                        HandleClose={preOrderHandleclose}
                      />
                    </Badge>
                  </TooltipWrapper>
                </div>
              )}
              {preOrderOpen && (
                <BSNavBarPreOrder HandleClose={preOrderHandleclose} />
              )}
              {sportsAppPreference && <BSMembership />}
              {Estimation?.SettingValue === 'Y' &&
                BookingType !== 'Dine In' &&
                !BookingTypeBoth &&
                !OrderOfferStatus && (
                  <div
                    style={{
                      pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
                    }}
                  >
                    <BSNavBarEstimate />
                  </div>
                )}
              {/* mohan */}
              {SalesMode?.SettingValue === 'Y' && !OtherServicesglobal && (
                <BSNavBarWholeSale />
              )}
              {!OtherServicesglobal &&
                ScanLayoutScreen?.SettingValue === 'Y' && <BSScanTemplate />}
              {!sportsAppPreference && (
                <div
                  style={{
                    pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
                  }}
                >
                  <BSNavBarFavItems />
                </div>
              )}
              <div
                className="favIcon"
                style={{
                  pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
                }}
              >
                <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" }}>
                <FaDisplay />
              </div> */}
                  <div
                    onClick={openNewTab}
                    className="BSBillingNavBar1-AllIcons"
                    style={{
                      width: '1.3rem',
                      margin: '10px',
                      cursor: 'pointer',
                    }}
                  >
                    <CustomerDisplayicon />
                  </div>
                </TooltipWrapper>
              )}
              {paymentfeataddon && (
                <TooltipWrapper title="Failed Payment" isMobile={isMobile}>
                  {/* <img src={paymentFailure} width={20} height={20} style={{ cursor: "pointer" }} onClick={() => { paymentFailedStatusFun() }}></img> */}
                  {/* <MdMoneyOff size={20} style={{ color: "rgb(33, 150, 243)",cursor:"pointer" }} onClick={() => { paymentFailedStatusFun() }} /> */}
                  <div
                    onClick={() => {
                      paymentFailedStatusFun();
                    }}
                    className="BSBillingNavBar1-AllIcons"
                    style={{ width: '1.4rem', cursor: 'pointer' }}
                  >
                    <PozoPaymentFailesIcon />
                  </div>
                </TooltipWrapper>
              )}

              {VerifyTheProducts && (
                <TooltipWrapper title={'Verfied Products'} isMobile={isMobile}>
                  <div>
                    <VerfiedProducts />
                  </div>
                </TooltipWrapper>
              )}
            </>
          )}
        </div>
        {isMobile && (
          <div
            style={{
              color: 'rgb(33, 150, 243)',
            }}
          >
            <BSMobilePrintSettings />
          </div>
        )}
        {!OtherServicesglobal && (
          <>
            <div className="BSNavbar1-time-user">
              <div
                className="BSBillingNavBar1-SearchBar"
                style={{ color: '#212529', flexDirection: 'column' }}
              >
                <TimerClock />
                {formattedDate}
              </div>
            </div>

            <Tooltip title={isFullscreen ? 'Exit Full Screen' : 'Full Screen'}>
              <div
                className={
                  isFullscreen
                    ? 'BsNavbar1FullScreenExit'
                    : 'BsNavbar1FullScreen'
                }
                onClick={handleFullscreen}
              >
                {isFullscreen ? <RiFullscreenExitFill /> : <RiFullscreenFill />}
              </div>
            </Tooltip>

            <TooltipWrapper title="User Profile" isMobile={isMobile}>
              <div className="UserProfile">
                <PozoUserIcon onClick={UserAcc} />
              </div>
            </TooltipWrapper>

            {/* {isMobile && ( */}
            {/* <div>
              <BSPrinterSetting />
            </div> */}
            {/* )} */}

            {/* Use BSNavBarUserInfo for the account menu */}
            <BSNavBarUserInfo
              isOpen={isAccOpen}
              divRef={divRef}
              CompBranchData={CompBranchData}
              BacktoLogin={BacktoLogin}
              userProfileData={userProfileData}
              handleEditProfile={handleEditProfile}
              UserRelieveManager={<UserRelieveManager />}
              Logout={Logout}
            />
          </>
        )}

        {/* small screen nav bar */}
        {Navmenu && (
          <div>
            <div
              className="BSBillingnav1-Smallscreen"
              style={{ backgroundColor: background }}
            >
              <div className="BSBillingNavBar1-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>
                )}
                {!OtherServicesglobal &&
                  ScanLayoutScreen?.SettingValue === 'Y' && <BSScanTemplate />}

                {!OtherServicesglobal && (
                  <>
                    {OpenFailData && (
                      <PaymentFailedSales
                        paymentFailedStatusFun={paymentFailedStatusFun}
                        OpenFailData={OpenFailData}
                      />
                    )}
                    {/* {ComboDropDown?.length >= 1 && (
                      <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>
                          )}
                        {item?.OptionName == 'Hold' &&
                          OrderType != 'Failed' &&
                          OrderType != 'Reorder' &&
                          CheckBookingStatus != 'Close' &&
                          isHoldEnable &&
                          !addnewAccess && (
                            <div>
                              <BSNavBarHand className="BSBillingNavBar1-hand" />
                            </div>
                          )}
                        {item?.OptionName == 'QuickAdd' && (
                          <div
                            style={{
                              pointerEvents:
                                OrderType === 'Failed' ? 'none' : 'auto',
                            }}
                          >
                            <BSNavBarQuickAdd />
                          </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 == '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' && (
                          // CartOrderDetails?.length > 0 &&
                          <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}
                          >
                            <PozoAddCustomerIcon className="BSBillingNav-icon" />
                          </Popover>
                        )}
                      </>
                    ))}
                    {FeatureAddonData?.FeatureDtls?.find(
                      (item) =>
                        item?.FeatureAddonName?.toLowerCase() === 'Weight Scale'
                    ) && (
                      <div
                        style={{
                          pointerEvents:
                            OrderType === 'Failed' ? 'none' : 'auto',
                        }}
                      >
                        <BSNavBarWeightScale />
                      </div>
                    )}
                    {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 />}

                    {!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 && <VerfiedProducts />}

                    {paymentfeataddon && (
                      <TooltipWrapper
                        title="Failed Payment"
                        isMobile={isMobile}
                      >
                        {/* PozoPaymentFailesIcon */}
                        <div
                          onClick={() => {
                            paymentFailedStatusFun();
                          }}
                          style={{ width: '1.4rem', cursor: 'pointer' }}
                        >
                          <PozoPaymentFailesIcon />
                        </div>
                      </TooltipWrapper>
                    )}
                  </>
                )}
              </div>
            </div>
          </div>
        )}
      </div>
      <div className="BSBillingnav1-threedots" onClick={NavmenuOpenClose}>
        {Navmenu ? (
          <IoMdClose size={24} color="#ff0000" />
        ) : (
          <PozoMenuIcon size={20} />
        )}
      </div>

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