import React, { useEffect, useState, useCallback, lazy, Suspense } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { isMobile } from 'react-device-detect';
import moment from 'moment';
import { Tooltip, Badge, Popconfirm } from 'antd';
const BSNavbar1 = lazy(() => import('../../Components/BSNavbar/BSNavbar1'));

const BSNavbar2 = lazy(() => import('../../Components/BSNavbar/BSNavbar2'));

const BSBillingTable1 = lazy(
  () => import('../../Components/BSBillingTables/BSBillingTable1/BSBTOverall1')
);

const BSBillingTable2 = lazy(
  () =>
    import('../../Components/BSBillingTables/BSBillingTable2/BSBillingTable2')
);

const BSBillingTable3 = lazy(
  () =>
    import('../../Components/BSBillingTables/BSBillingTable3/BSBillingTable3overall')
);

const BSBillingTable4 = lazy(
  () =>
    import('../../Components/BSBillingTables/BSBillingTable4/BSBillingTable4Full')
);

const BSBillingTable5 = lazy(
  () =>
    import('../../Components/BSBillingTables/BSBillingTable5/BSBillingTable5')
);

const BSBillingTable6 = lazy(
  () => import('../../Components/BSBillingTables/BSBillingTable6/BSBTOverall6')
);

const BSBillingTable7 = lazy(
  () =>
    import('../../Components/BSBillingTables/BSBillingTable7/BSBillingTable7Overall.jsx')
);
import BSItemCard from '../../Components/BSItemCards/BSItemCard';
const CategoryHorizontal = lazy(
  () => import('../../Components/BSCategories/BSCategoryHorizontal')
);
import { dynamicComponentProps } from '../DynamicComponentProps.js';
import {
  GlobalPricingAppPricingName,
  getTemplateData,
  SelectedGlobalCardColorDetail,
  SelectedGlobalCatgColorDetail,
  SelectedGlobalLayoutColorDetail,
  StoredSessionData,
  SelectedGlobalBillingColorDetail,
} from '../../../../Features/ThemeChange/ThemeChange';
import '../../../../Styles/BookingScreen/Template/BSLayout6/BSLayout6.scss';
import '../../../../Styles/BookingScreen/Components/BSBillingTables/BSBillingTable4/BSBillingTable4.scss';
import { settingDataSelector } from '../../../../Features/PreferenceMaster/PreferenceMaster.js';
import {
  GlobalSalesDetailData,
  getSalesDetailData,
  GlobalCombosearch,
  GlobalOrderCardDetails,
  GlobalOrderStatus,
  PreferenceData,
  GlobalAppExpDateData,
  GlobalBtoBQuickProductTransfer,
  GlobalOtherSevices,
} from '../../../../Features/BookingScreen/BookingData/BookingData.js';
import { ArrowUpOutlined } from '@ant-design/icons';
import { getSession } from '../../../../Services/Others.js';
import BSKioskCounterPayment from '../../Components/UtillComponents/BSKioskCounterPayment.jsx';
import {
  getKioskDatas,
  globalKioskSalesCount,
} from '../../../../Features/Kiosk/kiosk.js';
import PozoKioskIcon from '../../Components/UtillComponents/Pozo retail icons/PozoKioskIcon.jsx';
import {
  GLobalSadminUserPin,
  putSadminUserExit,
  checkSession,
  ApplicationPreferences,
} from '../../../../Features/BrachLogin/BranchLogin';
import { Messages } from '../../../../Components/Notifications/Messages.jsx';
import SAdminUserNotification from '../../Components/BookingFunctionality/SAdminUserNotification.jsx';
import SalesCountComponent from '../SalesCountComponent.jsx';
import {
  getBookingStatus,
  GlobalBookingStatus,
} from '../../../../Features/Payment/PaymentReceivedRetail/PaymentReceivedRetail.js';
import { PutBookingClose } from '../../../../Features/BookingScreen/RetailBookingClose.js';
import TooltipWrapper from '../../../../Components/Tooltip/Tooltip.jsx';
import BookingCloseIcon from '../../Components/UtillComponents/BookingCloseIcon.jsx';
import RetailBookingClosing from '../RetailBookingClose.jsx';
const ListOfSalesInvoices = lazy(
  () =>
    import('../../Components/BSBillingTables/ListofInvoices/ListOfSalesInvoices.jsx')
);
const BSEwayBillicon = lazy(
  () => import('../../Components/UtillComponents/BSEwayBillicon.jsx')
);
const BSComboItemCard = lazy(
  () => import('../../Components/BSItemCards/BSComboItemCard.jsx')
);
const BranchTransferComponent = lazy(
  () =>
    import('../../Components/UtillComponents/BSQuickBranchToBranchTransferComponent.jsx')
);
const BSExpireProductsList = lazy(
  () => import('../../Components/UtillComponents/BSExpireProductsList.jsx')
);

