import React, { useEffect, useState, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { MdOutlinePayments } from 'react-icons/md';
import { HiOutlineBackspace } from 'react-icons/hi';
import { ArrowRightOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import { Modal } from 'antd';
import { CiSearch } from 'react-icons/ci';
import { Collapse, Radio } from 'antd';
import Buttons from '../../../Components/Forms/Buttons';
import Search from '../../../Components/Forms/Search.jsx';
import UPI from '../../../Images/upinew.svg';
import Card from '../../../Images/card.png';
import CrediCard from '../../../Images/PayOptImgs/creditcard.png';
import DebitCard from '../../../Images/PayOptImgs/debitcard.png';
import CashCard from '../../../Images/PayOptImgs/cashcard.png';
import NetBank from '../../../Images/PayOptImgs/netbank.png';
import Wallet from '../../../Images/PayOptImgs/wallet.png';
import { DefaultModal } from '../../../Components/Modal/DefaultModal';
import { Messages } from '../../../Components/Notifications/Messages';
import '../Payment/KioskPaymentWithModal.scss';
import {
  getKioskLightColour,
  changeKioskCustomerMobileNo,
  globalKioskCustomerMobileNo,
  changeKioskPageName,
  changeSelectedKioskPaymentOption,
  getKioskTemplate,
  GlobalKioskPrinterDetails,
  getKioskPrinterDetails,
} from '../../../Features/Kiosk/kiosk';
import {
  GlobalBookingTypeKiosk,
  GlobalKioskBookingTypeBoth,
  GlobalKioskOrderDetails,
  PostKioskBookingData,
  PutBookingPaymentStatusChange,
  changeOrderId,
  postPaymentDevice,
  getPaymentDeviceResponse,
  getPaymentGatewayDetails,
  getPaymentOptionsData,
  getPaymentDeviceAccessData,
  getPaymentGatewayAccessData,
  changeAllGlbStatustData,
  PutKioskBookingData,
  GlobalPGFailedTransId,
  changePGFailedTransId,
  changePaymentgatewayRedirect,
  getProductCategories,
  GlobalPGFailedAmt,
  changePGFailedAmt,
  getPaymentVerfication,
  GlobalOrderId,
} from '../../../Features/BookingScreen/BookingData/KioskBookingData';
import {
  getPrintSelectionComponentData,
  GlobalprintDatas,
  SelectedPrintTemplate,
} from '../../../Features/ThemeChange/ThemeChange';
import {
  getConfigType,
  getPreferenceData,
  PreferenceData,
  PutPendingPaymentList,
} from '../../../Features/BookingScreen/BookingData/BookingData';
import { isMobile } from 'react-device-detect';
import MobilePrint from '../../../Pages/BookingScreen/Components/BookingFunctionality/MobilePrint.jsx';
import KioskMobilePrint from '../../../Pages/BookingScreen/Components/BookingFunctionality/KioskMobilePrint.jsx';
import { PrintStyleFunction } from '../../../Pages/paymentpdfPage/PrintStyleFunction.js';
import {
  printDiv,
  extractLastNumberOrderId,
  encryptedValuesFun,
  getSession,
} from '../../../Services/Others';
import PaymentPdfBooking from '../../paymentpdfPage/PaymentPdfBooking.jsx';
import KioskBookingReceipt from '../../paymentpdfPage/KioskBookingReceipt.jsx';
import { getSalesDetails } from '../../../Features/PaymentGateway/PaymentGateway.js';
import { sendSms } from '../../../Features/Payment/PaymentDetails/PaymentDetails.js';
import { ApplicationPreferences } from '../../../Features/BrachLogin/BranchLogin.js';
import { VerifiedPaymentDtl } from '../../../Features/BookingScreen/Customer/addCustomer.js';
import PaymentGatewayEmbedded from '../../BookingScreen/Components/UtillComponents/PaymentGatewayEmbedded.jsx';
import MobileMultiPdfPrintTrigger from '../../BookingScreen/Components/UtillComponents/MobileMultiPdfPrintTrigger.jsx';
import { checkLastOrderTimeLimit, sendupiotp } from '../../../Features/UpiDetails/UpiDetails.js';
import { isIndianMobile } from '../../../utils/calculations.js';

const CustomPaymentUrl = import.meta.env.ENV_CUSTOM_PAYMENT_URL;

const KioskPayment = (props) => {
  const paymentGatewayRef = React.useRef(null);
  const dispatch = useDispatch();
  const SessionData = props?.sessionData;
  const DeviceMacAddress = getSession('DeviceAddress');
  console.log(DeviceMacAddress, 'DeviceMacAddress');

  const [open, setOpen] = useState(props.modalOpen);
  const [width, setWidth] = useState(window.innerWidth);
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);
  const appPreferences = useSelector(ApplicationPreferences);
  const CustomerMobileNumber = useSelector(globalKioskCustomerMobileNo);
  const OrderId = useSelector(GlobalOrderId);
  console.log(OrderId, 'OrderIdOrderId');
  const PGfailedId = useSelector(GlobalPGFailedTransId);
  const PGfailedAmt = useSelector(GlobalPGFailedAmt);
  const KioskPrinterList = useSelector(GlobalKioskPrinterDetails);
  const [counterAvailability, setCounterAvailability] = useState(false);
  const [cardAvailability, setCardAvailability] = useState(false);
  const [upiAvailability, setUpiAvailability] = useState(false);
  const [SelectedBookingType, setSelectedBookingType] = useState(null);
  const [TotalTaxAmount, setTotalTaxAmount] = useState(null);
  const [TotalBillAmount, setBillAmount] = useState(null);
  const [TotalNetAmount, setTotalNetAmount] = useState(null);
  const [PrintOrderDetails, setPrintOrderDetails] = useState([]);
  const [PaymentOptionsData, setPaymentOptionsData] = useState([]);
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [paymentDeviceAccess, setPaymentDeviceAccess] = useState([]);
  const [paymentGatewayAccess, setPaymentGatewayAccess] = useState([]);
  const [paymentDefalutOption, setPaymentDefaultOption] = useState(null);
  const [showPaymentGatewayOptions, setShowPaymentGatewayOptions] =
    useState(false);
  const [paymentGatewayMethods, setPaymentGatewayMethods] = useState([]);
  const [paymentOptionDetailsBusinessUpi, setPaymentOptionDetailsBusinessUpi] =
    useState(null);
  const [selectedOption, setselectedOption] = useState();
  const [value, setValue] = useState();
  const [itemsdata, setItemsdata] = useState();
  const [dataAccept, setDataAccept] = useState();
  const [cardName, setCardName] = useState();
  const [selectedPaymentOption, setSelectedPaymentOption] = useState(null);
  const [devicePaymentStatus, setDevicePaymentStatus] = useState(false);
  const [FailedTranId, setFailedTranId] = useState(null);
  const getKioskLightColourdata = useSelector(getKioskLightColour);
  const KioskOrderDetails = useSelector(GlobalKioskOrderDetails);
  console.log(CustomerMobileNumber, 'CustomerMobileNumber');
  const [number, setNumber] = useState(
    CustomerMobileNumber ? CustomerMobileNumber : ''
  );
  const BookingTypeBoth = useSelector(GlobalKioskBookingTypeBoth);
  const BookingType = useSelector(GlobalBookingTypeKiosk);
  const printerTemplateStyle = useSelector(SelectedPrintTemplate);
  const printDatas = useSelector(GlobalprintDatas);
  const SettingDataSelector = useSelector(PreferenceData);
  console.log(
    SettingDataSelector,
    KioskPrinterList,
    'SettingDataSelectorSettingDataSelector'
  );
  const MobileA4Print = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
    (setting) =>
      setting?.SettingIdName?.toLowerCase() === 'mobilea4' &&
      setting?.SettingValue === 'Y'
  );
  const isOtpEnabled = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
    (setting) =>
      setting?.SettingIdName?.toLowerCase() === 'kioskotp' &&
      setting?.SettingValue === 'Y'
  );
  const isTimeLimitEnabled = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
    (setting) =>
      (setting?.SettingIdName?.toLowerCase() === 'hours' || setting?.SettingIdName?.toLowerCase() === 'minutes') &&
      setting?.SettingValue === 'Y'
  );

  const bookingTypePreference = appPreferences?.find(
    (preference) => preference?.PreferredCatName === 'Booking Type'
  )?.PreferenceCatDetails;
  const [showPaymentMethods, setShowPaymentMethods] = useState(null);
  const [resendTimer, setResendTimer] = useState(0)
  const [canResend, setCanResend] = useState(true)
  const [otpInput, setOtpInput] = useState(['', '', '', '']);
  const [otpIndex, setOtpIndex] = useState(0);
  const [otpSent, setOtpSent] = useState(false);
  const [otpVerifed, setOtpVerified] = useState(false);
  const [otpNumber, setOTPNumber] = useState(null);
  const [paymentUrl, setpaymentUrl] = useState(null);
  const [businessUPI, setBusinessUPI] = useState(false);
  console.log(PrintOrderDetails, 'PrintOrderDetails');
  const [TransctionId, setTransctionId] = useState(null);
  const [paymentSucess, setPaymentSuccess] = useState(false);
  useEffect(() => {
    fetchPaymentAccess();
  }, []);
  useEffect(() => {
    TotalCalculation();
  }, [KioskOrderDetails]);
  useEffect(() => {
    if (SessionData.CompId && SessionData.BranchId && SessionData.AppId) {
      if (DeviceMacAddress) {
        let data = {
          CompId: SessionData.CompId,
          BranchId: SessionData.BranchId,
          AppId: SessionData.AppId,
          DeviceMacAddress: DeviceMacAddress,
        };
        dispatch(getKioskPrinterDetails(data)).unwrap();
      }
      dispatch(getPreferenceData({ CompId: SessionData.CompId, BranchId: SessionData.BranchId, AppId: SessionData.AppId })).unwrap();
    }
  }, [SessionData.CompId, SessionData.BranchId, SessionData.AppId]);

  useEffect(() => {
    const getPrintData = async () => {
      try {
        const data = {
          AppId: SessionData.AppId,
          CompId: SessionData.CompId,
          BranchId: SessionData.BranchId,
          OrderId: TransctionId,
        };

        const res = await dispatch(VerifiedPaymentDtl(data)).unwrap();

        if (res?.data?.statusCode === 1 && res?.data?.data?.length > 0) {
          const orderData = [{ OrderDetails: res.data.data }];

          // Reset states first
          setTransctionId(null);
          setBusinessUPI(false);
          setPaymentSuccess(false);

          // Then set new data and trigger side effects
          setPrintOrderDetails(orderData);
          // dispatch(changeKioskPageName('initialPage'));
          // dispatch(changeAllGlbStatustData());
          // CustomerDisplay();
          // ClearAllGlobalStateDatas();
          // handleURL(orderData);
        }
      } catch (error) {
        console.error('Failed to fetch print data:', error);
        // Reset states even on error
        setBusinessUPI(false);
        setPaymentSuccess(false);
      }
    };

    if (paymentSucess && TransctionId) {
      const timer = setTimeout(() => {
        getPrintData();
      }, 3000);

      return () => clearTimeout(timer);
    }
  }, [paymentSucess, TransctionId]);

  useEffect(() => {
    getBookingTypeId();
  }, [BookingType]);
  useEffect(() => {
    getSalesDetail();
  }, [FailedTranId, PGfailedId]);
  const getSalesDetail = async () => {
    if (PGfailedId) {
      let OrderId = PGfailedId;
      let response = await dispatch(
        getSalesDetails({ SalesId: OrderId })
      ).unwrap();
      console.log(response, 'salesdetail');
      if (response?.data?.statusCode === 1) {
        if (response?.data?.PaymentOrderDtl?.length >= 2) {
          setMessageType('error');
          setMessageData('Your transaction limt exceeds, Please contact admin');
          clearAllStates();
          dispatch(
            getProductCategories({
              AppId: SessionData.AppId,
              CompId: SessionData.CompId,
              BranchId: SessionData.BranchId,
            })
          ).unwrap();
          setTimeout(function () {
            dispatch(changeKioskPageName('initialPage'));
            dispatch(changeAllGlbStatustData());
          }, 2000);
        }
      }
    }
  };
  useEffect(() => {
    if (PrintOrderDetails?.length > 0) {
      if (selectedPaymentOption == 'Counter') {
        if (isMobile) {
          KioskMobilePrint(PrintOrderDetails?.[0]?.OrderDetails?.[0]);
          setTimeout(function () {
            dispatch(changeKioskPageName('paymentPage'));
          }, 3000);
        } else {
          Print();
        }
      }
      if (selectedPaymentOption == 'BU') {
        if (isMobile) {
          if (MobileA4Print) {
            const preferenceDetails =
              SettingDataSelector?.[0]?.SettingDtlDetails;
            let PrinterDetails = KioskPrinterList;
            MobileMultiPdfPrintTrigger({
              preferenceDetails,
              printerTemplateStyle,
              printDatas,
              PrinterDetails,
              PrintOrderDetails,
              SessionData,
              bookingTypePreference,
            });
            //
          } else {
            MobilePrint(
              appPreferences,
              PrintOrderDetails,
              '',
              'Booking',
              SettingDataSelector
            );
            setTimeout(function () {
              dispatch(changeKioskPageName('paymentPage'));
            }, 3000);
          }
          dispatch(changeKioskPageName('initialPage'));
          dispatch(changeAllGlbStatustData());
          ClearAllGlobalStateDatas();
        } else {
          PrintDevice();
        }
      }
      if (devicePaymentStatus && selectedPaymentOption != 'Counter') {
        if (isMobile) {
          MobilePrint(
            appPreferences,
            PrintOrderDetails,
            '',
            'Booking',
            SettingDataSelector
          );
          setTimeout(function () {
            dispatch(changeKioskPageName('paymentPage'));
          }, 3000);
        } else {
          PrintDevice();
        }
      }
    }
  }, [PrintOrderDetails]);

  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [width]);

  useEffect(() => {
    isIndianMobile(number) && dispatch(changeKioskCustomerMobileNo(number));
  }, [number]);

  const onChange = (e) => {
    setValue(e?.target?.value);
    setDataAccept(
      itemsdata?.[e.target.value]?.DataAcceptedAt == 'CCAvenue' ? 'Y' : 'N'
    );
    setCardName(itemsdata?.[e.target.value]?.CardName);
  };
  const onSearchChange = (e) => {
    let Details = paymentGatewayMethods?.[selectedOption]?.MethodDetails;
    let searchTerm = e.target.value?.toLowerCase();

    let updated = Details.filter((item) =>
      item.CardName?.toLowerCase().startsWith(searchTerm)
    );

    setItemsdata(updated);
  };
  const items = [
    {
      key: '1',
      label: `${paymentGatewayMethods?.[selectedOption]?.CardType == 'CRDC' ||
        paymentGatewayMethods?.[selectedOption]?.CardType == 'DBCRD'
        ? 'Choose Your Card'
        : paymentGatewayMethods?.[selectedOption]?.CardType == 'WLT'
          ? 'Choose Your Wallet'
          : 'Choose Your Bank'
        } `,
      children: (
        <Radio.Group
          onChange={onChange}
          value={value}
          style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}
        >
          {itemsdata?.map((item, index) => {
            return (
              <>
                <Radio
                  value={index}
                  style={{
                    width: '106%',
                    marginLeft: '-15px',
                    borderBottom: '1px solid #dadada',
                  }}
                >
                  {item.CardName}
                </Radio>
              </>
            );
          })}
        </Radio.Group>
      ),
    },
  ];
  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const setNumberFun = (newValue) => {
    setNumber((prevNumber) => {
      if (prevNumber.length < 10) {
        return prevNumber + newValue;
      }
      return prevNumber;
    });
  };

  const handleOtpNumber = (num) => {
    if (otpIndex > 3) return;

    const newOtp = [...otpInput];
    newOtp[otpIndex] = num.toString();
    setOtpInput(newOtp);

    if (otpIndex < 3) {
      setOtpIndex(otpIndex + 1);
    }
  };

  const handleOtpBackspace = () => {
    if (otpIndex < 0) return;

    const newOtp = [...otpInput];

    if (newOtp[otpIndex]) {
      newOtp[otpIndex] = '';
    } else if (otpIndex > 0) {
      newOtp[otpIndex - 1] = '';
      setOtpIndex(otpIndex - 1);
    }

    setOtpInput(newOtp);
  };

  const handleBackspace = () => {
    setNumber((prevNumber) => prevNumber.slice(0, -1));
  };

  const fetchPaymentAccess = async () => {
    const Data1 = {
      AppId: SessionData.AppId,
      CompId: SessionData.CompId,
      BranchId: SessionData.BranchId,
    };
    dispatch(getPrintSelectionComponentData(Data1)).unwrap();
    const paymentDeviceAccessResponse = await dispatch(
      getPaymentDeviceAccessData({
        AppId: SessionData.AppId,
        CompId: SessionData.CompId,
        BranchId: SessionData.BranchId,
        UserId: SessionData.UserId,
      })
    ).unwrap();
    setPaymentDeviceAccess(paymentDeviceAccessResponse?.data?.data);
    const paymentGatewayAccessResponse = await dispatch(
      getPaymentGatewayAccessData({
        AppId: SessionData.AppId,
        CompId: SessionData.CompId,
        BranchId: SessionData.BranchId,
        ActiveStatus: 'A',
      })
    ).unwrap();
    setPaymentGatewayAccess(paymentGatewayAccessResponse?.data?.data);
    fetchPaymentOptionsData(
      paymentDeviceAccessResponse?.data?.data,
      paymentGatewayAccessResponse?.data?.data
    );
  };
  function updatePaymentDetails(
    paymentDetails,
    paymentDeviceAccess,
    paymentGatewayAccess
  ) {
    const kioskSalesFlow = paymentDetails.find(
      (detail) => detail.FlowName === 'Kiosk Sales'
    );

    if (kioskSalesFlow) {
      kioskSalesFlow.OptionDetails = kioskSalesFlow.OptionDetails.filter(
        (option) => {
          if (option.OptionName === 'Payment Device') {
            return paymentDeviceAccess.length > 0;
          }
          if (option.OptionName === 'Payment Gateway') {
            return paymentGatewayAccess.length > 0;
          }
          return true;
        }
      );
    }

    return paymentDetails;
  }

  const fetchPaymentOptionsData = async (
    paymentDeviceAccess,
    paymentGatewayAccess
  ) => {
    const paymentOptionsResponse = await dispatch(
      getPaymentOptionsData({
        AppId: SessionData.AppId,
        CompId: SessionData.CompId,
        BranchId: SessionData.BranchId,
      })
    ).unwrap();
    if (paymentOptionsResponse?.data?.data?.length > 0) {
      setPaymentDefaultOption(
        paymentOptionsResponse?.data?.data?.[0]?.['KioskDefaultOption']
      );
      setPaymentOptionDetailsBusinessUpi(
        paymentOptionsResponse?.data?.data?.[0].PaymentDetails?.filter(
          (element) => element.FlowName === 'Kiosk Sales'
        )[0]?.OptionDetails?.find((e) => e?.OptionName === 'Business Upi')
      );

      const updatedPaymentDetails = updatePaymentDetails(
        paymentOptionsResponse?.data?.data?.[0].PaymentDetails,
        paymentDeviceAccess,
        paymentGatewayAccess
      );

      updatedPaymentDetails?.forEach((app) => {
        if (app.FlowName === 'Kiosk Sales') {
          app?.OptionDetails?.forEach((option) => {
            if (option.OptionName === 'Pay at the counter') {
              setCounterAvailability(true);
            }
            if (
              (option.OptionName === 'Payment Gateway' ||
                option.OptionName === 'Payment Device') &&
              option.ModeDetails.some((mode) => mode.ModeName === 'UPI')
            ) {
              setUpiAvailability(true);
            }
            if (
              (option.OptionName === 'Payment Gateway' &&
                option.ModeDetails.some(
                  (mode) =>
                    mode.ModeName === 'CreditCard' ||
                    mode.ModeName === 'DebitCard'
                )) ||
              (option.OptionName === 'Payment Device' &&
                option.ModeDetails.some((mode) => mode.ModeName === 'Card'))
            ) {
              setCardAvailability(true);
            }
          });
          setPaymentOptionsData(app);
        }
      });
    }
  };

  const getBookingTypeId = async () => {
    let tempconfigdata = await dispatch(
      getConfigType({ TypeName: 'Booking Type' })
    ).unwrap();
    let configdata = tempconfigdata?.data?.data;
    let checkName = BookingTypeBoth ? 'DineIn,TakeAway' : BookingType;

    let filterconfigdata = configdata?.find((a) => a?.ConfigName === checkName);

    setSelectedBookingType(filterconfigdata?.ConfigId);
  };

  const TotalCalculation = () => {
    const totalwithouttax = KioskOrderDetails?.reduce((accumulator, card) => {
      return accumulator + parseFloat(card.WithoutTaxRate || 0);
    }, 0);
    setBillAmount(parseFloat(totalwithouttax)?.toFixed(2));
    const totalPrice = KioskOrderDetails?.reduce((accumulator, card) => {
      return accumulator + parseFloat(card.TotalAmt || 0);
    }, 0);
    setTotalNetAmount(parseFloat(totalPrice)?.toFixed(2));
    const totalTaxAmt = KioskOrderDetails?.reduce((accumulator, card) => {
      return accumulator + parseFloat(card.TaxAmt || 0);
    }, 0);

    setTotalTaxAmount(parseFloat(totalTaxAmt)?.toFixed(2));
  };

  function getKioskDefaultOption(
    paymentDetails,
    selectedOption,
    kioskDefaultOption
  ) {
    if (kioskDefaultOption === 'PD') {
      if (selectedOption === 'UPI') {
        const paymentDevice = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Payment Device'
        );
        if (
          paymentDevice &&
          paymentDevice.ModeDetails.some((mode) => mode.ModeName === 'UPI')
        ) {
          return 'PD';
        }
        const paymentGateway = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Payment Gateway'
        );
        if (
          paymentGateway &&
          paymentGateway.ModeDetails.some((mode) => mode.ModeName === 'UPI')
        ) {
          return 'PG';
        }
        const payAtCounter = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Pay at the counter'
        );
        if (
          payAtCounter &&
          payAtCounter.ModeDetails.some((mode) => mode.ModeName === 'UPI')
        ) {
          return 'PC';
        }
      } else if (selectedOption === 'Card') {
        const paymentDevice = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Payment Device'
        );
        if (
          paymentDevice &&
          paymentDevice.ModeDetails.some((mode) => mode.ModeName === 'Card')
        ) {
          return 'PD';
        }
        const paymentGateway = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Payment Gateway'
        );
        if (
          paymentGateway &&
          paymentGateway.ModeDetails.some(
            (mode) =>
              mode.ModeName === 'CreditCard' || mode.ModeName === 'DebitCard'
          )
        ) {
          return 'PG';
        }
      }
    } else if (kioskDefaultOption === 'PG') {
      if (selectedOption === 'UPI') {
        const paymentGateway = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Payment Gateway'
        );
        if (
          paymentGateway &&
          paymentGateway.ModeDetails.some((mode) => mode.ModeName === 'UPI')
        ) {
          return 'PG';
        }
        const paymentDevice = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Payment Device'
        );
        if (
          paymentDevice &&
          paymentDevice.ModeDetails.some((mode) => mode.ModeName === 'UPI')
        ) {
          return 'PD';
        }
        const payAtCounter = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Pay at the counter'
        );
        if (
          payAtCounter &&
          payAtCounter.ModeDetails.some((mode) => mode.ModeName === 'UPI')
        ) {
          return 'PC';
        }
      } else if (selectedOption === 'Card') {
        const paymentGateway = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Payment Gateway'
        );
        if (
          paymentGateway &&
          paymentGateway.ModeDetails.some(
            (mode) =>
              mode.ModeName === 'CreditCard' || mode.ModeName === 'DebitCard'
          )
        ) {
          return 'PG';
        }
        const paymentDevice = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Payment Device'
        );
        if (
          paymentDevice &&
          paymentDevice.ModeDetails.some((mode) => mode.ModeName === 'Card')
        ) {
          return 'PD';
        }
      }
    } else if (kioskDefaultOption === null) {
      if (selectedOption === 'UPI') {
        const paymentDevice = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Payment Device'
        );
        if (
          paymentDevice &&
          paymentDevice.ModeDetails.some((mode) => mode.ModeName === 'UPI')
        ) {
          return 'PD';
        }
        const paymentGateway = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Payment Gateway'
        );
        if (
          paymentGateway &&
          paymentGateway.ModeDetails.some((mode) => mode.ModeName === 'UPI')
        ) {
          return 'PG';
        }
        const payAtCounter = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Pay at the counter'
        );
        if (
          payAtCounter &&
          payAtCounter.ModeDetails.some((mode) => mode.ModeName === 'UPI')
        ) {
          return 'PC';
        }
      } else if (selectedOption === 'Card') {
        const paymentDevice = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Payment Device'
        );
        if (
          paymentDevice &&
          paymentDevice.ModeDetails.some((mode) => mode.ModeName === 'Card')
        ) {
          return 'PD';
        }
        const paymentGateway = paymentDetails.OptionDetails.find(
          (option) => option.OptionName === 'Payment Gateway'
        );
        if (
          paymentGateway &&
          paymentGateway.ModeDetails.some(
            (mode) =>
              mode.ModeName === 'CreditCard' || mode.ModeName === 'DebitCard'
          )
        ) {
          return 'PG';
        }
      }
    }

    return null;
  }

  const checkLast30MinOrder = async (MobileNo) => {
    const response = await dispatch(checkLastOrderTimeLimit({
      MobileNo,
      AppId: SessionData.AppId,
      CompId: SessionData.CompId,
      BranchId: SessionData.BranchId,
    }))?.unwrap();
    return response?.data;
  };

  const handlePaymentOption = async (option) => {

    if (isTimeLimitEnabled) {
      const withinTimeLimit = await checkLast30MinOrder(number);
      if (withinTimeLimit?.IsEligible === false) {
        setMessageData(withinTimeLimit?.response);
        setMessageType('warning');
        return;
      }
    }

    setSelectedPaymentOption(option);
    dispatch(changeSelectedKioskPaymentOption(option));

    if (option == 'UPI' || option == 'Card') {
      const kioskDefaultOption = getKioskDefaultOption(
        PaymentOptionsData,
        option,
        paymentDefalutOption
      );
      if (kioskDefaultOption == 'PD') {
        handleDevice(PaymentOptionsData, option);
      } else if (kioskDefaultOption == 'PG') {
        if (option == 'UPI') {
          const filteredUpiData = {
            ...PaymentOptionsData,
            OptionDetails: PaymentOptionsData.OptionDetails.filter(
              (option) => option.OptionName === 'Payment Gateway'
            ).map((option) => ({
              ...option,
              ModeDetails: option.ModeDetails.filter(
                (mode) => mode.ModeName == 'UPI'
              ),
            })),
          };
          handleGateway(
            PaymentOptionsData,
            option,
            filteredUpiData?.OptionDetails?.[0]?.ModeDetails
          );
        } else {
          const filteredData = {
            ...PaymentOptionsData,
            OptionDetails: PaymentOptionsData.OptionDetails.filter(
              (option) => option.OptionName === 'Payment Gateway'
            ).map((option) => ({
              ...option,
              ModeDetails: option.ModeDetails.filter(
                (mode) => mode.ModeName !== 'UPI'
              ),
            })),
          };

          setPaymentGatewayMethods(
            filteredData?.OptionDetails?.[0]?.ModeDetails
          );
          setselectedOption(0);
          setItemsdata(
            filteredData?.OptionDetails?.[0]?.ModeDetails?.[0]?.MethodDetails
          );
          setShowPaymentGatewayOptions(true);
        }
      } else {
        setMessageType('error');
        setMessageData('Something went wrong');
      }
    } else if (option == 'BU') {
      handleCounterBusinessUpi();
    } else {
      handleCounter();
    }
  };

  async function getModeId(paymentDetails, option, optionName) {
    const paymentDeviceOption = paymentDetails.OptionDetails.find(
      (option) => option.OptionName === optionName
    );
    if (!paymentDeviceOption) {
      return null;
    }
    const selectedMode = paymentDeviceOption.ModeDetails.find(
      (mode) => mode.ModeName === option
    );
    if (!selectedMode) {
      return null;
    }

    return selectedMode.ModeId;
  }
  const clearAllStates = () => {
    setFailedTranId(null);
    dispatch(changeKioskCustomerMobileNo(null));
    dispatch(changePaymentgatewayRedirect(false));
    dispatch(changePGFailedAmt(null));
  };

  const handleCounter = async () => {
    const NotSlectedTypeFind = KioskOrderDetails?.find(
      (a) => a?.BookingType != SelectedBookingType
    );
    let putdevicedata;
    if (FailedTranId || PGfailedId) {
      putdevicedata = {
        CompId: SessionData.CompId,
        BranchId: SessionData.BranchId,
        AppId: SessionData.AppId,
        CustSuppId: CustomerMobileNumber,
        UpdatedBy: SessionData.UserId,
        OrderId: PGfailedId ? PGfailedId : FailedTranId,
        Amount: PGfailedId ? PGfailedAmt : TotalNetAmount,
        PaymentType: 0,
        PaymentOptionType: 'PC',
        PaymentStatus: 'P',
        Debit: 0,
        Credit: 0,
      };
    }
    let postCounterData = {
      CompId: SessionData.CompId,
      BranchId: SessionData.BranchId,
      OrderType: 'O',
      MobileNo: CustomerMobileNumber,
      BookingType:
        NotSlectedTypeFind && !BookingTypeBoth
          ? NotSlectedTypeFind?.BookingType
          : SelectedBookingType,
      ActiveStatus: 'A',
      CreatedBy: SessionData.UserId,
      AppId: SessionData.AppId,
      RefundAmount: 0,
      BillAmount: TotalBillAmount,
      OverallDisc: 0,
      TaxAmount: TotalTaxAmount,
      VatAmount: 0,
      NetAmount: TotalNetAmount,
      PaymentType: 0,
      GivenAmt: 0,
      BalGiven: 0,
      BookingMedia: 'KW',
      PaymentStatus: 'P',
      OrderDtlDetails: KioskOrderDetails,
      Type: 0,
      Debit: 0,
      Credit: 0,
      SalesPaymentType: 'normal',
      PaymentDetail: [
        {
          Amount: TotalNetAmount,
          PaymentOptionType: 'PC',
          PaymentStatus: 'P',
          Debit: 0,
          Credit: 0,
        },
      ],
    };
    let response;
    if (FailedTranId || PGfailedId) {
      response = await dispatch(PutKioskBookingData(putdevicedata)).unwrap();
    } else {
      response = await dispatch(PostKioskBookingData(postCounterData)).unwrap();
    }
    if (response?.data?.statusCode == 1) {
      await dispatch(
        changeOrderId(
          response?.data?.OrderDetails?.[0]?.SalesId
            ? extractLastNumberOrderId(
              response?.data?.OrderDetails?.[0]?.SalesId,
              response?.data?.OrderDetails?.[0]?.FYStatus
            )
            : null
        )
      );
      setPrintOrderDetails([response?.data]);
      setOpen(false);
      if (response?.data?.SMSbody) {
        const postData = {
          body: response?.data?.SMSbody,
        };
        await dispatch(sendSms(postData));
      }
      clearAllStates();
    } else {
      if (
        response?.data?.statusCode == 0 &&
        response?.data?.response == 'Order Limit Exceeded'
      ) {
        setMessageType('error');
        setMessageData('Order Limit Exceeded');
      } else {
        setMessageType('error');
        setMessageData('Something went wrong');
      }
      setTimeout(function () {
        dispatch(changeKioskPageName('initialPage'));
        dispatch(changeAllGlbStatustData());
      }, 2000);
    }
  };
  const handleCounterBusinessUpi = async () => {
    const NotSlectedTypeFind = KioskOrderDetails?.find(
      (a) => a?.BookingType != SelectedBookingType
    );
    let putdevicedata;
    if (FailedTranId || PGfailedId) {
      putdevicedata = {
        CompId: SessionData.CompId,
        BranchId: SessionData.BranchId,
        AppId: SessionData.AppId,
        CustSuppId: CustomerMobileNumber,
        UpdatedBy: SessionData.UserId,
        OrderId: PGfailedId ? PGfailedId : FailedTranId,
        Amount: PGfailedId ? PGfailedAmt : TotalNetAmount,
        PaymentType: 0,
        PaymentOptionType: 'PC',
        PaymentStatus: 'P',
        Debit: 0,
        Credit: 0,
      };
    }
    let BusinessUpi = paymentOptionDetailsBusinessUpi?.ModeDetails?.[0];
    let postCounterData = {
      CompId: SessionData.CompId,
      BranchId: SessionData.BranchId,
      OrderType: 'O',
      MobileNo: CustomerMobileNumber,
      BookingType:
        NotSlectedTypeFind && !BookingTypeBoth
          ? NotSlectedTypeFind?.BookingType
          : SelectedBookingType,
      ActiveStatus: 'A',
      CreatedBy: SessionData.UserId,
      AppId: SessionData.AppId,
      RefundAmount: 0,
      BillAmount: TotalBillAmount,
      OverallDisc: 0,
      TaxAmount: TotalTaxAmount,
      VatAmount: 0,
      NetAmount: TotalNetAmount,
      PaymentType: 0,
      GivenAmt: 0,
      BalGiven: 0,
      BookingMedia: 'KW',
      PaymentStatus: 'P',
      OrderDtlDetails: KioskOrderDetails,
      Type: 0,
      Debit: 0,
      Credit: 0,
      SalesPaymentType: 'normal',
      PaymentDetail: [
        {
          AccountDtl: [],
          Amount: TotalNetAmount,
          Credit: 0,
          Debit: 0,
          PaymentOptionType: 'BU',
          PaymentStatus: 'P',
          PaymentType: BusinessUpi?.ModeId || 0,
          ModeOfPayment: null,
          MerchantId: BusinessUpi?.MerchantId,
        },
      ],
    };
    let response;
    if (FailedTranId || PGfailedId) {
      response = await dispatch(PutKioskBookingData(putdevicedata)).unwrap();
    } else {
      response = await dispatch(PostKioskBookingData(postCounterData)).unwrap();
    }
    if (response?.data?.statusCode == 1) {
      console.log(response?.data?.OrderDetails?.[0]?.SalesId, 'hhhh');

      setOpen(false);
      dispatch(
        changeOrderId(
          response?.data?.OrderDetails?.[0]?.SalesId
            ? extractLastNumberOrderId(
              response?.data?.OrderDetails?.[0]?.SalesId,
              response?.data?.OrderDetails?.[0]?.FYStatus
            )
            : null
        )
      );
      let OrderId = response?.data?.OrderId;
      setTransctionId(OrderId);
      setBusinessUPI(true);

      setpaymentUrl(response?.data?.PaymentPageLink);
    } else {
      if (
        response?.data?.statusCode == 0 &&
        response?.data?.response == 'Order Limit Exceeded'
      ) {
        setMessageType('error');
        setMessageData('Order Limit Exceeded');
      } else {
        setMessageType('error');
        setMessageData('Something went wrong');
      }
      setTimeout(function () {
        dispatch(changeKioskPageName('initialPage'));
        dispatch(changeAllGlbStatustData());
      }, 2000);
    }
  };

  const handleDevice = async (paymentDetails, option) => {
    const paymentDeviceDetails = await dispatch(
      getPaymentGatewayDetails({
        AppId: SessionData.AppId,
        CompId: SessionData.CompId,
        BranchId: SessionData.BranchId,
        DetailType: 'D',
      })
    ).unwrap();
    const NotSlectedTypeFind = KioskOrderDetails?.find(
      (a) => a?.BookingType != SelectedBookingType
    );
    let putdevicedata;
    const modeId = await getModeId(paymentDetails, option, 'Payment Device');
    if (FailedTranId || PGfailedId) {
      putdevicedata = {
        CompId: SessionData.CompId,
        BranchId: SessionData.BranchId,
        AppId: SessionData.AppId,
        CustSuppId: CustomerMobileNumber,
        UpdatedBy: SessionData.UserId,
        PaymentType: modeId,
        OrderId: PGfailedId ? PGfailedId : FailedTranId,
        Amount: PGfailedId ? PGfailedAmt : TotalNetAmount,
        PaymentOptionType: 'PD',
        PaymentStatus: 'P',
        Debit: 0,
        Credit: 0,
        ModeOfPayment: null,
        AccountDtl: paymentDeviceDetails?.data?.data,
      };
    }
    let postDeviceData = {
      CompId: SessionData.CompId,
      BranchId: SessionData.BranchId,
      OrderType: 'O',
      MobileNo: CustomerMobileNumber,
      BookingType:
        NotSlectedTypeFind && !BookingTypeBoth
          ? NotSlectedTypeFind?.BookingType
          : SelectedBookingType,
      ActiveStatus: 'A',
      CreatedBy: SessionData.UserId,
      AppId: SessionData.AppId,
      RefundAmount: 0,
      BillAmount: TotalBillAmount,
      OverallDisc: 0,
      TaxAmount: TotalTaxAmount,
      VatAmount: 0,
      NetAmount: TotalNetAmount,
      PaymentType: 0,
      GivenAmt: 0,
      BalGiven: 0,
      BookingMedia: 'KW',
      PaymentStatus: 'P',
      OrderDtlDetails: KioskOrderDetails,
      Type: 0,
      Debit: 0,
      Credit: 0,
      SalesPaymentType: 'normal',
      PaymentDetail: [
        {
          Amount: TotalNetAmount,
          PaymentType: modeId,
          PaymentOptionType: 'PD',
          PaymentStatus: 'P',
          Debit: 0,
          Credit: 0,
          ModeOfPayment: null,
          AccountDtl: paymentDeviceDetails?.data?.data,
        },
      ],
    };
    let response;
    if (FailedTranId || PGfailedId) {
      response = await dispatch(PutKioskBookingData(putdevicedata)).unwrap();
    } else {
      response = await dispatch(PostKioskBookingData(postDeviceData)).unwrap();
    }
    if (response?.data?.statusCode == 1) {
      let PaymentOrderDetails = response?.data?.PaymentOrderDtl?.filter(
        (item) => item.PaymentOptionType == 'PD' && item.PaymentStatus == 'P'
      );
      let PaymentOrderIndividualDetails =
        PaymentOrderDetails?.length == 1 ? PaymentOrderDetails?.[0] : [];
      let paymentDeviceData = {
        TransactionNumber: PaymentOrderIndividualDetails?.['PaymentOrderId'],
        SequenceNumber: 1,
        AllowedPaymentMode:
          option === 'Card' ? '1' : option === 'UPI' ? '10' : '',
        Amount: `${parseInt(TotalNetAmount) * 100}`,
        ClientID: paymentDeviceAccess?.[0]?.['ClientId'],
        StoreID: paymentDeviceAccess?.[0]?.['StoreId'],
        UserID: SessionData?.UserId,
        MerchantID: paymentDeviceAccess?.[0]?.['MerchantId'],
        SecurityToken: paymentDeviceAccess?.[0]?.['SecurityToken'],
        IMEI: paymentDeviceAccess?.[0]?.['IMEI'],
        AutoCancelDurationInMinutes:
          paymentDeviceAccess?.[0]?.['AutoCancelDurationInMinutes'],
      };
      let apiresponse = await dispatch(
        postPaymentDevice(paymentDeviceData)
      ).unwrap();
      if (apiresponse?.ResponseMessage?.toLowerCase() === 'approved') {
        let pendingPaymentList = {
          MerchantID: paymentDeviceAccess?.[0]?.['MerchantId'],
          SecurityToken: paymentDeviceAccess?.[0]?.['SecurityToken'],
          ClientID: paymentDeviceAccess?.[0]?.['ClientId'],
          StoreID: paymentDeviceAccess?.[0]?.['StoreId'],
          IMEI: paymentDeviceAccess?.[0]?.['IMEI'],
          PlutusTransactionReferenceId:
            apiresponse?.PlutusTransactionReferenceID,
          PaymentOrderId: PaymentOrderIndividualDetails?.['PaymentOrderId'],
          UpdatedBy: SessionData?.UserId,
        };
        await dispatch(PutPendingPaymentList(pendingPaymentList)).unwrap();
        let isApproved = false;
        const startTime = Date.now();
        let postPaymentDeviceData = {
          MerchantID: paymentDeviceAccess?.[0]?.['MerchantId'],
          SecurityToken: paymentDeviceAccess?.[0]?.['SecurityToken'],
          ClientID: paymentDeviceAccess?.[0]?.['ClientId'],
          StoreID: paymentDeviceAccess?.[0]?.['StoreId'],
          IMEI: paymentDeviceAccess?.[0]?.['IMEI'],
          PlutusTransactionReferenceID:
            apiresponse?.PlutusTransactionReferenceID,
        };
        while (!isApproved) {
          let ApiResponseget = await dispatch(
            getPaymentDeviceResponse(postPaymentDeviceData)
          ).unwrap();
          if (
            ApiResponseget?.ResponseMessage?.toLowerCase() === 'txn approved'
          ) {
            let putPaymentDeviceData = {
              OrderBookingId: PaymentOrderIndividualDetails?.OrderId,
              OrderId: PaymentOrderIndividualDetails?.PaymentOrderId,
              PaymentStatus: 'S',
              Amount: PaymentOrderIndividualDetails?.Amount,
              AccountDtl: [paymentDeviceDetails?.data?.data],
              ResponseDtl: [ApiResponseget],
              PaymentType: PaymentOrderIndividualDetails?.PaymentType,
              UpdatedBy: SessionData?.UserId,
            };
            let putPaymentDeviceResponse = await dispatch(
              PutBookingPaymentStatusChange(putPaymentDeviceData)
            ).unwrap();
            if (putPaymentDeviceResponse?.data?.statusCode === 1) {
              setDevicePaymentStatus(true);
              await dispatch(
                changeOrderId(
                  putPaymentDeviceResponse?.data?.OrderDetails?.[0]?.SalesId
                    ? extractLastNumberOrderId(
                      putPaymentDeviceResponse?.data?.OrderDetails?.[0]
                        ?.SalesId,
                      putPaymentDeviceResponse?.data?.OrderDetails?.[0]
                        ?.FYStatus
                    )
                    : null
                )
              );
              setPrintOrderDetails([putPaymentDeviceResponse?.data]);
              clearAllStates();
            } else {
              setMessageType('error');
              setMessageData('Something went wrong, Please Contact Admin');
              setTimeout(function () {
                dispatch(changeKioskPageName('initialPage'));
                dispatch(changeAllGlbStatustData());
              }, 2000);
            }
            isApproved = true;
            console.log('Transaction Approved!');
            break;
          }

          if (
            Date.now() - startTime >
            paymentDeviceAccess?.[0]?.['AutoCancelDurationInMinutes'] * 60000
          ) {
            console.error('Transaction not approved within 1 minute.');
            let putPaymentDeviceFailureData = {
              OrderBookingId: PaymentOrderIndividualDetails?.OrderId,
              OrderId: PaymentOrderIndividualDetails?.PaymentOrderId,
              PaymentStatus: 'F',
              Amount: PaymentOrderIndividualDetails?.Amount,
              AccountDtl: [paymentDeviceDetails?.data?.data],
              ResponseDtl: [ApiResponseget],
              PaymentType: PaymentOrderIndividualDetails?.PaymentType,
              UpdatedBy: SessionData?.UserId,
            };
            await dispatch(
              PutBookingPaymentStatusChange(putPaymentDeviceFailureData)
            ).unwrap();

            if (response?.data?.PaymentOrderDtl?.length < 2) {
              setFailedTranId(PaymentOrderIndividualDetails?.OrderId);
              setMessageType('error');
              setMessageData('Payment Failed, Try again..');
            } else {
              setMessageType('error');
              setMessageData(
                'Your transaction limt exceeds, Please contact admin'
              );
              setTimeout(function () {
                dispatch(changeKioskPageName('initialPage'));
                dispatch(changeAllGlbStatustData());
              }, 2000);
            }
            setSelectedPaymentOption(null);
            break;
          }

          await new Promise((resolve) => setTimeout(resolve, 3000));
        }
      } else {
        let putPaymentDeviceFailureData = {
          OrderBookingId: PaymentOrderIndividualDetails?.OrderId,
          OrderId: PaymentOrderIndividualDetails?.PaymentOrderId,
          PaymentStatus: 'F',
          Amount: PaymentOrderIndividualDetails?.Amount,
          AccountDtl: [paymentDeviceDetails?.data?.data],
          ResponseDtl: [],
          PaymentType: PaymentOrderIndividualDetails?.PaymentType,
          UpdatedBy: SessionData?.UserId,
        };
        await dispatch(
          PutBookingPaymentStatusChange(putPaymentDeviceFailureData)
        ).unwrap();

        if (response?.data?.PaymentOrderDtl?.length < 2) {
          setFailedTranId(PaymentOrderIndividualDetails?.OrderId);
          setMessageType('error');
          setMessageData('Payment Failed, Try again..');
        } else {
          setMessageType('error');
          setMessageData('Your transaction limt exceeds, Please contact admin');
          setTimeout(function () {
            dispatch(changeKioskPageName('initialPage'));
            dispatch(changeAllGlbStatustData());
          }, 2000);
        }
        setSelectedPaymentOption(null);
      }
      if (response?.data?.SMSbody) {
        const postData = {
          body: response?.data?.SMSbody,
        };
        await dispatch(sendSms(postData));
      }
    } else {
      if (
        response?.data?.statusCode == 0 &&
        response?.data?.response == 'Order Limit Exceeded'
      ) {
        setMessageType('error');
        setMessageData('Order Limit Exceeded');
      } else {
        setMessageType('error');
        setMessageData('Something went wrong');
      }
      setTimeout(function () {
        dispatch(changeKioskPageName('initialPage'));
        dispatch(changeAllGlbStatustData());
      }, 2000);
    }
  };

  const handleGateway = async (paymentDetails, option, upiData) => {
    let bankDetails = {
      PayOpt: paymentGatewayMethods?.[selectedOption]?.PayOpt,
      CardType: paymentGatewayMethods?.[selectedOption]?.CardType,
      cardName: cardName,
    };
    if (
      (bankDetails?.PayOpt != undefined &&
        bankDetails?.CardType != undefined &&
        bankDetails?.cardName != undefined &&
        value !== undefined) ||
      option == 'UPI'
    ) {
      const paymentGatewayDetails = await dispatch(
        getPaymentGatewayDetails({
          AppId: SessionData.AppId,
          CompId: SessionData.CompId,
          BranchId: SessionData.BranchId,
          DetailType: 'P',
        })
      ).unwrap();
      const NotSlectedTypeFind = KioskOrderDetails?.find(
        (a) => a?.BookingType != SelectedBookingType
      );

      const modeId = await getModeId(
        paymentDetails,
        option == 'UPI'
          ? option
          : paymentGatewayMethods?.[selectedOption]?.ModeName,
        'Payment Gateway'
      );
      let putGatewaydata;
      if (FailedTranId || PGfailedId) {
        putGatewaydata = {
          CompId: SessionData.CompId,
          BranchId: SessionData.BranchId,
          AppId: SessionData.AppId,
          CustSuppId: CustomerMobileNumber,
          UpdatedBy: SessionData.UserId,
          OrderId: PGfailedId ? PGfailedId : FailedTranId,
          PaymentType: modeId,
          Amount: PGfailedId ? PGfailedAmt : TotalNetAmount,
          PaymentOptionType: 'PG',
          PaymentStatus: 'P',
          Debit: 0,
          Credit: 0,
          ModeOfPayment: null,
          AccountDtl: paymentGatewayDetails?.data?.data,
        };
      }
      let postGatewayData = {
        CompId: SessionData.CompId,
        BranchId: SessionData.BranchId,
        OrderType: 'O',
        MobileNo: CustomerMobileNumber,
        BookingType:
          NotSlectedTypeFind && !BookingTypeBoth
            ? NotSlectedTypeFind?.BookingType
            : SelectedBookingType,
        ActiveStatus: 'A',
        CreatedBy: SessionData.UserId,
        AppId: SessionData.AppId,
        RefundAmount: 0,
        BillAmount: TotalBillAmount,
        OverallDisc: 0,
        TaxAmount: TotalTaxAmount,
        VatAmount: 0,
        NetAmount: TotalNetAmount,
        PaymentType: 0,
        GivenAmt: 0,
        BalGiven: 0,
        BookingMedia: 'KW',
        PaymentStatus: 'P',
        OrderDtlDetails: KioskOrderDetails,
        Type: 0,
        Debit: 0,
        Credit: 0,
        SalesPaymentType: 'normal',
        PaymentDetail: [
          {
            Amount: TotalNetAmount,
            PaymentType: modeId,
            PaymentOptionType: 'PG',
            PaymentStatus: 'P',
            Debit: 0,
            Credit: 0,
            ModeOfPayment: null,
            AccountDtl: paymentGatewayDetails?.data?.data,
          },
        ],
      };
      let response;
      if (FailedTranId || PGfailedId) {
        response = await dispatch(PutKioskBookingData(putGatewaydata)).unwrap();
      } else {
        response = await dispatch(
          PostKioskBookingData(postGatewayData)
        ).unwrap();
      }
      if (response?.data?.statusCode == 1) {
        let PaymentOrderDetails = response?.data?.PaymentOrderDtl?.filter(
          (item) => item.PaymentOptionType == 'PG' && item.PaymentStatus == 'P'
        );
        let PaymentOrderIndividualDetails =
          PaymentOrderDetails?.length == 1 ? PaymentOrderDetails?.[0] : [];
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `${CustomPaymentUrl}/ccavRetailRequestHandler`;
        form.style.display = 'none'; // Hide the form
        console.log('upiDataupiData', upiData);
        const data1 = {
          merchant_id: paymentGatewayAccess?.[0]?.['MerchantId'],
          order_id: PaymentOrderIndividualDetails?.PaymentOrderId,
          currency: 'INR',
          amount: TotalNetAmount,
          redirect_url:
            'https://pozo.app/CustomPaymentGateway/CustomPaymentGateway/ccavRetailResponseHandler',
          cancel_url:
            'https://pozo.app/CustomPaymentGateway/CustomPaymentGateway/ccavRetailResponseHandler',
          payment_option:
            option == 'UPI'
              ? upiData?.[0]?.PayOpt
              : paymentGatewayMethods?.[selectedOption]?.PayOpt,
          card_type:
            option == 'UPI'
              ? upiData?.[0]?.CardType
              : paymentGatewayMethods?.[selectedOption]?.CardType,
          card_name: option == 'UPI' ? 'UPI' : cardName,
          data_accept:
            option == 'UPI'
              ? upiData?.[0]?.MethodDetails?.[0]?.DataAcceptedAt == 'CCAvenue'
                ? 'Y'
                : 'N'
              : dataAccept,
          language: 'EN',
          billing_name: 'User',
          billing_address: 'xyz',
          billing_city: 'xyz',
          billing_state: 'xyz',
          billing_zip: '000000',
          billing_country: 'India',
          billing_tel: CustomerMobileNumber,
          billing_email: 'xyz@gmail.com',
          delivery_name: '',
          delivery_address: SessionData?.AppId,
          delivery_city: 'K',
          delivery_zip: SessionData?.BranchId,
          delivery_country: modeId,
          delivery_tel: SessionData?.MobileNo,
          merchant_param1: SessionData?.userName,
          merchant_param2: PaymentOrderIndividualDetails?.OrderId,
          merchant_param3: SessionData?.UserId,
          merchant_param4: SessionData?.CompId,
          merchant_param5: 'paymentRetailHandler.html',
          promo_code: '',
          customer_identifier: '',
          workingKey: paymentGatewayAccess?.[0]?.['WorkingKey'], // Include the working key
          accessCode: paymentGatewayAccess?.[0]?.['AccessCode'],
        };
        console.log('data1data1', data1);
        Object.keys(data1).forEach((key) => {
          const input = document.createElement('input');
          input.type = 'hidden';
          input.name = key;
          input.value = encryptedValuesFun(data1[key]);
          form.appendChild(input);
        });

        document.body.appendChild(form);

        form.submit();
        if (response?.data?.SMSbody) {
          const postData = {
            body: response?.data?.SMSbody,
          };
          await dispatch(sendSms(postData));
        }
      } else {
        if (
          response?.data?.statusCode == 0 &&
          response?.data?.response == 'Order Limit Exceeded'
        ) {
          setMessageType('error');
          setMessageData('Order Limit Exceeded');
        } else {
          setMessageType('error');
          setMessageData('Something went wrong');
        }
        setTimeout(function () {
          dispatch(changeKioskPageName('initialPage'));
          dispatch(changeAllGlbStatustData());
        }, 2000);
      }
    } else {
      setMessageType('error');
      setMessageData('Please Select the Payment');
    }
  };
  const Print = async () => {
    const style = `<style> 
    *{
      font-family:Poppins;
    }

    .Kiosk-Print-body{  
      height: 100%;
      margin: 0vw 0vh;
      padding: 1vw 2vh;
    }

    
    .kiosk-print-title {
      font-size: 19px;
      font-weight: 600;
      font-family: Gilroy;
      margin-bottom: -10px;
      text-align:center;
    }

    .kiosk-print-Add {
      font-size: 12px;
      font-family: Poppins;
      margin-bottom: -5px;
    }

    .kiosk-print-GST {
      font-size: 9px;
      font-family: Poppins;
    }

    .kiosk-print-top {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 100%;
    }

    .kiosk-print-bill {
      display: flex;
      flex-direction: column;
      font-family: Gilroy;
    }
    

    .kiosk-print-bold{
      font-size: 12px;
      font-family: Poppins;
      letter-spacing: 1px;
    }
    
     

    </style>`;
    await printDiv('Kiosk-Print', style);
    await dispatch(changeKioskPageName('paymentPage'));
  };
  const PrintDevice = async () => {
    const style = await PrintStyleFunction(
      printerTemplateStyle == undefined ? 'Style 13' : printerTemplateStyle,
      'Sales'
    );
    const stylesMap = {
      'Style 1': 'PrintStyle1',
      'Style 2': 'PrintStyle2',
      'Style 3': 'PrintStyle3',
      'Style 4': 'PrintStyle4',
      'Style 5': 'PrintStyle5',
      'Style 6': 'PrintStyle6',
      'Style 7': 'PrintStyle7',
      'Style 8': 'PrintStyle8',
      'Style 9': 'PrintStyle9',
      'Style 10': 'PrintStyle10',
      'Style 11': 'PrintStyle11',
      'Style 12': 'PrintStyle12',
      'Style 13': 'RePrint',
      A4: 'PrintStyleA4',
      A5: 'PrintStyleA5',
      A4Standard: 'A4Standard',
    };

    const selectedStyle =
      stylesMap[
      printerTemplateStyle == undefined ? 'Style 13' : printerTemplateStyle
      ];
    if (selectedStyle) {
      await Promise.all(
        PrintOrderDetails?.[0]?.OrderDetails?.map(
          async (orderDetail, index) => {
            await printDiv(`${selectedStyle}-${index}`, style);

            if (orderDetail?.BookingTypeName !== 'Dine In') {
              const tokensToPrint = orderDetail?.productDetails?.map(
                async (item, idx) => {
                  if (item.TokenAvailable === 'Y') {
                    await TokenPrint(`${idx}-${item?.ProdId}`);
                  }
                }
              );

              if (tokensToPrint?.length > 0) {
                await Promise.all(tokensToPrint);
              }
            }
          }
        )
      );

      setPrintOrderDetails([]);
      await dispatch(changeKioskPageName('paymentPage'));
    }
    await dispatch(changeKioskPageName('initialPage'));
    await dispatch(changeAllGlbStatustData());
    ClearAllGlobalStateDatas();
  };
  const TokenPrint = async (index) => {
    try {
      console.log(`Starting token print for index ${index}`);

      const stylePrint = `<style> 
          *{
            font-family:Poppins;
          }
        
          .Reprint-body{  
            height: 100%;
            margin: 0vw 0vh;
            padding: 1vw 2vh;
          }
        
          .Re-print-body-Tr {
            text-align: center;
            font-family: Poppins;
          }
          .Re-print-body-Product{
            text-align:left;
            font-size:12px;
            border: 1px solid black;
            border-collapse: collapse;
            font-family: Poppins;
            padding-left:5px;
          }
          .Re-print-body-Rate{
            text-align:right;
              font-size:12px;
              padding-right:5px;
              border: 1px solid black;
              border-collapse: collapse;
              font-family: Poppins;
          }
          .Re-print-Logo{
            width: 50px ;
            height: 50px;
            margin-bottom: -20px;
           }
        
          .Re-print-title {
            font-size: 19px;
            font-weight: 600;
            font-family: Gilroy;
            margin-bottom: -10px;
            text-align:center;
          }
          
          .Re-print-Add {
            font-size: 12px;
            font-family: Poppins;
            margin-bottom: -5px;
          }
          
          .Re-print-GST {
            font-size: 12px;
            font-family: Poppins;
          }
        
          .Re-print-top {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
          }
        
          .Re-print-top2 {
            display: flex;
            width: 90%;
            margin:0px 10px;
            font-family: Gilroy;
            justify-content: space-between;
          }
          .Re-print-top3 {
            display: flex;
            width: 75%;
            margin:0px 30px;
            font-family: Gilroy;
            justify-content: space-between;
            margin-bottom: 5px;
          }
          .Re-print-bold{
            font-size: 8px;
            font-weight: 400;
            font-family: Poppins;
            letter-spacing: 1px;
          }
        
          .Re-print-bold1{
            font-size: 12px;
            font-weight: 600;
            font-family: Poppins;
            letter-spacing: 1px;
          }
          .Re-print-bold2{
            width:100%;
            font-size: 12px;
            font-family: Poppins;
            text-align:center;
          }
        
          .Re-print-Table {
              width: 90%;
              margin:0px 10px;
            }
        
          .Re-print-Table ,.Re-print-th ,.Re-print-td {
              border: 1px solid black;
              border-collapse: collapse;
              font-family: Poppins;
            }
            .Re-print-td
            {
              font-size:12px;
            }
        
          </style>`;
      await printDiv(`TakeawayToken${index}`, stylePrint);
    } catch (error) {
      console.error(`Error printing token for index ${index}:`, error);
    }
  };

  const HandleCloseModal = () => {
    if (FailedTranId || PGfailedId) {
      showDeleteConfirm();
    } else {
      props.handleCancel();
    }
  };
  const { confirm } = Modal;
  const showDeleteConfirm = () => {
    confirm({
      title: 'Are you sure cancel this order?',
      icon: <ExclamationCircleFilled />,
      content: '',
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      onOk() {
        console.log('OK');
        props.handleCancel();
        dispatch(changeKioskPageName('initialPage'));
        dispatch(changeAllGlbStatustData());
        dispatch(changePaymentgatewayRedirect(false));
        dispatch(changeKioskCustomerMobileNo(null));
        dispatch(changePGFailedTransId(null));
        dispatch(
          getKioskTemplate({
            AppId: SessionData.AppId,
            CompId: SessionData.CompId,
            BranchId: SessionData.BranchId,
          })
        ).unwrap();
        dispatch(
          getProductCategories({
            AppId: SessionData.AppId,
            CompId: SessionData.CompId,
            BranchId: SessionData.BranchId,
          })
        ).unwrap();
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const ClearAllGlobalStateDatas = () => {
    setSelectedPaymentOption(null);
    props.handleCancel();
    clearAllStates();
  };

  const sendOTP = async () => {
    const valid = isIndianMobile(number);
    if (valid) {
      if (isTimeLimitEnabled) {
        const withinTimeLimit = await checkLast30MinOrder(number);
        if (withinTimeLimit?.IsEligible === false) {
          setMessageData(withinTimeLimit?.response);
          setMessageType('warning');
          return;
        }
      }
    } else {
      setMessageData('Please enter valid mobile No.');
      setMessageType('warning');
      return
    }
    try {
      setOtpIndex(0);
      setOtpSent(true);
      let response = await dispatch(sendupiotp({
        "MobileNo": number,
        "CreatedBy": 0
      }))?.unwrap()
      if (response?.data?.statusCode == 1) {
        setMessageData('OTP sent to your mobile number');
        setMessageType('success');
        setOTPNumber(response?.data?.OTP);
        startResendTimer();
      }
    }
    catch (error) {
      console.log(error)
    }
  }

  const startResendTimer = () => {
    setCanResend(false);
    setResendTimer(30);
    const timer = setInterval(() => {
      setResendTimer((prev) => {
        if (prev <= 1) {
          clearInterval(timer);
          setCanResend(true);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  }

  const handleOtpChange = (e, index) => {
    const value = e.target.value.replace(/\D/g, '');

    const newOtp = [...otpInput];
    newOtp[index] = value;
    setOtpInput(newOtp);
  };

  const verifyOtp = () => {
    const enteredOtp = otpInput.join('');

    if (enteredOtp === otpNumber?.toString()) {
      setMessageType('success');
      setMessageData('OTP Verified Successfully');
      setOtpSent(false);
      setOtpInput(['', '', '', '']);
      setShowPaymentMethods(true);
      setOtpVerified(true);
    } else {
      setMessageType('error');
      setMessageData('Invalid OTP');
    }
  };

  return (
    <div>
      <Messages
        messageType={messageType}
        messageData={messageData}
        onComplete={onComplete}
      />
      <DefaultModal
        open={open}
        handleCancel={!selectedPaymentOption && HandleCloseModal}
        footer={false}
        width={width > 768 ? 800 : 600}
        children={
          showPaymentGatewayOptions ? (
            <div className="paymentCardMain">
              <div className="cardChooice">
                <div className="cardoption">
                  <div>
                    <div
                      className="titleofpay"
                      style={{
                        textAlign: 'center',
                        width: '100%',
                        fontSize: '22px',
                        fontWeight: '500',
                      }}
                    >
                      Payment Options
                    </div>
                  </div>
                </div>
                {paymentGatewayMethods?.map((item, index) => (
                  <div
                    className="cardoption"
                    key={index}
                    onClick={() => {
                      setselectedOption(index);
                      setItemsdata(
                        paymentGatewayMethods?.[index]?.MethodDetails
                      );
                      setValue(undefined);
                    }}
                    style={{
                      borderLeft:
                        selectedOption === index ? '5px solid #52C41A' : 'none',
                      backgroundColor:
                        selectedOption === index ? ' #52c41a2e' : ' ',
                      color: selectedOption === index ? ' #000' : ' ',
                    }}
                  >
                    <div>
                      {item?.ModeName == 'EMI' && <img src={Emi} alt="emi" />}
                      {item?.ModeName == 'CreditCard' && (
                        <img src={CrediCard} alt="CrediCard" />
                      )}
                      {item?.ModeName == 'DebitCard' && (
                        <img src={DebitCard} alt="DebitCard" />
                      )}
                      {item?.ModeName == 'NetBanking' && (
                        <img src={NetBank} alt="NetBanking" />
                      )}
                      {item?.ModeName == 'CashCard' && (
                        <img src={CashCard} alt="CashCard" />
                      )}
                      {item?.ModeName == 'Wallet' && (
                        <img src={Wallet} alt="Wallet" />
                      )}
                    </div>
                    <div
                      style={{
                        display: 'flex',
                        alignItems: 'flex-start',
                        flexDirection: 'column',
                      }}
                    >
                      <div className="cardname">{item?.ModeName}</div>
                      <div className="cardname2">
                        {' '}
                        Google Pay PhonePe & More
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              <div className="bankChooice">
                <div className="search-bar">
                  <div className="searchbar">
                    <CiSearch />
                    <Search
                      placeholder={
                        paymentGatewayMethods?.[selectedOption]?.CardType ==
                          'CRDC' ||
                          paymentGatewayMethods?.[selectedOption]?.CardType ==
                          'DBCRD'
                          ? 'Search Your Card'
                          : paymentGatewayMethods?.[selectedOption]?.CardType ==
                            'WLT'
                            ? 'Search Your Wallet'
                            : 'Search Your Bank'
                      }
                      onSearchChange={onSearchChange}
                    />
                  </div>
                  <div className="choosecardMain">
                    <div className="choosecard">
                      <div className="bankname">
                        <Collapse items={items} defaultActiveKey={['1']} />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div className="buttonOfpay">
                <div className="inr">INR ₹ {TotalNetAmount}</div>
                <Buttons
                  type="submit"
                  buttonText="PROCEED TO PAY"
                  className="sbmt-btn"
                  handleSubmit={() => {
                    handleGateway(PaymentOptionsData, 'Card', []);
                  }}
                  icon={<ArrowRightOutlined />}
                ></Buttons>
              </div>
            </div>
          ) : (
            <div className="paymentModal-Master">
              <h4 className="Titlepayment">{isOtpEnabled && !showPaymentMethods
                ? "Verify Mobile Number"
                : "PAYMENT"}</h4>
              <div className="paymentModal_main">
                {!otpSent && !otpVerifed && (<>
                  <div className="prompt">
                    <p style={{ fontFamily: 'Poppins', fontWeight: '600' }}>
                      Get your order bill on your mobile <br />
                      via SMS / Whatsapp
                    </p>
                  </div>

                  <div
                    className={`KioskPayment-inputModal ${number ? 'green-border' : ''}`}
                  >
                    <input type="text" value={number} readOnly />
                    {number?.length === 10 && !isIndianMobile(number) && <div className='input-err'>Please Enter Valid Mobile Number</div>}
                  </div>


                  {/* input boxxes */}
                  <div
                    className="KioskPayment-dailpad-main"
                    style={{
                      pointerEvents: selectedPaymentOption && 'none',
                      opacity: selectedPaymentOption && '40%',
                    }}
                  >
                    <div
                      className="Kiosk-dailpadModal"
                      style={{ backgroundColor: getKioskLightColourdata }}
                    >
                      <div className="KioskPayment-dailpad-1">
                        <p onClick={() => setNumberFun(1)}>1</p>
                        <p onClick={() => setNumberFun(2)}>2</p>
                        <p onClick={() => setNumberFun(3)}>3</p>
                      </div>
                      <div className="KioskPayment-dailpad-2">
                        <p onClick={() => setNumberFun(4)}>4</p>
                        <p onClick={() => setNumberFun(5)}>5</p>
                        <p onClick={() => setNumberFun(6)}>6</p>
                      </div>
                      <div className="KioskPayment-dailpad-3">
                        <p onClick={() => setNumberFun(7)}>7</p>
                        <p onClick={() => setNumberFun(8)}>8</p>
                        <p onClick={() => setNumberFun(9)}>9</p>
                      </div>
                      <div className="KioskPayment-dailpad-4">
                        <p onClick={handleBackspace}>
                          <HiOutlineBackspace
                            size={30}
                            style={{ marginBottom: '-2px' }}
                          />
                        </p>
                        <p onClick={() => setNumberFun(0)}>0</p>
                        <p style={{ background: 'none' }}></p>
                      </div>
                    </div>
                  </div>
                  {isOtpEnabled && (
                    <>
                      <button className='KioskOPTBTn'
                        // disabled={number?.length === 10}
                        onClick={() => sendOTP()}
                      >Get OTP</button>
                    </>
                  )}
                </>)}
                {(isOtpEnabled && otpSent) && (
                  <div className="otp-section">

                    {/* Mobile Number + Edit */}
                    <div className="otp-mobile-row">
                      <span className="otp-mobile-number">{number}</span>
                      <button
                        className="otp-edit-btn"
                        onClick={() => {
                          setOtpSent(false);
                          setOtpInput(['', '', '', '']);
                          setShowPaymentMethods(false);
                        }}
                      >
                        Edit
                      </button>
                    </div>

                    {/* 4 Digit OTP Input */}
                    <div className="otp-input-container">
                      {otpInput.map((digit, index) => (
                        <input
                          key={index}
                          type="text"
                          value={digit}
                          className={`otp-box ${index === otpIndex ? 'active' : ''}`}
                          onClick={() => setOtpIndex(index)}
                          readOnly
                        />
                      ))}
                    </div>
                    <div className="KioskPayment-dailpad-main">
                      <div
                        className="Kiosk-dailpadModal"
                        style={{ backgroundColor: getKioskLightColourdata }}
                      >
                        <div className="KioskPayment-dailpad-1">
                          <p onClick={() => handleOtpNumber(1)}>1</p>
                          <p onClick={() => handleOtpNumber(2)}>2</p>
                          <p onClick={() => handleOtpNumber(3)}>3</p>
                        </div>
                        <div className="KioskPayment-dailpad-2">
                          <p onClick={() => handleOtpNumber(4)}>4</p>
                          <p onClick={() => handleOtpNumber(5)}>5</p>
                          <p onClick={() => handleOtpNumber(6)}>6</p>
                        </div>
                        <div className="KioskPayment-dailpad-3">
                          <p onClick={() => handleOtpNumber(7)}>7</p>
                          <p onClick={() => handleOtpNumber(8)}>8</p>
                          <p onClick={() => handleOtpNumber(9)}>9</p>
                        </div>
                        <div className="KioskPayment-dailpad-4">
                          <p onClick={handleOtpBackspace}>
                            <HiOutlineBackspace size={30} />
                          </p>
                          <p onClick={() => handleOtpNumber(0)}>0</p>
                          <p style={{ background: 'none' }}></p>
                        </div>
                      </div>
                    </div>

                    {/* Buttons */}
                    <div className="otp-buttons">
                      <button
                        className="verify-btn"
                        disabled={otpInput.join('').length !== 4}
                        onClick={verifyOtp}
                      >
                        Verify
                      </button>

                      <button
                        className="resend-btn"
                        disabled={!canResend}
                        onClick={sendOTP}
                      >
                        {canResend ? "Resend OTP" : `Resend in ${resendTimer}s`}
                      </button>
                    </div>

                  </div>
                )}
                {(!isOtpEnabled || (showPaymentMethods && otpVerifed)) && <>
                  <p className="choiseTitle">Select Payment Method</p>
                  {console.log('selectedOption', selectedPaymentOption)}
                  <div
                    className="paymentChoise"
                    style={{
                      pointerEvents:
                        (!isIndianMobile(number) || selectedPaymentOption) &&
                        'none',
                      opacity:
                        (!isIndianMobile(number) || selectedPaymentOption) && '40%',
                    }}
                  >
                    {/* {upiAvailability && (
                    <div
                      className="upi"
                      onClick={() => handlePaymentOption('UPI')}
                    >
                      <img src={UPI} alt="" width={80} />
                      <p>UPI</p>
                    </div>
                  )} */}
                    {/* {cardAvailability && (
                    <div
                      className="upi"
                      onClick={() => handlePaymentOption('Card')}
                    >
                      <img src={Card} alt="" width={60} />
                      <p>CARD</p>
                    </div>
                  )} */}
                    {counterAvailability && (
                      <div
                        className="upi"
                        onClick={() => handlePaymentOption('Counter')}
                      >
                        <MdOutlinePayments size={50} opacity={0.5} />
                        <p style={{ fontSize: '12px', textAlign: 'center' }}>
                          PAY AT THE COUNTER
                        </p>
                      </div>
                    )}
                    {paymentOptionDetailsBusinessUpi && (
                      <div
                        className="upi"
                        onClick={() => handlePaymentOption('BU')}
                      >
                        <img src={UPI} alt="" width={60} />
                        <p> UPI</p>
                      </div>
                    )}
                    {!paymentOptionDetailsBusinessUpi && !counterAvailability && (
                      <div className="payment-error-msg">
                        Please Set Payment Options Contact Admin
                      </div>
                    )}
                  </div>
                </>}
              </div>
            </div>
          )
        }
      ></DefaultModal>
      {PrintOrderDetails?.length > 0 &&
        PrintOrderDetails?.[0]?.OrderDetails?.map((orderDetail, index) => (
          <div style={{ display: 'none' }}>
            <PaymentPdfBooking
              index={index}
              table2Data={orderDetail}
              singleData2={orderDetail?.productDetails}
              orderId={
                orderDetail?.OrderId &&
                extractLastNumberOrderId(
                  orderDetail?.OrderId,
                  orderDetail?.FYStatus
                )
              }
              CreatedDate={orderDetail?.CreatedDate}
              PaymentStatus={PrintOrderDetails?.[0]?.PaymentOrderDtl}
              Preference={SettingDataSelector}
            />
            {selectedPaymentOption == 'Counter' && (
              <KioskBookingReceipt
                BranchDetails={orderDetail}
                CreatedDate={orderDetail?.CreatedDate}
                OrderId={
                  orderDetail?.SalesId &&
                  extractLastNumberOrderId(
                    orderDetail?.SalesId,
                    orderDetail?.FYStatus
                  )
                }
              />
            )}
          </div>
        ))}
      {/* {paymentUrl != null && (
        <div className="payment-modal">
          <div className="modal-header">
            <h2>Complete Payment</h2>
            <button
              className="paymentclose-btn"
              onClick={() => {
                props.handleCancel();
                setpaymentUrl(null);
              }}
            >
              ✖
            </button>
          </div>

          <iframe
            src={paymentUrl}
            title="Payment"
            className="payment-frame"
          ></iframe>
        </div>
      )} */}

      <DefaultModal
        open={businessUPI}
        handleCancel={() => setShowCancelConfirm(true)}
        footer={false}
        width={500}
        children={
          <>
            <PaymentGatewayEmbedded
              orderId={TransctionId}
              setBusinessUPIOrderId={setTransctionId}
              businessUPILink={paymentUrl}
              setBusinessUPI={setBusinessUPI}
              setPaymentSuccess={setPaymentSuccess}
              paymentSucess={paymentSucess}
              ClearAllGlobalStateDatas={ClearAllGlobalStateDatas}
              // CustomerDisplay={CustomerDisplay}
              ref={paymentGatewayRef}
            />
          </>
        }
      />
      {showCancelConfirm && (
        <Modal
          open={showCancelConfirm}
          title="Cancel Payment"
          onOk={() => {
            paymentGatewayRef.current?.clearPolling();
            setBusinessUPI(false);
            setShowCancelConfirm(false);
            ClearAllGlobalStateDatas();
          }}
          onCancel={() => setShowCancelConfirm(false)}
          okText="Yes"
          cancelText="No"
        >
          Do you want to cancel the payment?
        </Modal>
      )}
    </div>
  );
};

export default KioskPayment;
