import React, { useEffect, useState, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import moment from 'moment';
import { Tooltip, Badge, Popconfirm } from 'antd';
import BSBillingTable1 from '../../Components/BSBillingTables/BSBillingTable1/BSBillingTable1';
import BSBillingTable2 from '../../Components/BSBillingTables/BSBillingTable2/BsBill2';
import BSBillingTable3 from '../../Components/BSBillingTables/BSBillingTable3/BSBillingTable3';
import BSBillingTable4 from '../../Components/BSBillingTables/BSBillingTable4/BSBillingTable4';
import BSBillingTable5 from '../../Components/BSBillingTables/BSBillingTable5/BsBill';
import BSBillingTable6 from '../../Components/BSBillingTables/BSBillingTable6/BSBillingTable6';
import BSBillingTable7 from '../../Components/BSBillingTables/BSBillingTable7/BSBillingTable7';
import BSC1Payment from '../../Components/BSCombo/BSC1Payment';
import BSC1NavBar from '../../Components/BSCombo/BSC1NavBar';
import BSC1Search from '../../Components/BSCombo/BSC1Search';
import {
  GlobalCombosearch,
  GlobalPayementloader,
  GlobalSalesDetailData,
  getSalesDetailData,
  GlobalPaymentTransactionNumber,
  GlobalOrderType,
  GlobalOrderStatus,
  PreferenceData,
  GlobalAppExpDateData,
  GlobalBtoBQuickProductTransfer,
  changeCombosearch,
  Comboget,
} from '../../../../Features/BookingScreen/BookingData/BookingData.js';
import { isMobile } from 'react-device-detect';
import { ArrowUpOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { getSession } from '../../../../Services/Others.js';
import BSNavBarComboSearch from '../../Components/UtillComponents/BSNavBarComboSearch.jsx';
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 {
  getTemplateData,
  GlobalPricingAppPricingName,
  StoredSessionData,
} from '../../../../Features/ThemeChange/ThemeChange.js';
import './../../../../Styles/BookingScreen/Template/BSLayout7/Combo1.scss';
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';
import ListOfSalesInvoices from '../../Components/BSBillingTables/ListofInvoices/ListOfSalesInvoices.jsx';
import BSEwayBillicon from '../../Components/UtillComponents/BSEwayBillicon.jsx';
import BranchTransferComponent from '../../Components/UtillComponents/BSQuickBranchToBranchTransferComponent.jsx';
import BSExpireProductsList from '../../Components/UtillComponents/BSExpireProductsList.jsx';
import ComboSalesBillTable from '../../Components/BSBillingTables/ComboSalesBillTable/ComboSalesBillTable.jsx';
import { GiBasket } from 'react-icons/gi';
import { FaRegKeyboard } from 'react-icons/fa';
import { CgSearchLoading } from "react-icons/cg";
 import { DefaultModal } from '../../../../Components/Modal/DefaultModal.jsx';
import MultipleSearch from '../../Components/UtillComponents/MultipleSearch.jsx';

const subDirectory = import.meta.env.BASE_URL;
const commonDirectory = import.meta.env.COMMON_BASE_URL;

export default function BSCombo1() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { action, selectedProducts } = useSelector(
    GlobalBtoBQuickProductTransfer
  );
  const BSComboData = useSelector(getTemplateData);
  const SettingDataSelector = useSelector(PreferenceData);
  const GlobalsalesDetailData = useSelector(GlobalSalesDetailData);
  const SessionData = useSelector(StoredSessionData);
  const badgeCount = useSelector(globalKioskSalesCount);
  const Comboglobal = useSelector(GlobalCombosearch);
  const paymentloader = useSelector(GlobalPayementloader);
  const PaymentTransactionNumber = useSelector(GlobalPaymentTransactionNumber);
  const OrderStatus = useSelector(GlobalOrderStatus);
  const OrderType = useSelector(GlobalOrderType);
  const SAdminuserPin = useSelector(GLobalSadminUserPin);
  const AppExpDate = useSelector(GlobalAppExpDateData);
  const PricingAppPricingName = useSelector(GlobalPricingAppPricingName);
  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 [popOverOpen, setPopOverOpen] = useState(false);

  // const [AppExpDate, setAppExpDate] = useState(0);
  const [Kioskopen, setKioskopen] = useState(false);
  const [count, setcount] = useState(0);
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [multiple, setMultiple] = useState(false);
  const BookingBilling = BSComboData?.BookingBilling?.[0];
  const DineInAccess = SettingDataSelector?.[0]?.SettingDtlDetails.filter(
    (i) => i.SettingIdName === 'DineIn'
  )?.[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 BookingStatus = useSelector(GlobalBookingStatus);
  const CheckBookingStatus =
    BookingStatus?.find((item) => item.ScreenType === 'Booking')
      ?.ScreenStatus ?? 'Open';
  const [BookingModalOpen, setBookingModalOpen] = useState(false);
  const currentDateValue = moment().format('YYYY-MM-DD HH:mm:ss');
  const animations = ['example1', 'example2', 'example3'];
  let ss = animations[count];
  const [ListOfInvoices, setListOfInvoices] = useState(false);
  const [ComboDropDown, setComboDropDown] = useState();

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

  useEffect(() => {
    if (AppExpDate?.RemainingDays <= 7) {
      const interval = setInterval(() => {
        setcount((prevCount) => (prevCount >= 2 ? 0 : prevCount + 1));
      }, 22000);

      return () => clearInterval(interval);
    }
  }, [count == 2]);
  useEffect(() => {
    Combodata();
    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();
  };

  const navigateFun = () => {
    navigate(`${subDirectory}PricingPage`, { state: { AppName: AppName } });
  };

  const navigatePublicFun = () => {
    navigate(`${commonDirectory}`);
  };

  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);
  };
  const Combodata = async () => {
    let data = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
      ActiveStatus: 'A',
    };

    let Response = await dispatch(Comboget(data)).unwrap();
    if (Response?.data?.statusCode == 1) {
      setComboDropDown(Response?.data?.data);
    }
  };

  const handleClick = async () => {
    if (Comboglobal == false) {
      await dispatch(changeCombosearch(true));
    } else {
      await dispatch(changeCombosearch(false));
    }
  };
  return (
    <>
      <Messages
        messageType={messageType}
        messageData={messageData}
        onComplete={onComplete}
      />
      {UserType != 'Super Admin' &&
        UserType != 'Super Admin User' &&
        (AppExpDate?.RemainingDays <= 7 || AppExpDate === 'undefined') && (
          <div className={`${ss}`}>
            <p>
              {(AppExpDate?.RemainingDays < 1 &&
                AppExpDate?.RemainingHours < 1 &&
                AppExpDate?.RemainingMinutes < 1 &&
                AppExpDate?.RemainingSeconds < 1) ||
              AppExpDate === 'undefined' ? (
                <span className="ExpiredMessage">
                  Subscription expired &nbsp;
                  <a
                    onClick={() => {
                      navigatePublicFun();
                    }}
                    className="upgrdbtn"
                  >
                    RENEWAL NOW <ArrowUpOutlined />
                  </a>
                </span>
              ) : AppExpDate?.RemainingDays < 1 ? (
                <p>
                  Your application subscription will expire within &nbsp;
                  <span className="Expired">
                    {AppExpDate?.RemainingHours >= 1
                      ? AppExpDate?.RemainingHours
                      : AppExpDate?.RemainingMinutes}
                  </span>{' '}
                  {AppExpDate?.RemainingHours >= 1 ? 'Hrs' : 'Min'} . &nbsp;
                  <a
                    onClick={() => {
                      navigateFun();
                    }}
                    className="upgrdbtn"
                  >
                    RENEWAL NOW <ArrowUpOutlined />
                  </a>
                </p>
              ) : (
                <p>
                  Your application subscription will expire within &nbsp;
                  <span className="NosDays">
                    {AppExpDate?.RemainingDays}
                  </span>{' '}
                  days. &nbsp;
                  <a
                    onClick={() => {
                      navigateFun();
                    }}
                    className="upgrdbtn"
                  >
                    RENEWAL NOW <ArrowUpOutlined />
                  </a>
                </p>
              )}
            </p>
          </div>
        )}

      {/* Combo Container */}
      <div className="overall-bscombo-container">
        <div className="SearchSubnavbar-combo">
          <BSC1NavBar data={BSComboData} SessionData={SessionData} />
          <div className="comboNavbarSubMain">
            {/* Multiple search  */}
            <Tooltip title={'Multiple Search'}>
              <div className='MultiSearchIconDiv'>
                 <CgSearchLoading onClick={() => setMultiple(true)} />
              </div>
            </Tooltip>

            {Comboglobal === false && (
              <BSC1Search
                data={BSComboData?.BookingLayout[0]}
                OrderType={OrderType}
              />
            )}
            {Comboglobal === true && (
              <div style={{ padding: '4px' }} className="CombomainSearch">
                <div className="M">
                  <div className="BSC1Search-div1">
                    <BSNavBarComboSearch SessionData={SessionData} />
                  </div>
                </div>
              </div>
            )}

            {/* <div className="Layout-bill-container" style={{ margin: '0' }}> */}
            <div className="Layout-bill-Subcontainer ComboSubNavbar">
              {UserType !== 'Employee' && (
                <div className="pricing-name-details">
                  <p>{PricingAppPricingName?.[0]?.PricingName}</p>
                  <p>{PricingAppPricingName?.[0]?.Type}</p>
                  {/* {PricingAppPricingName?.[0]?.PricingName +
                      ' / ' +
                      PricingAppPricingName?.[0]?.Type} */}
                </div>
              )}

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

              {Kioskopen && (
                <BSKioskCounterPayment
                  Kioskopen={Kioskopen}
                  closeKioskModal={closeModalKiosk}
                />
              )}
              {SAdminuserPin?.length > 0 && UserType != 'Super Admin User' && (
                <div>
                  <SAdminUserNotification
                    SAdminuserPin={SAdminuserPin}
                    popOverOpen={popOverOpen}
                    handleSupportUser={handleSupportUser}
                    handlePopOverOpen={handlePopOverOpen}
                  />
                </div>
              )}

              <div className="combuSubNavbarRightSide">
                <SalesCountComponent
                  DineInAccess={DineInAccess}
                  GlobalsalesDetailData={GlobalsalesDetailData}
                />
                {/* LOW STOCK ALERT  */}
                <div className="BookingCloseCombo">
                  <TooltipWrapper
                    title={'Low Stock Alerts'}
                    isMobile={isMobile}
                  >
                    {' '}
                    <BSExpireProductsList />
                  </TooltipWrapper>
                </div>

                {CheckBookingStatus == 'Open' ? (
                  <div
                    style={{ marginLeft: '2px' }}
                    className="BookingCloseCombo"
                  >
                    <TooltipWrapper title={'Booking Close'} isMobile={isMobile}>
                      {' '}
                      <BookingCloseIcon
                        onClick={OpenBookingModal}
                        bgFill={'#1292ee'}
                        style={{
                          fontSize: '20px',
                          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>
                )}
                <div
                  style={{ display: 'flex', alignItems: 'center' }}
                  className="comboPrichangeBTN"
                >
                  {ComboDropDown?.length >= 1 && (
                    <div
                      style={{
                        fontSize: '1.5rem',
                      }}
                    >
                      <TooltipWrapper title="Combo Product" isMobile={isMobile}>
                        <GiBasket
                          fill={Comboglobal === true ? '#52C41A' : '#1292EE'}
                          enableBackground={
                            Comboglobal === true ? '#1292EE' : '#52C41A'
                          }
                          onClick={handleClick}
                          style={{
                            pointerEvents:
                              OrderType === 'Failed' ? 'none' : 'auto',
                            cursor: 'pointer',
                          }}
                        />
                      </TooltipWrapper>
                    </div>
                  )}
                </div>

                <Tooltip title="KeyBoard Shortcut">
                  <div className="keyboardShortcut">
                    <FaRegKeyboard size={20} />
                  </div>
                </Tooltip>
              </div>
            </div>
            {/* </div> */}
          </div>
        </div>
        <div
          // className="BSC1-Master"  comment by sree here this class name issues
          className="ComboScreenPageTable"
          style={{
            height: isMobile ? '56vh' : '70vh',
            overflow: 'hidden',
          }}
        >
          {/* <div className="BS1ComboTable"> */}
          <div
            className={
              ComboSalesBillTable
                ? 'BS1ComboTableComboSalesBillTable'
                : 'BS1ComboTable'
            }
          >
            {action ? (
              <BranchTransferComponent />
            ) : (
              // <ComboSalesBillTable />
              <>
                {BookingBilling == 'Billing1' && <BSBillingTable1 />}
                {BookingBilling == 'Billing2' && <BSBillingTable2 />}
                {BookingBilling == 'Billing3' && <BSBillingTable3 />}
                {BookingBilling == 'Billing4' && <BSBillingTable4 />}
                {BookingBilling == 'Billing5' && <BSBillingTable5 />}
                {BookingBilling == 'Billing6' && <BSBillingTable6 />}
                {BookingBilling == 'Billing7' && <BSBillingTable7 />}
                {BookingBilling == 'Billing8' && <ComboSalesBillTable />}
              </>
            )}
          </div>

          <div style={{ position: 'fixed', bottom: '0' }}>
            <BSC1Payment optionNames={BSComboData} />
          </div>
        </div>
        {paymentloader === true && (
          <div class="Payment-loader1">
            <div class="Payment-loader">
              <div class="contener_mixte">
                <div class="ballcolor ball_1">&nbsp;</div>
              </div>
              <div class="contener_mixte">
                <div class="ballcolor ball_2">&nbsp;</div>
              </div>
              <div class="contener_mixte">
                <div class="ballcolor ball_3">&nbsp;</div>
              </div>
              <div class="contener_mixte">
                <div class="ballcolor ball_4">&nbsp;</div>
              </div>
              <p style={{ marginTop: '2rem' }}>
                {' '}
                Please wait while we process your payment
              </p>
              {PaymentTransactionNumber != null && (
                <p style={{ fontSize: '16px', fontWeight: '600' }}>
                  Transaction Number : {PaymentTransactionNumber}
                </p>
              )}
            </div>
          </div>
        )}
      </div>
      {BookingModalOpen && (
        <RetailBookingClosing
          PaymentOpen={BookingModalOpen}
          PaymentClose={HandleBookingModalClose}
        />
      )}
      {ListOfInvoices && (
        <ListOfSalesInvoices
          ListOfInvoicesOpen={ListOfInvoices}
          handleInvoiceClose={handleInvoiceClose}
        />
      )}
      <DefaultModal
        open={multiple}
        title="Multiple Search"
        footer={false}
        width={350}
        handleCancel={() => setMultiple(false)}
        destroyOnClose={true}
        children={
          <>
            <MultipleSearch
              close={setMultiple}
            />
          </>
        }
      />
    </>
  );
}
