import { useState, useEffect, useRef, useCallback, useMemo, lazy } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch, useSelector, shallowEqual } from 'react-redux';
import {
  changealldata,
  changeBookingType,
  changeComboRedirectionToDefaultLayoutForParking,
  changeCompoPaymentIconStatus,
  changeCustomerID,
  changeEstimateBooking,
  changeOrderCardDetails,
  changeOtherServices,
  changeReorderHoldDetails,
  changeReorderProductDetails,
  changeSelectedCustId,
  changeSelectedOption,
  GlobalBookingType,
  GlobalBookingTypeBoth,
  GlobalComboRedirectionToDefaultLayoutForParking,
  GlobalCommonPaymentOptions,
  GlobalEstimateBooking,
  GlobalFeatAddOnData,
  GlobalOrderCardDetails,
  GlobalOrderStatus,
  GlobalOrderType,
  GlobalOtherSevices,
  GlobalSelCustId,
  PreferenceData,
} from '../../../../Features/BookingScreen/BookingData/BookingData.js';
import {
  ApplicationPreferences,
  GenerateLogout,
  GlobalCompBranchData,
} from '../../../../Features/BrachLogin/BranchLogin.js';
import { useApplyOfferto_CardDetail } from '../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx';
import '../../../../Styles/BookingScreen/Components/BSNavbar/BSNavbar3.scss';

// UI Imports
import { Badge, Popconfirm, Tooltip } from 'antd';
import { AiFillHome } from 'react-icons/ai';
import {
  FaPlus,
  FaHandPaper,
  FaHeart,
  FaUserAlt,
  FaPhoneAlt,
  FaParking,
} from 'react-icons/fa';
import { CiMenuBurger } from 'react-icons/ci';
import { IoCloseOutline } from 'react-icons/io5';
import {
  RiFullscreenExitFill,
  RiFullscreenFill,
  RiPrinterFill,
} from 'react-icons/ri';
import { GiShoppingBag } from 'react-icons/gi';
const BSNavBarAddUser = lazy(
  () => import('../UtillComponents/BSNavBarAddUser.jsx')
);
const BSCustomerSelect = lazy(
  () => import('../UtillComponents/BSSelectCustomer.jsx')
);
const FeaturesFunctionalities = lazy(
  () => import('../BookingFunctionality/FeaturesFunctionalities.jsx')
);
import CustomerDisplayicon from '../UtillComponents/Pozo retail icons/PozoCustomerDisplayicon.jsx';
import {
  getUserProfile,
  userDataByUserId,
} from '../../../../Features/UserAccount/userData.js';
import {
  clearSession,
  getSession,
  sessionStore,
} from '../../../../Services/Others.js';
import {
  getTemplate,
  getTemplateData,
  StoredSessionData,
} from '../../../../Features/ThemeChange/ThemeChange.js';
import {
  CurrentTimeDisplay,
  CurrentDateDisplay,
} from '../UtillComponents/CurrentDateTimeDisplay.jsx';
import TooltipWrapper from '../../../../Components/Tooltip/Tooltip.jsx';
import { isMobile } from 'react-device-detect';
import {
  getCustomerDisplayWindow,
  setCustomerDisplayWindow,
} from '../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
import BSNavBarPreOrder from '../UtillComponents/BSNavBarPreOrder.jsx';
import {
  changepreOrder,
  changePreOrderAdditem,
  changepreOrderList,
  GlobalPreOrderPendingCount,
} from '../../../../Features/BookingScreen/PreOrder/PreOrder.js';
import PozoPreOrderIcon from '../UtillComponents/Pozo retail icons/PozoPreOrderIcon.jsx';
import { OtherServicesCardlistdata } from '../../../../Features/OtherServices/OtherServices.js';
import BSNavBarEstimate from '../UtillComponents/BSNavBarEst.jsx';
import BSNavBarWholeSale from '../UtillComponents/BSNavBarWholeSale.jsx';
import { Global_OfferStatus } from '../../../../Features/Offer/Offer.js';
import { globalholddata } from '../../../../Features/BookingScreen/HoldOption/HoldOption.js';
import BSNavBarWeightScale from '../UtillComponents/BSNavBarWeightScale.jsx';
import { TbSettingsSearch } from 'react-icons/tb';
import { DefaultModal } from '../../../../Components/Modal/DefaultModal.jsx';
import MultipleSearch from '../UtillComponents/MultipleSearch.jsx';

