import React, { lazy, Suspense, useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { TiLocation } from 'react-icons/ti';
import { BsFillPersonFill } from 'react-icons/bs';
import { PiStorefrontFill } from 'react-icons/pi';
import { BiSolidDashboard, BiSolidReport } from 'react-icons/bi';
import { FaUserLarge } from 'react-icons/fa6';
import { BiSolidPhoneCall } from 'react-icons/bi';
import { CgMenuGridR } from 'react-icons/cg';
import { MdTableChart } from 'react-icons/md';
import { MdEdit } from 'react-icons/md';
import MyTime, { DateDisplay, TimeDisplay } from './BSTimer.jsx';
import '../../../../Styles/BookingScreen/Template/BSLayout7/BSC1NavBar.scss';
import {
  GenerateLogout,
  getBranchDetail,
  getCompBranchData,
} from '../../../../Features/BrachLogin/BranchLogin.js';
import { clearSession, sessionStore } from '../../../../Services/Others';
import PozoHomeIcon from '../UtillComponents/Pozo retail icons/PozoHomeIcon.jsx';
import { GlobalCompBranchData } from '../../../../Features/BrachLogin/BranchLogin.js';
import BSPrinterSetting from '../UtillComponents/BSPrinterSetting.jsx';
import { isMobile } from 'react-device-detect';
import { FaDisplay } from 'react-icons/fa6';
import {
  GlobalFeatAddOnData,
  PreferenceData,
} from '../../../../Features/BookingScreen/BookingData/BookingData.js';
import { setCustomerDisplayWindow } from '../../../../Features/customerDisplayWindow/customerDisplayWindow';
import TooltipWrapper from '../../../../Components/Tooltip/Tooltip';
import { userDataByUserId } from '../../../../Features/UserAccount/userData.js';
import { RiFullscreenExitFill, RiFullscreenFill } from 'react-icons/ri';
import { Popconfirm, Tooltip } from 'antd';
import { FaCaretDown } from 'react-icons/fa';
const UserRelieveManager = lazy(
  () => import('../../Template/RealivingUser.jsx')
);

const BSNavBarUserInfo = lazy(() => import('../BSNavbar/BSNavBarUserInfo.jsx'));

const BSScanTemplate = lazy(
  () => import('../UtillComponents/BSScanTemplate.jsx')
);

const BSPrinterSetting = lazy(
  () => import('../UtillComponents/BSPrinterSetting.jsx')
);
const subDirectory = import.meta.env.ENV_BASE_URL;
const commonUrl = import.meta.env.ENV_COMMON_BASE_URL;
const BSC1NavBar = (props) => {
  const divRef = useRef(null);

  const navigate = useNavigate();
  const dispatch = useDispatch();
  const AppId = props?.SessionData?.AppId;
  const CompId = props?.SessionData?.CompId;
  const BranchId = props?.SessionData?.BranchId;
  const UserId = props?.SessionData?.UserId;
  const UserType = props?.SessionData?.UserType;
  const [formattedDate, setFormattedDate] = useState('');
  const [isAccOpen, setAccIsOpen] = useState(false);
  const [menu, setMenu] = useState(false);
  const [branchName, setBranchName] = useState('Guest');
  const [BranchCity, setBranchCity] = useState();
  const CompBranchData = useSelector(GlobalCompBranchData);
  const FeatureAddonData = useSelector(GlobalFeatAddOnData);
  const preferenceDatas = useSelector(PreferenceData);
  const [isFullscreen, setIsFullscreen] = useState(false);

  // const [FeatureAddonData, setFeatureAddonData] = useState([]);
  const userProfileData = useSelector(userDataByUserId);
  console.log('userProfileData', userProfileData);
  const handleHome = () => {
    navigate(`${subDirectory}app-page/home`);
  };

  const ScanLayoutScreen = preferenceDatas?.[0]?.SettingDtlDetails?.find(
    (item) => item.SettingIdName === 'ScanLayout'
  );

  useEffect(() => {
    const d = new Date();
    const options = { weekday: 'short', day: '2-digit', month: 'long' };
    const formatted = d.toLocaleDateString('en-GB', options);
    setFormattedDate(formatted);
    fetchBranchDetailData();
    fetchBranchData();
    // if (UserType !== 'Super Admin' && UserType !== 'Super Admin User') {
    //   getFeatureAddonData();
    // }
  }, []);
  const fetchBranchDetailData = async () => {
    const response = await dispatch(
      getBranchDetail({ BrId: BranchId })
    ).unwrap();
    if (response?.data?.statusCode === 1) {
      setBranchName(response?.data?.data?.[0]?.BrName);
      setBranchCity(response?.data?.data?.[0]?.City);
    }
  };
  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 UserAcc = () => {
    setAccIsOpen(!isAccOpen);
  };
  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 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 handleEditProfile = async () => {
    navigate(`${subDirectory}app-page/redirect-userprofile`);
  };
  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);
      }
    }
  };

  return (
    <Suspense fallback={<div>Loading...</div>}>
      <>
        <div
          className="BSC1NavBar-Container"
          style={{
            // backgroundColor:
            //   BSComboData?.BookingLayout?.[0] === 'Combo1'
            //     ? '#645CAA'
            //     : '#08A7B8',
            background: 'linear-gradient(to bottom right, #1e2536, #2a3447)',
          }}
        >
          <div className="BSC1NavBar-div1">
            <div className="BSC1NavBar-manu">
              <Popconfirm
                title="Are you sure you want to go to home?"
                onConfirm={handleHome}
                okText="Yes"
                cancelText="No"
              >
                <PozoHomeIcon
                  style={{ color: '#1292EE', fontSize: '30px' }}
                  className="BSC1NavBar-manu-icon"
                />
              </Popconfirm>{' '}
              <div
                className={`BSC1NavBar-manu-content ${menu ? 'BSC1NavBar-manu-menu' : ''}`}
              >
                <div className="BSC1NavBar-manu-div">
                  <TooltipWrapper
                    placement="right"
                    title="DashBoard"
                    isMobile={isMobile}
                  >
                    <BiSolidDashboard className="BSC1Nav-menu-icon" />
                  </TooltipWrapper>

                  <TooltipWrapper
                    placement="right"
                    title="Booking / Sale"
                    isMobile={isMobile}
                  >
                    <CgMenuGridR className="BSC1Nav-menu-icon" />
                  </TooltipWrapper>

                  <TooltipWrapper
                    placement="right"
                    title="TableBooking"
                    isMobile={isMobile}
                  >
                    <MdTableChart className="BSC1Nav-menu-icon" />
                  </TooltipWrapper>

                  <TooltipWrapper
                    placement="right"
                    title="Report"
                    isMobile={isMobile}
                  >
                    <BiSolidReport className="BSC1Nav-menu-icon" />
                  </TooltipWrapper>
                </div>
              </div>
            </div>

            <div className="BSC1NavBar-name">
              {/* <PiStorefrontFill className="BSC1NavBar-name-icon" /> */}
              <TooltipWrapper placement="bottom" title={branchName}>
                <span className="BSC1NavBar-ellipsisname">
                  {branchName}
                </span>{' '}
              </TooltipWrapper>
              {BranchCity && (
                <span className="BSC1NavBar-location">
                  {' '}
                  <TiLocation className="BSC1NavBar-location-icon" />
                  <span className="BSC1NavBar-name-ellipsis">
                    {BranchCity}
                  </span>{' '}
                </span>
              )}
            </div>

            <div className="BSC1NavBar-name">
              {ScanLayoutScreen?.SettingValue === 'Y' && (
                <span className="BSC1NavBarlocation">
                  <BSScanTemplate />
                </span>
              )}
            </div>

            <div></div>
          </div>
          <div className="BSC1NavBar-div2">
            <div className="BSC1NavBar-date">
              {/* {formattedDate} */}
              <TimeDisplay />

              <DateDisplay />
            </div>

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

            {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 color="#1292ee" size={18} />
                </div>
              </TooltipWrapper>
            )}

            {!isMobile && (
              <div className="comboPrinterIcon">
                <BSPrinterSetting />
              </div>
            )}

            <div className="BSC1NavBar-person" onClick={UserAcc}>
              <TooltipWrapper title="Account " isMobile={isMobile}>
                <div className="myProfileIconDrDown">
                  <BsFillPersonFill className="BSC1NavBar-person-icon" />
                  <FaCaretDown />
                </div>
              </TooltipWrapper>
            </div>
            {isAccOpen && (
              <BSNavBarUserInfo
                isOpen={isAccOpen}
                divRef={divRef}
                CompBranchData={CompBranchData}
                BacktoLogin={BacktoLogin}
                userProfileData={userProfileData}
                handleEditProfile={handleEditProfile}
                UserRelieveManager={<UserRelieveManager />}
                Logout={Logout}
              />
            )}
          </div>
        </div>
      </>
    </Suspense>
  );
};

export default BSC1NavBar;