import BSOtherServiceItemCard from '../../Components/BSItemCards/BSOtherServiceItemCard.jsx';
import BSOtherServicesHorizontalcat from '../../Components/BSCategories/BSOtherServicesHorizontalcat';
import BSNavbar3 from '../../Components/BSNavbar/BSNavbar3.jsx';
import SalesCountForStandard from '../SalesCountForStandard.jsx';
import StandardTable from '../../Components/BSBillingTables/StandardTable/StandardTable.jsx';
import ComboSalesBillTable from '../../Components/BSBillingTables/ComboSalesBillTable/ComboSalesBillTable.jsx';
import PlanExpireNotification from '../PlanExpireNotification.jsx';
import CardSkeleton from '../../../../Components/Skeleton/CardSkeleton.jsx';
const BSLayout6 = () => {
  const dispatch = useDispatch();
  const { action, selectedProducts } = useSelector(
    GlobalBtoBQuickProductTransfer
  );
  const BSLayout6Data = useSelector(getTemplateData);
  const SettingDataSelector = useSelector(PreferenceData);
  const GlobalsalesDetailData = useSelector(GlobalSalesDetailData);
  const GlobalLayoutColorDetail = useSelector(SelectedGlobalLayoutColorDetail);
  const SelectedCatgColor = useSelector(SelectedGlobalCatgColorDetail);
  const SelectedCardColor = useSelector(SelectedGlobalCardColorDetail);
  const Comboglobal = useSelector(GlobalCombosearch);
  const SessionData = useSelector(StoredSessionData);
  const badgeCount = useSelector(globalKioskSalesCount);
  const OrderStatus = useSelector(GlobalOrderStatus);
  const BookingStatus = useSelector(GlobalBookingStatus);
  const OtherServicesglobal = useSelector(GlobalOtherSevices);
  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 CheckBookingStatus =
    BookingStatus?.find((item) => item.ScreenType === 'Booking')
      ?.ScreenStatus ?? 'Open';
  const [BookingModalOpen, setBookingModalOpen] = useState(false);
  const [connectingState, setConnectingState] = useState({});
  const [Kioskopen, setKioskopen] = useState(false);
  const AppExpDate = useSelector(GlobalAppExpDateData);
  const [screenHeight, setScreenHeight] = useState(window?.innerHeight);
  // const [AppExpDate, setAppExpDate] = useState(0);
  const [count, setcount] = useState(0);
  const BookingNavbar = BSLayout6Data?.BookingNavbar?.[0];
  const BookingCategory = BSLayout6Data?.BookingCategory;
  const BookingCard = BSLayout6Data?.BookingCard;
  const BookingBilling = BSLayout6Data?.BookingBilling?.[0];
  const AppName = SessionData?.AppName;
  const AppId = SessionData?.AppId;
  const CompId = SessionData?.CompId;
  const BranchId = SessionData?.BranchId;
  const UserId = SessionData?.UserId;
  const UserType = SessionData?.UserType;
  const [ListOfInvoices, setListOfInvoices] = useState(false);

  const DineInAccess = SettingDataSelector?.[0]?.SettingDtlDetails.filter(
    (i) => i.SettingIdName === 'DineIn'
  )?.[0];

  const currentDateValue = moment().format('YYYY-MM-DD HH:mm:ss');
  const PricingAppPricingName = useSelector(GlobalPricingAppPricingName);
  const SAdminuserPin = useSelector(GLobalSadminUserPin);

  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [popOverOpen, setPopOverOpen] = useState(false);

  useEffect(() => {
    fetchAmount();
    if (
      SessionData?.FeatureAddonData?.FeatureDtls?.find(
        (item) => item?.FeatureAddonName?.toLowerCase() === 'kiosk sales'
      )
    ) {
      fetchKioskDatas();
    }
  }, [SessionData]);

  useEffect(() => {
    if (AppId && CompId && BranchId && UserId) {
      fetchBookingStatus();
    }
  }, [AppId, CompId, BranchId, UserId]);
  const OpenListOfInvoices = () => {
    setListOfInvoices(true);
  };
  const handleInvoiceClose = () => {
    setListOfInvoices(false);
  };
  const fetchKioskDatas = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      UserId: 0,
    };
    await dispatch(getKioskDatas(data));
  };

  const fetchAmount = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      UserId: UserId,
      FromDate: currentDateValue,
      ToDate: currentDateValue,
    };

    await dispatch(getSalesDetailData(data)).unwrap();
  };

  let containerHeight = isMobile
    ? AppExpDate?.RemainingDays <= 7 ||
      AppExpDate?.PlanType?.toLowerCase() === 'extend'
      ? '577px'
      : '595px'
    : (UserType != 'Super Admin' &&
          UserType != 'Super Admin User' &&
          AppExpDate?.RemainingDays <= 7) ||
        AppExpDate?.PlanType?.toLowerCase() === 'extend'
      ? '96vh'
      : '99vh';

  useEffect(() => {
    function handleResize() {
      setScreenHeight(window.innerHeight);
    }

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  const openModalKiosk = () => {
    setKioskopen(true);
  };

  const closeModalKiosk = () => {
    setKioskopen(false);
  };
  const handlePopOverOpen = () => {
    setPopOverOpen(!popOverOpen);
  };
  const handleSupportUser = async () => {
    let response = await dispatch(
      putSadminUserExit({
        AppId: AppId,
        CompId: CompId,
        BranchId: BranchId,
        UserId: UserId,
        UpdatedBy: UserId,
      })
    ).unwrap();
    if (response?.data?.statusCode == 1) {
      setMessageData('success');
      setMessageType(response?.data?.data);
      setPopOverOpen(false);
      const UserId = getSession('UserId');
      const sessionId = getSession('SessionId');
      await dispatch(checkSession({ UserId, sessionId })).unwrap();
    } else {
      setMessageData('error');
      setMessageType(response?.data?.data);
    }
  };
  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);
  const fetchBookingStatus = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      UserId: UserId,
    };
    await dispatch(getBookingStatus(data));
  };
  const BookingOpenFun = async (status) => {
    let Postdata = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
      UserId: UserId,
      ScreenType: 'Booking',
      ScreenStatus: status,
      CreatedBy: UserId,
      Date: new Date(),
    };
    let Postresponse = await dispatch(PutBookingClose(Postdata)).unwrap();
    if (Postresponse?.data?.statusCode === 1) {
      fetchBookingStatus();
    } else {
    }
  };
  const OpenBookingModal = () => {
    setBookingModalOpen(true);
  };
  const HandleBookingModalClose = () => {
    setBookingModalOpen(false);
  };
  return (
    <Suspense fallback={<CardSkeleton />}>
      <>
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        {UserType != 'Super Admin' &&
          UserType != 'Super Admin User' &&
          (AppExpDate?.RemainingDays <= 30 ||
            AppExpDate === 'undefined' ||
            AppExpDate?.PlanType?.toLowerCase() === 'extend') && (
            <PlanExpireNotification />
          )}

        <div
          className="BSLayout6-fullbody"
          style={{ height: containerHeight, overflow: 'hidden' }}
        >
          <div className="BSLayout6-fullnav">
            <div className="BSLayout6-Navbar">
              <BSNavbar1
                BookingNavbar={BookingNavbar}
                connectingState={connectingState}
                setConnectingState={setConnectingState}
              />
            </div>

            <div className="Layout-bill-container">
              <div
                className="Layout-bill-Subcontainer"
                style={{ width: OtherServicesglobal ? '10%' : '100%' }}
              >
                {UserType !== 'Employee' && (
                  <div className="pricing-name-details">
                    {PricingAppPricingName?.[0]?.PricingName +
                      ' / ' +
                      PricingAppPricingName?.[0]?.Type}
                  </div>
                )}
                {!OtherServicesglobal && (
                  <SalesCountComponent
                    DineInAccess={DineInAccess}
                    GlobalsalesDetailData={GlobalsalesDetailData}
                    BookingNavbar={BookingNavbar}
                  />
                )}
                {!OtherServicesglobal &&
                  SessionData?.FeatureAddonData?.FeatureDtls?.find(
                    (item) =>
                      item?.FeatureAddonName?.toLowerCase() === 'kiosk sales'
                  ) &&
                  !sportsAppPreference && (
                    <div
                      style={{
                        pointerEvents: OrderStatus > 0 ? 'none' : 'auto',
                        opacity: OrderStatus > 0 ? 0.5 : 1,
                      }}
                    >
                      <Tooltip title={'Kiosk Sales'}>
                        {''}
                        <Badge
                          count={badgeCount}
                          offset={[-10, 3]}
                          size="small"
                        >
                          <PozoKioskIcon
                            onClick={() => openModalKiosk()}
                            style={{ cursor: 'pointer', fontSize: '1.5rem' }}
                            className="iconsize"
                          />
                        </Badge>
                      </Tooltip>
                    </div>
                  )}
                {!OtherServicesglobal && (
                  <TooltipWrapper
                    title={'Low Stock Alerts'}
                    isMobile={isMobile}
                  >
                    {' '}
                    <BSExpireProductsList />
                  </TooltipWrapper>
                )}
                {!OtherServicesglobal && Kioskopen && (
                  <BSKioskCounterPayment
                    Kioskopen={Kioskopen}
                    closeKioskModal={closeModalKiosk}
                  />
                )}
                {SAdminuserPin?.length > 0 &&
                  UserType != 'Super Admin User' && (
                    <div>
                      <SAdminUserNotification
                        SAdminuserPin={SAdminuserPin}
                        popOverOpen={popOverOpen}
                        handleSupportUser={handleSupportUser}
                        handlePopOverOpen={handlePopOverOpen}
                      />
                    </div>
                  )}
                {!OtherServicesglobal && (
                  <>
                    {' '}
                    {CheckBookingStatus == 'Open' ? (
                      <div style={{ marginLeft: '10px' }}>
                        <TooltipWrapper
                          title={'Booking Close'}
                          isMobile={isMobile}
                        >
                          {' '}
                          <BookingCloseIcon
                            onClick={OpenBookingModal}
                            bgFill={'#52c41a'}
                            style={{
                              fontSize: '16px',
                              marginTop: '4px',
                              color: '#52c41a',
                              cursor: 'pointer',
                            }}
                          />
                          {/* <button className="BookingCloseButton"
                                        >Booking Close</button> */}
                        </TooltipWrapper>
                      </div>
                    ) : (
                      <div style={{ marginLeft: '10px' }}>
                        <TooltipWrapper
                          title="Booking Open"
                          isMobile={isMobile}
                        >
                          <Popconfirm
                            placement="leftTop"
                            title="Booking Open"
                            description="Are you sure you want to Open the sales?"
                            okText="Yes"
                            cancelText="No"
                            onConfirm={() => BookingOpenFun('Open')}
                          >
                            <span>
                              <BookingCloseIcon
                                bgFill="red"
                                style={{
                                  fontSize: '16px',
                                  marginTop: '4px',
                                  color: '#52c41a',
                                  cursor: 'pointer',
                                }}
                              />
                            </span>
                          </Popconfirm>
                        </TooltipWrapper>
                      </div>
                    )}
                  </>
                )}
                {!OtherServicesglobal && (
                  <div style={{ marginLeft: '10px' }}>
                    <TooltipWrapper title={'E-way Bill'} isMobile={isMobile}>
                      {''}
                      <BSEwayBillicon
                        style={{ cursor: 'pointer', marginTop: '5px' }}
                        onClick={OpenListOfInvoices}
                      />
                    </TooltipWrapper>
                  </div>
                )}
              </div>
            </div>

            <div
              className="BSLayout6-category-div"
              style={{
                backgroundColor: SelectedCatgColor?.['OverallBackgroundColor'],
              }}
            >
              {!OtherServicesglobal && Comboglobal === false && (
                <CategoryHorizontal
                  categoryFunction={dynamicComponentProps(
                    'Category',
                    BSLayout6Data?.BookingCategory?.[1],
                    BSLayout6Data?.BookingCategory?.[0]
                  )}
                />
              )}
              {OtherServicesglobal && (
                <BSOtherServicesHorizontalcat
                  categoryFunction={dynamicComponentProps(
                    'Category',
                    BSLayout6Data?.BookingCategory?.[1],
                    BSLayout6Data?.BookingCategory?.[0]
                  )}
                />
              )}
            </div>
          </div>

          <div
            className="BSLayout6-fulldiv"
            style={{
              backgroundColor: GlobalLayoutColorDetail?.OverallBackgroundColor,
            }}
          >
            <div
              className="BSLayout6-cards"
              style={{
                backgroundColor: SelectedCardColor?.['OverallBackgroundColor'],
                width: '100vw',
                display: 'flex',
              }}
            >
              {!OtherServicesglobal && Comboglobal === false && (
                <BSItemCard
                  connectingState={connectingState}
                  setConnectingState={setConnectingState}
                  // screenHeight={screenHeight}
                  cardFunctionality={dynamicComponentProps(
                    'Card',
                    BSLayout6Data?.BookingCard?.[1],
                    BSLayout6Data?.BookingCard?.[0]
                  )}
                />
              )}
              {!OtherServicesglobal && Comboglobal === true && (
                <BSComboItemCard
                  cardFunctionality={dynamicComponentProps(
                    'Card',
                    BSLayout6Data?.BookingCard?.[1],
                    BSLayout6Data?.BookingCard?.[0]
                  )}
                />
              )}
              {OtherServicesglobal && (
                <BSOtherServiceItemCard
                  screenHeight={window.innerHeight}
                  cardFunctionality={dynamicComponentProps(
                    'Card',
                    BookingCard?.[1],
                    BookingCard?.[0]
                  )}
                />
              )}
            </div>

            <div className="BSLayout6table-fulldiv">
              <div className="BSLayout6-table">
                {action ? (
                  <BranchTransferComponent />
                ) : (
                  <>
                    {BSLayout6Data?.BookingBilling?.[0] == 'Billing1' && (
                      <BSBillingTable1 />
                    )}
                    {BSLayout6Data?.BookingBilling?.[0] == 'Billing2' && (
                      <BSBillingTable2 />
                    )}
                    {BSLayout6Data?.BookingBilling?.[0] == 'Billing3' && (
                      <BSBillingTable3 />
                    )}
                    {BSLayout6Data?.BookingBilling?.[0] == 'Billing4' && (
                      <BSBillingTable4 />
                    )}
                    {BSLayout6Data?.BookingBilling?.[0] == 'Billing5' && (
                      <BSBillingTable5 />
                    )}
                    {BSLayout6Data?.BookingBilling?.[0] == 'Billing6' && (
                      <BSBillingTable6 />
                    )}
                    {BSLayout6Data?.BookingBilling?.[0] == 'Billing7' && (
                      <BSBillingTable7 />
                    )}
                    {BookingBilling == 'Billing8' && <ComboSalesBillTable />}
                    {BSLayout6Data?.BookingBilling?.[0] ==
                      'StandardBilling' && (
                      <div
                        className="BSCategory2New"
                        style={{
                          height: BSLayout6Data ? '88vh' : '99vh',
                        }}
                      >
                        <StandardTable />
                      </div>
                    )}
                  </>
                )}
                {/* <div className="salesStoreName"
                style={{
                  color: SelectedBillColor?.['FontColor'],
                  backgroundColor: SelectedBillColor?.['BackgroundColor'],
                }}>
                <BranchName />
              </div> */}
              </div>
            </div>
          </div>
          {BookingModalOpen && !OtherServicesglobal && (
            <RetailBookingClosing
              PaymentOpen={BookingModalOpen}
              PaymentClose={HandleBookingModalClose}
            />
          )}
          {ListOfInvoices && !OtherServicesglobal && (
            <ListOfSalesInvoices
              ListOfInvoicesOpen={ListOfInvoices}
              handleInvoiceClose={handleInvoiceClose}
            />
          )}
        </div>
      </>
    </Suspense>
  );
};
export default BSLayout6;