// Jsx Files
const BSNavBarFavItems = lazy(
  () => import('../UtillComponents/BSNavBarFavItems.jsx')
);
const BSNavBarHand = lazy(() => import('../UtillComponents/BSNavBarHand.jsx'));
const BSNavBarDragItems = lazy(
  () => import('../UtillComponents/BSNavBarDragItems.jsx')
);
const BSNavBarUserInfo = lazy(() => import('./BSNavBarUserInfo.jsx'));

const UserRelieveManager = lazy(
  () => import('../../Template/RealivingUser.jsx')
);
const BSNavbarSearchStandard = lazy(
  () => import('../UtillComponents/BSNavbarSearchStandard.jsx')
);
const BSPrinterSetting = lazy(
  () => import('../UtillComponents/BSPrinterSetting.jsx')
);
const BSNavBarTable = lazy(
  () => import('../UtillComponents/BSNavBarTable.jsx')
);
const BSMobilePrintSettings = lazy(
  () => import('../UtillComponents/BSMobilePrintSettings.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 BSNavBarAddons = lazy(
  () => import('../UtillComponents/BSNavBarAddons.jsx')
);
const BSNavBarOffer = lazy(
  () => import('../UtillComponents/BSNavBarOffer/BSNavBarOffer.jsx')
);
const BSNavBarQuickAdd = lazy(
  () => import('../UtillComponents/BSNavBarQuickAdd.jsx')
);
// Api
const subDirectory = import.meta.env.ENV_BASE_URL;
const commonUrl = import.meta.env.ENV_COMMON_BASE_URL;

const BSNavbar3 = ({ optionNames }) => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const applyOffer = useApplyOfferto_CardDetail();
  const userMenuRef = useRef(null);
  const searchInputRef = useRef(null);
  const mobileMenuRef = useRef(null);
  const SessionData = useSelector(StoredSessionData);
  const AppId = SessionData?.AppId;
  const CompId = SessionData?.CompId;
  const BranchId = SessionData?.BranchId;
  const userId = getSession('UserId');

  const [drawerOpen, setDrawerOpen] = useState({
    favourite: false,
    customer: false,
    hold: false,
    dragItem: false,
    reprint: false,
    verifyProduct: false,
    membership: false,
    wholesale: false,
  });
  const [isHoldEnable, setisisHoldEnable] = useState(false);
  const [isUserAccOpen, setIsUserAccOpen] = useState(false);
  const [quickAdd, setQuickAdd] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);

  const [isFullscreen, setIsFullscreen] = useState(false);
  const [multiple, setMultiple] = useState(false);
  const GlobEstBooking = useSelector(GlobalEstimateBooking);
  const compBranchData = useSelector(GlobalCompBranchData);
  const userProfileData = useSelector(userDataByUserId);
  const appPreferences = useSelector(ApplicationPreferences);
  const preferences = useSelector(PreferenceData);
  const orderType = useSelector(GlobalOrderType);
  const bookingType = useSelector(GlobalBookingType, shallowEqual);
  const layoutData = useSelector(getTemplateData);
  const OtherServicesglobal = useSelector(GlobalOtherSevices);
  const preOrderPendingCount = useSelector(GlobalPreOrderPendingCount);
  const comboRedirectionToDefaultLayoutForParking = useSelector(
    GlobalComboRedirectionToDefaultLayoutForParking
  );
  const Holddata = useSelector(globalholddata);
  const OrderCardDetail = useSelector(GlobalOrderCardDetails);
  const FeatureAddonData = useSelector(GlobalFeatAddOnData);
  const tableData = useSelector(GlobalOrderStatus);
  const BookingTypeBoth = useSelector(GlobalBookingTypeBoth);
  const OrderOfferStatus = useSelector(Global_OfferStatus);
  const GlobaluseOptions = useSelector(GlobalCommonPaymentOptions);
  const SelCustId = useSelector(GlobalSelCustId);

  const Estimation = preferences?.[0]?.SettingDtlDetails?.find(
    (item) => item.SettingIdName === 'Estimation'
  );
  const ScanLayoutScreen = preferences?.[0]?.SettingDtlDetails?.find(
    (item) => item.SettingIdName === 'ScanLayout'
  );
  const verifyproduct = preferences?.[0]?.SettingDtlDetails?.find(
    (item) =>
      item.SettingIdName === 'VerifyProduct' && item.SettingValue === 'Y'
  );
  const Parking = preferences?.[0]?.SettingDtlDetails?.find(
    (item) => item.SettingIdName === 'Parking' && item.SettingValue === 'Y'
  );

  const commonModulePreference = appPreferences?.find(
    (preference) => preference?.PreferredCatName === 'Common Module'
  )?.PreferenceCatDetails;
  const sportsAppPreference = commonModulePreference?.find(
    (preference) =>
      preference?.PreferredSubCatName === 'SportsApp' &&
      preference?.PreferredStatus === 'Y'
  );
  const {
    searchOption,
    reprintOption,
    quickAddOption,
    dineInOption,
    takeAwayOption,
    offerOption,
    extraChargeOption,
    holdOption,
    addCustomerOption,
  } = useMemo(() => {
    const navbarOptions = layoutData?.BookingNavbar?.[1];
    return {
      searchOption: navbarOptions?.find(
        (option) => option?.OptionName?.toLowerCase() === 'search'
      ),
      reprintOption: navbarOptions?.find(
        (option) => option?.OptionName?.toLowerCase() === 'reprint'
      ),
      quickAddOption: navbarOptions?.find(
        (option) => option?.OptionName?.toLowerCase() === 'quickadd'
      ),
      dineInOption: navbarOptions?.find(
        (option) => option?.OptionName?.toLowerCase() === 'dinein'
      ),
      takeAwayOption: navbarOptions?.find(
        (option) => option?.OptionName?.toLowerCase() === 'takeaway'
      ),
      offerOption: navbarOptions?.find(
        (option) => option?.OptionName?.toLowerCase() === 'offer'
      ),
      extraChargeOption: navbarOptions?.find(
        (option) => option?.OptionName?.toLowerCase() === 'extracharge'
      ),
      holdOption: navbarOptions?.find(
        (option) => option?.OptionName?.toLowerCase() === 'hold'
      ),
      addCustomerOption: navbarOptions?.find(
        (option) => option?.OptionName?.toLowerCase() === 'addcustomer'
      ),
    };
  }, [layoutData]);

  const [preOrderOpen, setPreOrderOpen] = useState(false);
  const [preOrderhiseandShow, setpreOrderhiseandShow] = useState(false);
  const [OtherServiceStatus, setOtherServiceStatus] = useState(false);

  // Memoized preference data
  const { dineInPreference, takeAwayPreference } = useMemo(() => {
    const bookingTypePref =
      appPreferences?.find((p) => p?.PreferredCatName === 'Booking Type')
        ?.PreferenceCatDetails || [];
    return {
      dineInPreference: bookingTypePref.find(
        (p) =>
          p?.PreferredSubCatName?.toLowerCase() === 'dine in' &&
          p?.PreferredStatus === 'Y'
      ),
      takeAwayPreference: bookingTypePref.find(
        (p) =>
          p?.PreferredSubCatName?.toLowerCase() === 'take away' &&
          p?.PreferredStatus === 'Y'
      ),
    };
  }, [appPreferences]);

  const SalesMode = preferences?.[0]?.SettingDtlDetails?.find(
    (item) => item.SettingIdName === 'Sales Mode'
  );

  const { preferenceOffer, dineIn } = useMemo(() => {
    return {
      preferenceOffer:
        preferences?.[0]?.['SettingDtlDetails']?.find(
          (item) => item.SettingIdName === 'Offer'
        )?.SettingValue === 'Y',

      dineIn: preferences?.[0]?.['SettingDtlDetails'].find(
        (item) => item.SettingIdName === 'DineIn' && item?.SettingValue === 'Y'
      ),
    };
  }, [preferences]);

  console.log(dineIn, dineInPreference, 'dineInPreference');

  const BSComboNavbar = useMemo(() => {
    const layout = optionNames?.BookingLayout?.[0];
    return layout === 'Combo1'
      ? optionNames?.BookingCombo1
      : optionNames?.BookingCombo2;
  }, [optionNames]);

  const OfferCheckedInSetup = useMemo(() => {
    return BSComboNavbar?.[1]?.some((opt) => opt.OptionName === 'Offer');
  }, [BSComboNavbar]);

  useEffect(() => {
    dispatch(getUserProfile({ UserId: userId, ActiveStatus: 'A' })).unwrap();
  }, [userId]);
  useEffect(() => {
    handleOtherData();
  }, []);
  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(() => {
    const handleClickOutside = (event) => {
      if (userMenuRef.current && !userMenuRef.current.contains(event.target)) {
        setIsUserAccOpen(false);
      }
      if (
        mobileMenuRef.current &&
        !mobileMenuRef.current.contains(event.target) &&
        !event.target.closest('.mobile-toggle-btn')
      ) {
        setIsMobileMenuOpen(false);
      }
    };
    const handleEscKey = (event) => {
      if (event.key === 'Escape') {
        setIsUserAccOpen(false);
        setIsMobileMenuOpen(false);
      }
    };
    if (isUserAccOpen || isMobileMenuOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      document.addEventListener('keydown', handleEscKey);
    }
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('keydown', handleEscKey);
    };
  }, [isUserAccOpen, isMobileMenuOpen]);

  const handleDineInNavigate = useCallback(async () => {
    navigate(`${subDirectory}sales/dine-in`);
    dispatch(changeBookingType('Dine In'));
    dispatch(changeEstimateBooking('Sales'));
    if (orderType === 'Hold') {
      dispatch(changeReorderHoldDetails({}));
      dispatch(changeReorderProductDetails([]));
      if (OfferCheckedInSetup && preferenceOffer) {
        await applyOffer([]);
      } else {
        dispatch(changeOrderCardDetails([]));
      }
    }
  }, [
    navigate,
    dispatch,
    orderType,
    OfferCheckedInSetup,
    preferenceOffer,
    applyOffer,
  ]);

  const handleTakeAway = () => dispatch(changeBookingType('TakeAway'));
  const handleUserAcc = () => setIsUserAccOpen((prev) => !prev);
  const handleHomePageNavigate = () => navigate(`${subDirectory}app-page/home`);
  const handleMobileMenuToggle = () => setIsMobileMenuOpen((prev) => !prev);

  const handleFullscreen = 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);
      }
    }
  };

  const renderWithTooltip = (element, title, placement = 'bottom') => (
    <Tooltip title={title} placement={placement}>
      {element}
    </Tooltip>
  );
  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 handleQuickAddClose = async () => {
    dispatch(changeCompoPaymentIconStatus(false));
    setQuickAdd(false);
  };

  const handleQuickAddOpen = async () => {
    dispatch(changeCompoPaymentIconStatus(true));
    setQuickAdd(true);
  };

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

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

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

  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 preOrderHandleclose = async () => {
    setPreOrderOpen(false);
    await dispatch(changepreOrder(false));
    setpreOrderhiseandShow(false);
  };

  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 handleotherservices = async () => {
    if (OtherServicesglobal && comboRedirectionToDefaultLayoutForParking) {
      dispatch(changeComboRedirectionToDefaultLayoutForParking(false));
      await dispatch(getTemplate({ CompId, BranchId, AppId })).unwrap();
    }
    dispatch(changeOtherServices(!OtherServicesglobal));
    dispatch(changeOrderCardDetails([]));
  };

  return (
    <>
      <div className="BSNavbar3Main">
        <div className="homeTime">
          <div className="homeIcon">
            <Popconfirm
              title="Are you sure you want to go to home page?"
              onConfirm={handleHomePageNavigate}
              okText="Yes"
              cancelText="No"
            >
              <AiFillHome color="#fff" size={24} />
            </Popconfirm>{' '}
            <div>
              {' '}
              <BranchName />
            </div>
          </div>

          {OtherServiceStatus && Parking && (
            <div
              style={{
                fontSize: '1.5rem',
                color: 'rgb(18, 146, 238)',
                position: 'sticky',
              }}
            >
              <TooltipWrapper title="Other Services" isMobile={isMobile}>
                <div onClick={handleotherservices}>
                  <FaParking
                    style={{
                      display: 'flex',
                      justifyContent: 'center',
                      cursor: 'pointer',
                    }}
                    fill={OtherServicesglobal === true ? '#52C41A' : '#1292EE'}
                  />
                </div>
              </TooltipWrapper>
            </div>
          )}
        </div>

        {!sportsAppPreference && searchOption && (
          <div
            className="BsnavbarSearchMain"
            onClick={() => searchInputRef.current?.focus()}
          >
            <BSNavbarSearchStandard inputRef={searchInputRef} />
            {/* Multiple search  */}
            <Tooltip title={'Multiple Search'}>
              <div className="MultiSearchIconDiv3">
                <TbSettingsSearch onClick={() => setMultiple(true)} />
              </div>
            </Tooltip>
          </div>
        )}

        {/* Customer Select - Always visible */}
        {addCustomerOption && (
          <div className="DropDownsCustomer always-visible">
            <BSCustomerSelect
              placeholder="Customer Name"
              TopName={'navbar-top'}
            />
            {addCustomerOption && (
              <span>
                {renderWithTooltip(<BSNavBarAddUser />, 'Add Customer')}
              </span>
            )}
          </div>
        )}

        {offerOption && (
          <div className="standard-extra-charges">
            {GlobEstBooking !== 'OvrAllEst' &&
              GlobEstBooking !== 'ParEst' &&
              GlobEstBooking === 'Sales' &&
              preferences?.[0]?.['SettingDtlDetails']?.find(
                (item) => item.SettingIdName === 'Offer'
              )?.SettingValue === 'Y' && (
                <div
                  style={{
                    pointerEvents: orderType === 'Failed' ? 'none' : 'auto',
                  }}
                >
                  <BSNavBarOffer />
                </div>
              )}
          </div>
        )}
        {extraChargeOption && !sportsAppPreference && (
          <div
            className="standard-extra-charges"
            style={{
              pointerEvents: orderType === 'Failed' ? 'none' : 'auto',
            }}
          >
            <BSNavBarAddons />
          </div>
        )}

        {!sportsAppPreference && quickAddOption && (
          <div
            className="standard-extra-charges"
            style={{
              pointerEvents: orderType === 'Failed' ? 'none' : 'auto',
            }}
          >
            <BSNavBarQuickAdd />
          </div>
        )}
        {/* Desktop CustomerActions */}
        <div className="CustomerActions desktop-only">
          {dineInPreference && dineIn && dineInOption && (
            <div className="mobile-action-item">
              <BSNavBarTable />
            </div>
          )}

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

          {!sportsAppPreference && (
            <div className="FaTruckIconFavItem" style={{ padding: '4px 6px' }}>
              {renderWithTooltip(
                <BSNavBarFavItems
                  size={41}
                  className="FaTruckIcon"
                  fill={'#fff'}
                />,
                'Favourites'
              )}
            </div>
          )}
          {holdOption &&
            ((bookingType !== 'Dine In' && OrderCardDetail?.length != 0) ||
              (bookingType !== 'Dine In' &&
                Holddata?.length > 0 &&
                OrderCardDetail?.length == 0)) &&
            isHoldEnable &&
            renderWithTooltip(
              <BSNavBarHand
                ComponentIcon={FaHandPaper}
                iconSize={50}
                iconClassName="FaTruckIconHold"
              />,
              'Hold'
            )}
          {ScanLayoutScreen?.SettingValue === 'Y' && <BSScanTemplate />}
          <div
            className="FaTruckIconDragItems"
            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}
                className="BSBillingNavBar1-AllIcons"
                style={{ width: '1.3rem', margin: '10px', cursor: 'pointer' }}
              >
                <CustomerDisplayicon />
              </div>
            </TooltipWrapper>
          )}
          <TooltipWrapper title="Reprint (Alt+R)" isMobile={isMobile}>
            {reprintOption && (
              <div
                style={{
                  pointerEvents: orderType === 'Failed' ? 'none' : 'auto',
                  color: '#6b7280',
                }}
              >
                <div className="FaTruckIconreprint">
                  <BSPrinterSetting IconComponent={RiPrinterFill} />
                </div>
              </div>
            )}
          </TooltipWrapper>

          {verifyproduct && (
            <div style={{ color: 'green' }}>
              <TooltipWrapper
                title={
                  sportsAppPreference
                    ? 'Booking Verification'
                    : 'Verified Products'
                }
                isMobile={isMobile}
              >
                <div>
                  <VerfiedProducts />
                </div>
              </TooltipWrapper>
            </div>
          )}
        </div>
        {isMobile && (
          <div
            style={{
              color: '#6b7280',
            }}
          >
            <BSMobilePrintSettings />
          </div>
        )}

        <div className="userDates">
          <div className="datesNewtimedate">
            <CurrentDateDisplay />
            <CurrentTimeDisplay />
          </div>

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

          <div className="BsNavbarUser">
            <FaUserAlt size={18} onClick={handleUserAcc} />
            <BSNavBarUserInfo
              isOpen={isUserAccOpen}
              divRef={userMenuRef}
              CompBranchData={compBranchData}
              BacktoLogin={handleBackToLogin}
              userProfileData={userProfileData}
              handleEditProfile={handleEditProfile}
              UserRelieveManager={<UserRelieveManager />}
              Logout={Logout}
            />
          </div>

          {/* Mobile Toggle Button */}
          <div className="mobile-toggle-btn" onClick={handleMobileMenuToggle}>
            <CiMenuBurger size={20} color="#fff" />
          </div>
        </div>
      </div>

      {/* Mobile Menu */}
      <div
        className={`mobile-menu ${isMobileMenuOpen ? 'open' : ''}`}
        ref={mobileMenuRef}
      >
        <div className="mobile-menu-content">
          <div
            className="mobile-toggle-btn"
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'flex-end',
              width: '100%',
              cursor: 'pointer',
              padding: '2px 0',
            }}
            onClick={handleMobileMenuToggle}
          >
            {isMobileMenuOpen ? (
              <IoCloseOutline size={25} strokeWidth={2} color="#fff" />
            ) : (
              <CiMenuBurger height={20} size={20} color="#fff" />
            )}
          </div>
          <div className="mobile-customer-actions">
            {takeAwayPreference && takeAwayOption && (
              <div className="mobile-action-item" onClick={handleTakeAway}>
                <GiShoppingBag
                  size={30}
                  color={bookingType === 'TakeAway' ? '#52c41a' : '#6b7280'}
                />
                <div>Take Away</div>
              </div>
            )}
            {dineInPreference && dineIn && dineInOption && (
              <div className="mobile-action-item">
                <BSNavBarTable width="30" height="30" />
                <div>{bookingType}</div>
              </div>
            )}
            {!sportsAppPreference && (
              <div
                className="mobile-action-item"
                onClick={() =>
                  setDrawerOpen((prev) => ({
                    ...prev,
                    favourite: !prev?.favourite,
                  }))
                }
              >
                <BSNavBarFavItems
                  size={30}
                  drawerOpen={drawerOpen?.favourite}
                  fill={'#fff'}
                />
                <div>Favourite</div>
              </div>
            )}
            {addCustomerOption && (
              <div
                className="mobile-action-item"
                onClick={() =>
                  setDrawerOpen((prev) => ({
                    ...prev,
                    customer: !prev?.customer,
                  }))
                }
              >
                <BSNavBarAddUser
                  drawerOpen={drawerOpen?.customer}
                  setDrawerOpen={setDrawerOpen}
                />
                <div>Add Customer</div>
              </div>
            )}
            {quickAddOption && (
              <div className="mobile-action-item" onClick={handleQuickAddOpen}>
                {renderWithTooltip(<FaPlus size={30} />, 'Quick Add', 'top')}
                <div>Quick Add</div>
              </div>
            )}
            {holdOption &&
              ((bookingType !== 'Dine In' && OrderCardDetail?.length != 0) ||
                (bookingType !== 'Dine In' &&
                  Holddata?.length > 0 &&
                  isHoldEnable &&
                  OrderCardDetail?.length == 0)) && (
                <div
                  className="mobile-action-item"
                  onClick={() =>
                    setDrawerOpen((prev) => ({ ...prev, hold: !prev?.hold }))
                  }
                >
                  <BSNavBarHand
                    ComponentIcon={FaHandPaper}
                    iconSize={20}
                    style={{ width: '15px' }}
                    drawerOpen={drawerOpen}
                    setDrawerOpen={setDrawerOpen}
                  />
                  <div>Hold</div>
                </div>
              )}
            {ScanLayoutScreen?.SettingValue === 'Y' && <BSScanTemplate />}
            <div
              className="mobile-action-item"
              onClick={(e) => {
                if (e.target === e.currentTarget) {
                  setDrawerOpen((prev) => ({
                    ...prev,
                    dragItem: !prev?.dragItem,
                  }));
                }
              }}
            >
              <BSNavBarDragItems
                drawerOpen={drawerOpen}
                setDrawerOpen={setDrawerOpen}
              />
              <div
                onClick={(e) => {
                  if (e.target === e.currentTarget) {
                    setDrawerOpen((prev) => ({
                      ...prev,
                      dragItem: !prev?.dragItem,
                    }));
                  }
                }}
              >
                Drag Item
              </div>
            </div>
            {reprintOption && (
              <div
                className="mobile-action-item"
                onClick={(e) => {
                  if (e.target === e.currentTarget) {
                    setDrawerOpen((prev) => ({
                      ...prev,
                      reprint: !prev?.reprint,
                    }));
                  }
                }}
              >
                <BSPrinterSetting
                  IconComponent={RiPrinterFill}
                  drawerOpen={drawerOpen}
                  setDrawerOpen={setDrawerOpen}
                />
                <div
                  onClick={(e) => {
                    if (e.target === e.currentTarget) {
                      setDrawerOpen((prev) => ({
                        ...prev,
                        reprint: !prev?.reprint,
                      }));
                    }
                  }}
                >
                  Re-Print
                </div>
              </div>
            )}
            {verifyproduct && (
              <div
                className="mobile-action-item"
                onClick={(e) => {
                  if (e.target === e.currentTarget) {
                    setDrawerOpen((prev) => ({
                      ...prev,
                      verifyProduct: !prev?.verifyProduct,
                    }));
                  }
                }}
              >
                <TooltipWrapper title={'Verfied Products'} isMobile={isMobile}>
                  <div>
                    <VerfiedProducts
                      drawerOpen={drawerOpen}
                      setDrawerOpen={setDrawerOpen}
                    />
                  </div>
                </TooltipWrapper>

                <div
                  onClick={(e) => {
                    if (e.target === e.currentTarget) {
                      setDrawerOpen((prev) => ({
                        ...prev,
                        verifyProduct: !prev?.verifyProduct,
                      }));
                    }
                  }}
                >
                  Verify Product
                </div>
              </div>
            )}

            {sportsAppPreference && (
              <div
                className="mobile-action-item"
                onClick={(e) => {
                  if (e.target === e.currentTarget) {
                    setDrawerOpen((prev) => ({
                      ...prev,
                      membership: !prev?.membership,
                    }));
                  }
                }}
              >
                <BSMembership
                  drawerOpen={drawerOpen}
                  setDrawerOpen={setDrawerOpen}
                />
                <div
                  onClick={(e) => {
                    if (e.target === e.currentTarget) {
                      setDrawerOpen((prev) => ({
                        ...prev,
                        membership: !prev?.membership,
                      }));
                    }
                  }}
                >
                  Membership
                </div>
              </div>
            )}

            {!OtherServicesglobal && (
              <>
                {Estimation?.SettingValue === 'Y' &&
                  bookingType !== 'Dine In' &&
                  !BookingTypeBoth &&
                  !OrderOfferStatus && (
                    <div
                      className="BSBillingNavBar2-AllIcons"
                      style={{
                        pointerEvents: orderType === 'Failed' ? 'none' : 'auto',
                      }}
                    >
                      <div className="mobile-action-item" onClick={() => {}}>
                        <BSNavBarEstimate />
                        <div>Estimate</div>
                      </div>
                    </div>
                  )}
              </>
            )}
            {SalesMode?.SettingValue === 'Y' && !OtherServicesglobal && (
              <div
                className="mobile-action-item"
                onClick={(e) => {
                  if (e.target === e.currentTarget) {
                    setDrawerOpen((prev) => ({
                      ...prev,
                      wholesale: !prev?.wholesale,
                    }));
                  }
                }}
              >
                <BSNavBarWholeSale
                  drawerOpen={drawerOpen}
                  setDrawerOpen={setDrawerOpen}
                />
                <div
                  onClick={(e) => {
                    if (e.target === e.currentTarget) {
                      setDrawerOpen((prev) => ({
                        ...prev,
                        wholesale: !prev?.wholesale,
                      }));
                    }
                  }}
                >
                  WholeSale
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      <DefaultModal
        open={multiple}
        title="Multiple Search"
        footer={false}
        width={350}
        handleCancel={() => setMultiple(false)}
        destroyOnClose={true}
        children={
          <>
            <MultipleSearch close={setMultiple} />
          </>
        }
      />
      {quickAdd && (
        <FeaturesFunctionalities
          handleQuickAddCancel={handleQuickAddClose}
          QuickAdd={quickAdd}
        />
      )}
    </>
  );
};

export default BSNavbar3;
