import React, { useState, useEffect, useCallback } from 'react';
import { Collapse, Radio } from 'antd';
import { ArrowRightOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import Emi from '../../../../Images/PayOptImgs/emi.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 Upi from '../../../../Images/PayOptImgs/upi.png';
import { IoPhonePortraitOutline } from 'react-icons/io5';
import { AiOutlineFileDone } from 'react-icons/ai';
import { CgMoreO } from 'react-icons/cg';
import '../../../../Styles/BookingScreen/Components/UtillComponents/PricingPage.scss';
import { CiSearch } from 'react-icons/ci';
import TextAreaInput from '../../../../Components/Forms/TextArea';
import Search from '../../../../Components/Forms/Search';
import { DefaultModal } from '../../../../Components/Modal/DefaultModal';
import { InputField } from '../../../../Components/Forms/InputField';
import {
  CheckPaymentStatus,
  getccavenuePaymentDetails,
  getPricingType,
  getPurchasedAppDetails,
  getUserDetails,
  postInvoice,
} from '../../../../Features/BookingScreen/Pricing/Pricing';
import Buttons from '../../../../Components/Forms/Buttons';
import {
  getPreferenceData,
  GlobalAppExpDateData,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
import { Messages } from '../../../../Components/Notifications/Messages';
import CryptoJS from 'crypto-js';
import { GenerateLogout } from '../../../../Features/BrachLogin/BranchLogin';
import { getActivePaymentUpiDetails, sendSms } from '../../../../Features/Payment/PaymentDetails/PaymentDetails';
import {
  clearSession,
  encryptedValuesUrlFun,
  getSession,
} from '../../../../Services/Others';
import PaymentGatewayEmbedded from './PaymentGatewayEmbedded';

const SECRET_KEY = import.meta.env.ENV_SECRET_KEY;
const commonSubDir = import.meta.env.ENV_COMMON_BASE_URL;
const CustomPaymentUrl = import.meta.env.ENV_CUSTOM_PAYMENT_URL;
const subDirectory = import.meta.env.ENV_BASE_URL;
const PricingPage = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const [PricingId, setPricingId] = useState(
    getSession('PricingId') ? getSession('PricingId') : null
  );
  const [activeBusinessUpiDetails, setActiveBusinessUpiDetails] = useState([]);
  const AppExpDate = useSelector(GlobalAppExpDateData);
  const UserType = getSession('UserType');
  const UserId =
    UserType == 'Admin' ? getSession('UserId') : AppExpDate?.UserId;
  const CompId = getSession('CompId');
  const AppName = getSession('AppName');
  const AppId = getSession('AppId');
  const BranchId = getSession('BranchId');
  const [MobileNo, setMobileNo] = useState(getSession('MobileNo'));
  const [invoiceDetails, setinvoiceDetails] = useState([]);
  const [UserDetails, setUserDetails] = useState([]);
  const [BookingId, setBookingId] = useState(null);
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [timeLeft, setTimeLeft] = useState(null);
  const [Buttondisabled, setButtondisabled] = useState(false);
  const [CompanyName, setCompanyName] = useState(null);
  const [zipcode, setzipcode] = useState(null);
  const [address, setaddress] = useState(null);
  const [City, setCity] = useState(null);
  const [Dist, setDist] = useState(null);
  const [State, setState] = useState(null);
  const [email, setemail] = useState(null);
  const [zipcondit, setZipcondit] = useState(true);
  const [gstcondit, setgstcondit] = useState(true);
  const [emailcondit, setemailcondit] = useState(true);
  const [citycondit, setcitycondit] = useState(true);
  const [statecondit, setstatecondit] = useState(true);
  const [addresscondit, setaddresscondit] = useState(true);
  const [gst, setgst] = useState(null);
  const [PaymentDetails, setPaymentDetails] = useState();
  const [selectedOption, setselectedOption] = useState();
  const [value, setValue] = useState();
  const [itemsdata, setItemsdata] = useState();
  const [dataAccept, setDataAccept] = useState();
  const [cardName, setCardName] = useState();
  const [moreInfo, setmoreInfo] = useState(false);
  const [currentDate, setCurrentDate] = useState('');
  const [PurchasedDetails, setPurchasedDetails] = useState([]);
  const [Companydetails, setCompanydetails] = useState([]);
  const [delay, setDelay] = useState(null);
  const [businessUpiModal, setBusinessUpiModal] = useState(false);
  const [paymentSucess, setPaymentSuccess] = useState(false);
  const [OrderId, setOrderId] = useState(null);
  const [PaymentPageLink, setPaymentPageLink] = useState(null);
  const Gstpattern =
    /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Za-z]{1}[Z]{1}[0-9A-Za-z]{1}$/;
  const numberPattern = /^[0-9]+$/;
  const [PayableAmount, setPayableAmount] = useState(0);

  useEffect(() => {
    setPayableAmount(invoiceDetails[0]?.NetPrice);
  }, [invoiceDetails]);
  useEffect(() => {
    if (!paymentSucess) return;

    const timeoutId = setTimeout(() => {
      setPaymentSuccess(false);
      redirectAfterPay();
    }, 3000);

    return () => clearTimeout(timeoutId);

  }, [paymentSucess]);
  const redirectAfterPay = () => {
    navigate(`${subDirectory}sales`);
  }
  useEffect(() => {
    fetchData();
    GetPaymentDetails();
    fetchUpiDetails()

  }, []);
  async function fetchUpiDetails() {
    try {
      const response = await dispatch(getActivePaymentUpiDetails()).unwrap();
      if (response?.data?.statusCode == 1) {
        setActiveBusinessUpiDetails(response?.data?.data?.filter((e) => e?.DetailType == "BU"));
      }
    }
    catch (error) {
      console.log(error, "errorerrorerror")
    }

  }
  useEffect(() => {
    if (UserDetails?.[0]?.MailId) {
      setemail(UserDetails?.[0]?.MailId);
    }
  }, [UserDetails]);

  let GetPaymentDetails = async () => {
    const response = await dispatch(getccavenuePaymentDetails()).unwrap();
    if (response?.data?.statusCode == 1) {
      setPaymentDetails(response?.data?.data);
      let index = await response?.data?.data?.findIndex(
        (item) => item.MethodName == 'NetBanking'
      );
      setselectedOption(index);
      setItemsdata(response?.data?.data?.[index]?.Details);
    }
  };
  let fetchData = async () => {
    let response = await dispatch(
      getPurchasedAppDetails({ AppId, UserId })
    ).unwrap();
    let response1 = await dispatch(
      getPreferenceData({ AppId, BranchId, CompId,UserId })
    ).unwrap();
    setPurchasedDetails(response?.data?.data);
    setCompanydetails(response1?.data?.data);
    setPricingId(response?.data?.data?.[0]?.PricingId);
  };
  useEffect(() => {
    const timer = setInterval(() => {
      setDelay(delay - 1);
    }, 1000);
    if (BookingId != null) {
      checkPayment();
    }

    if (delay === 0) {
      UpdatePaymentStatus();
      clearInterval(timer);
    }

    if (delay === null) {
      clearInterval(timer);
    }

    return () => {
      clearInterval(timer);
    };
  }, [delay]);

  const handleCancel = () => {
    setmoreInfo(false);
  };

  const encryptedValuesFun = (value) => {
    const encryptedValue = CryptoJS.AES.encrypt(
      JSON.stringify(value),
      SECRET_KEY
    ).toString();

    if (encryptedValue) {
      return encryptedValue
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=+$/, ''); // Base64 URL-safe encoding
    }
  };
  const UpdatePaymentStatus = async () => {
    let putdata = {};
    putdata['UpdatedBy'] = getSession('UserId');
    putdata['PaymentStatus'] = 'F';
    putdata['UniqueId'] = BookingId;
  };

  const checkPayment = async () => {
    let response = await dispatch(CheckPaymentStatus(BookingId)).unwrap();
    if (response?.data?.statusCode === 1) {
      setprintdata(response?.data?.data);
      setPaymentStatus(true);
      setDelay(null);
      setMessageType('success');
      setMessageData('Payment Success!');
      setTimeout(() => {
        redirectAfterPay();
      }, 15000);
    }
  };

  useEffect(() => {
    if (timeLeft === 0) {
      setButtondisabled(false);

      setTimeLeft(null);
    }

    // exit early when we reach 0
    if (!timeLeft) return;

    // save intervalId to clear the interval when the
    // component re-renders
    const intervalId = setInterval(() => {
      setTimeLeft(timeLeft - 1);
    }, 1000);

    // clear interval on re-render to avoid memory leaks
    return () => clearInterval(intervalId);
  }, [timeLeft]);

  useEffect(() => {
    fetchFeature(PricingId);
  }, [PricingId]);

  useEffect(() => {
    getUserDetail();
  }, []);

  const fetchFeature = async (PricingId) => {
    const response = await dispatch(getPricingType(PricingId)).unwrap();
    if (response?.data?.statusCode === 1) {
      setinvoiceDetails(response?.data?.data);
    }
  };

  const getUserDetail = async () => {
    const response = await dispatch(getUserDetails(UserId)).unwrap();
    if (response?.data?.statusCode === 1) {
      setUserDetails(response?.data?.data ? response?.data?.data : []);
      setMobileNo(
        response?.data?.data?.[0]?.MobileNo > 0
          ? response?.data?.data?.[0]?.MobileNo
          : getSession('MobileNo')
      );
    }
  };

  function addDays(dateString, days) {
    const currentDate = new Date(dateString);
    currentDate.setDate(currentDate.getDate() + days);

    // Extract individual date components
    const year = currentDate.getFullYear();
    const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
    const day = currentDate.getDate().toString().padStart(2, '0');
    const hours = currentDate.getHours().toString().padStart(2, '0');
    const minutes = currentDate.getMinutes().toString().padStart(2, '0');
    const seconds = currentDate.getSeconds().toString().padStart(2, '0');
    const milliseconds = currentDate
      .getMilliseconds()
      .toString()
      .padStart(3, '0');

    // Construct the formatted date string
    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;

    return formattedDate;
  }

  const onSubmit = async () => {
    let bankDetails = {
      PayOpt: PaymentDetails?.[selectedOption]?.PayOpt,
      CardType: PaymentDetails?.[selectedOption]?.CardType,
      cardName:
        PaymentDetails?.[selectedOption]?.CardType != 'UPI' ? cardName : 'UPI',
    };
    if (!email) {
      setMessageType('error');
      setMessageData('Please Enter Email');
    } else {
      if (
        bankDetails?.PayOpt != undefined &&
        bankDetails?.CardType != undefined &&
        bankDetails?.cardName != undefined
      ) {
        let postData = {};
        postData['UserId'] = UserId;
        postData['AppId'] = getSession('AppId');
        postData['PricingId'] = PurchasedDetails?.[0]?.PricingId;
        postData['PurDate'] = currentDate;
        postData['NoofDays'] = PurchasedDetails?.[0]?.NoOfDays;
        postData['PaymentMode'] = 27;
        postData['PaymentStatus'] = 'P';
        postData['LicenseStatus'] = PurchasedDetails?.[0]?.LicenseStatus;
        postData['Price'] = PurchasedDetails?.[0]?.Price
          ? PurchasedDetails?.[0]?.Price
          : 0;
        postData['TaxId'] = PurchasedDetails?.[0]?.TaxId
          ? PurchasedDetails?.[0]?.TaxId
          : 0;
        postData['NetPrice'] = PurchasedDetails?.[0]?.ExistingPlanNetPrice
          ? PurchasedDetails?.[0]?.ExistingPlanNetPrice
          : 0;
        postData['ValidityStart'] = currentDate;
        postData['ValidityEnd'] = addDays(
          currentDate,
          PurchasedDetails?.[0]?.NoOfDays
        );
        postData['CreatedBy'] = getSession('UserId');
        postData['TaxAmount'] = PurchasedDetails?.[0]?.TaxAmount
          ? PurchasedDetails?.[0]?.TaxAmount
          : 0;
        postData['MobileNo'] = getSession('MobileNo');
        postData['MailId'] = email;
        postData['Gst'] = Gstpattern?.test(gst) ? gst : null;
        postData['BillingName'] = Companydetails?.[0]?.CompName;
        postData['Zip'] = numberPattern.test(zipcode) ? zipcode : null;
        postData['City'] = City;
        postData['State'] = State;
        postData['Address'] = address;
        postData['District'] = Dist;

        let response = await dispatch(postInvoice(postData)).unwrap();
        if (response?.data?.statusCode == 1) {
          if (response?.data?.SMSbody) {
            const postData = {
              body: response?.data?.SMSbody,
            };
            await dispatch(sendSms(postData));
          }
          setBookingId(response?.data?.BookingId);
          const form = document.createElement('form');
          form.method = 'POST';
          form.action = `${CustomPaymentUrl}/ccavRequestHandler`;
          form.style.display = 'none'; // Hide the form

          const data1 = {
            merchant_id: '15191',
            order_id: response?.data?.OrderId,
            currency: 'INR',
            amount: PayableAmount,
            redirect_url:
              'https://pozo.app/CustomPaymentGateway/CustomPaymentGateway/ccavResponseHandler',
            cancel_url:
              'https://pozo.app/CustomPaymentGateway/CustomPaymentGateway/ccavResponseHandler',
            payment_option: PaymentDetails?.[selectedOption]?.PayOpt,
            card_type: PaymentDetails?.[selectedOption]?.CardType,
            card_name:
              PaymentDetails?.[selectedOption]?.CardType != 'UPI'
                ? cardName
                : 'UPI',
            data_accept: dataAccept,
            language: 'EN',
            billing_name:
              Companydetails?.[0]?.CompName != null
                ? Companydetails?.[0]?.CompName
                : 'User',
            billing_address: address != null ? address : 'xyz',
            billing_city: City != null ? City : 'xyz',
            billing_state: State != null ? State : 'xyz',
            billing_zip: zipcode != null ? zipcode : '000000',
            billing_country: 'India',
            billing_tel: MobileNo,
            billing_email: email,
            delivery_name: 'R',
            delivery_address: 'N',
            delivery_city: Dist != null ? Dist : 'xyz',
            delivery_zip: 'O',
            delivery_country: 'India',
            delivery_tel: Gstpattern?.test(gst) ? gst : null,
            merchant_param1: getSession('SessionId'),
            merchant_param2: response?.data?.BookingId,
            merchant_param3: getSession('UserId'),
            merchant_param4: invoiceDetails?.[0]?.PricingName,
            merchant_param5: 'paymentHandler.html',
            promo_code: '',
            customer_identifier: '',
          };

          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();
        }
      } else {
        setMessageType('error');
        setMessageData('Please Select the Payment');
      }
    }
  };
  const onSubmitBusinessUpi = async () => {
    let bankDetails = {
      PayOpt: PaymentDetails?.[selectedOption]?.PayOpt,
      CardType: PaymentDetails?.[selectedOption]?.CardType,
      cardName:
        PaymentDetails?.[selectedOption]?.CardType != 'UPI' ? cardName : 'UPI',
    };
    if (!email) {
      setMessageType('error');
      setMessageData('Please Enter Email');
    } 
    else {
     
        let postData = {};
        postData['UserId'] = UserId;
        postData['AppId'] = getSession('AppId');
        postData['PricingId'] = PurchasedDetails?.[0]?.PricingId;
        postData['PurDate'] = currentDate;
        postData['NoofDays'] = PurchasedDetails?.[0]?.NoOfDays;
        postData['PaymentMode'] = 27;
        postData['PaymentStatus'] = 'P';
        postData['LicenseStatus'] = PurchasedDetails?.[0]?.LicenseStatus;
        postData['Price'] = PurchasedDetails?.[0]?.Price
          ? PurchasedDetails?.[0]?.Price
          : 0;
        postData['TaxId'] = PurchasedDetails?.[0]?.TaxId
          ? PurchasedDetails?.[0]?.TaxId
          : 0;
        postData['NetPrice'] = PurchasedDetails?.[0]?.ExistingPlanNetPrice
          ? PurchasedDetails?.[0]?.ExistingPlanNetPrice
          : 0;
        postData['ValidityStart'] = currentDate;
        postData['ValidityEnd'] = addDays(
          currentDate,
          PurchasedDetails?.[0]?.NoOfDays
        );
        postData['CreatedBy'] = getSession('UserId');
        postData['TaxAmount'] = PurchasedDetails?.[0]?.TaxAmount
          ? PurchasedDetails?.[0]?.TaxAmount
          : 0;
        postData['MobileNo'] = getSession('MobileNo');
        postData['MailId'] = email;
        postData['Gst'] = Gstpattern?.test(gst) ? gst : null;
        postData['BillingName'] = Companydetails?.[0]?.CompName;
        postData['Zip'] = numberPattern.test(zipcode) ? zipcode : null;
        postData['City'] = City;
        postData['State'] = State;
        postData['Address'] = address;
        postData['District'] = Dist;
        postData["PaymentOptionType"] = "BU";
        postData["MerchantId"] = activeBusinessUpiDetails?.[0]?.MerchantId;
        postData["PaymentType"] = activeBusinessUpiDetails?.[0]?.MerchantNameId;

        let response = await dispatch(postInvoice(postData)).unwrap();
        if (response?.data?.statusCode == 1) {
          if (response?.data?.SMSbody) {
            const postData = {
              body: response?.data?.SMSbody,
            };
            await dispatch(sendSms(postData));
          }
          setBusinessUpiModal(true)
          setOrderId(response?.data?.OrderId)
          setPaymentPageLink(response?.data?.PaymentPageLink)
        }
      
       
    }
  };

  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const setCompanyNames = async (e) => {
    setCompanyName(e?.target?.value);
  };

  const setCitys = async (e) => {
    setCity(e?.target?.value);
    setcitycondit(true);
  };
  const setStates = async (e) => {
    setState(e?.target?.value);
    setstatecondit(true);
  };

  const setgsts = async (e) => {
    setgst(e);
  };
  function checkCondition1(input) {
    if (input?.length === 15 && Gstpattern?.test(input)) {
      setgstcondit(true);
      setgsts(input);
    } else if (input?.length === 0) {
      setgstcondit(true);
    } else {
      setgstcondit(false);
    }
    setgsts(input);
  }

  function isValidEmail(email) {
    const emailRegex =
      /^[a-zA-Z0-9._%+-]{1,64}@[a-zA-Z0-9.-]{1,255}\.[a-zA-Z]{2,}$/;
    return emailRegex.test(email);
  }

  const getViewMore = () => {
    setmoreInfo(!moreInfo);
  };

  function handleInputChange(event) {
    // setemail(event?.target?.value)
    if (isValidEmail(event?.target?.value)) {
      setemailcondit(true);
      setEmailValue(event?.target?.value);
    } else {
      setemail(undefined);
      setemailcondit(false);
    }
  }

  const setaddresss = async (e) => {
    setaddress(e?.target?.value);
    setaddresscondit(true);
  };
  const setzipcodes = async (e) => {
    setzipcode(e);
  };
  const setEmailValue = async (e) => {
    setemail(e);
  };

  const getPincodeValues = async (pinCode) => {
    let response = '';
    await fetch(`https://api.postalpincode.in/pincode/${pinCode}`)
      .then((res) => res.text())
      .then((text) => (response = JSON.parse(text)));

    if (response[0]['Status'] === 'Success') {
      setCity(response[0]['PostOffice'][0]['Block']);
      setDist(response[0]['PostOffice'][0]['District']);
      setState(response[0]['PostOffice'][0]['State']);
      setcitycondit(true);
      setstatecondit(true);
    }
  };

  async function checkCondition(input) {
    if (input?.length === 6 && numberPattern.test(input)) {
      setZipcondit(true);
      setzipcodes(input);
      await getPincodeValues(input);
    } else if (input?.length === 0) {
      setZipcondit(true);
    } else {
      setZipcondit(false);
      setCity(null);
      setState(null);
    }
    setzipcodes(input);
  }

  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 = PaymentDetails?.[selectedOption]?.Details;
    let searchTerm = e.target.value?.toLowerCase();

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

    setItemsdata(updated);
  };

  const items = [
    {
      key: '1',
      label: `${
        PaymentDetails?.[selectedOption]?.CardType == 'CRDC' ||
        PaymentDetails?.[selectedOption]?.CardType == 'DBCRD'
          ? 'Choose Your Card'
          : PaymentDetails?.[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>
      ),
    },
  ];
  useEffect(() => {
    const fetchDate = () => {
      const now = new Date();
      // const formattedDate = now.toISOString();
      const formattedDate = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}.${now.getMilliseconds().toString().padStart(3, '0')}`;

      setCurrentDate(formattedDate);
    };

    fetchDate();
  }, []);

  //  const navigatetoPricing = async () => {
  //      // navigate(`${commonSubDir}/home/${AppName}`, { state: { AppName: AppName } })
  //      // window.location.reload();
  //      const UserId = getSession('UserId')
  //      const status = "N"; // replace with your actual status
  //      const res = await dispatch(GenerateLogout({UserId,status})).unwrap();
  //      if (res?.data?.statusCode === 1) {
  //       window.location.replace(`${commonSubDir}/home/${AppName}`, { state: { AppName: AppName } });
  //      }
  //   }
  const navigatetoPricing = async () => {
    // navigate(`${commonSubDir}/home/${AppName}`, { state: { AppName: AppName } })
    // window.location.reload();
    const MobileNo = encryptedValuesUrlFun(getSession('MobileNo'));
    const userName = encryptedValuesUrlFun(getSession('userName'));
    const UserId = encryptedValuesUrlFun(getSession('UserId'));
    const UserType = encryptedValuesUrlFun(getSession('UserType'));
    const CompId = encryptedValuesUrlFun(getSession('CompId'));
    const CompName = encryptedValuesUrlFun(getSession('CompName'));
    const SessionId = encryptedValuesUrlFun(getSession('SessionId'));
    const AdminId = encryptedValuesUrlFun(
      UserType == 'Admin' ? getSession('UserId') : AppExpDate?.UserId
    );
    if (sessionStorage.getItem('BranchId') !== null) {
      clearSession('BranchId');
    }
    if (sessionStorage.getItem('AppId') !== null) {
      clearSession('AppId');
    }
    if (sessionStorage.getItem('hasRefreshed') !== null) {
      sessionStorage.removeItem('hasRefreshed');
    }
    const param = {
      MN: MobileNo,
      UN: userName,
      UD: UserId,
      UT: UserType,
      CD: CompId,
      CN: CompName,
      SD: SessionId,
      AD: AdminId,
    };
    const queryParams = new URLSearchParams(param).toString();
    window.location.replace(`${commonSubDir}/home/${AppName}?${queryParams}`);
  };

  return (
    <>
      <div className="Invoice-details-bg">
        <div className="Invoice-details-pricedetails">
          <Messages
            messageType={messageType}
            messageData={messageData}
            onComplete={onComplete}
          />
          <div className="pricedetails-div">
            <div
              style={{
                background: ' ',
                display: 'flex',
                flexDirection: 'row',
                justifyContent: 'space-around',
              }}
            >
              {activeBusinessUpiDetails?.length == 0 && <div
                style={{
                  background: ' ',
                  display: 'flex',
                  flexDirection: 'column',
                  rowGap: '1rem',
                }}
              >
                <div
                  style={{
                    backgroundColor: '#52c41a2e',
                    padding: '1rem 1rem',
                    borderRadius: '10px',
                    display: 'flex',
                    flexDirection: 'row',
                    rowGap: '2rem',
                    justifyContent: 'space-between',
                  }}
                >
                  <div
                    style={{
                      display: 'flex',
                      flexDirection: 'column',
                      rowGap: '0.2rem',
                    }}
                  >
                    <div>
                      <button
                        className="planchange-btn"
                        onClick={navigatetoPricing}
                      >
                        Change Plan
                      </button>
                    </div>

                    <div
                      style={{
                        display: 'flex',
                        fontFamily: 'Gilroy',
                        fontSize: 'clamp(18px, 2.5vw, 25px)',
                        fontWeight: '600',
                        color: 'green',
                        borderRadius: '3px',
                        alignItems: 'center',
                        columnGap: '0.2rem',
                      }}
                    >
                      <AiOutlineFileDone />
                      {PurchasedDetails?.[0]?.PricingName} /{' '}
                      {PurchasedDetails?.[0]?.NoOfDays > 30
                        ? 'Yearly'
                        : 'Monthly'}
                    </div>
                    <div>
                      <div
                        style={{
                          display: 'flex',
                          alignItems: 'center',
                          columnGap: '0.5rem',
                          color: 'green',
                        }}
                      >
                        <p
                          style={{
                            fontSize: 'clamp(16px, 2.5vw, 20px)',
                            fontWeight: '500',
                          }}
                        >
                          {PurchasedDetails?.[0]?.ExistingPlanNetPrice > 0
                            ? `₹ ${PurchasedDetails?.[0]?.ExistingPlanNetPrice}`
                            : '₹ 0.00'}
                        </p>
                        <p> to Pay </p>
                      </div>
                    </div>
                  </div>

                  <div>
                    <div className={emailcondit ? 'NoError' : 'ShowError'}>
                      {UserDetails?.[0]?.MailId ? (
                        <p
                          style={{
                            fontSize: 'clamp(16px, 2.5vw, 17px)',
                            fontWeight: '500',
                            color: 'green',
                          }}
                        >
                          {UserDetails?.[0]?.MailId}
                        </p>
                      ) : (
                        <div>
                          <InputField
                            fieldState={true}
                            fieldApi={true}
                            autocomplete="off"
                            value={email}
                            label="Email"
                            className="mailInpt"
                            id="Email"
                            field="Email"
                            onChange={handleInputChange}
                          />
                          {emailcondit ? (
                            ''
                          ) : (
                            <p
                              style={{
                                color: '#FF4D4F',
                                fontSize: '12px',
                                margin: '-10px 0px 0px 13px',
                              }}
                            >
                              Enter Valid Email
                            </p>
                          )}
                        </div>
                      )}
                    </div>

                    <div
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        columnGap: '0.2rem',
                        fontSize: '20px',
                        fontWeight: '600',
                        color: 'green',
                      }}
                    >
                      <IoPhonePortraitOutline />
                      <p
                        style={{
                          fontFamily: 'Poppins',
                          fontSize: 'clamp(16px, 2.5vw, 20px)',
                          fontWeight: '500',
                          color: 'green',
                          borderRadius: '3px',
                        }}
                      >
                        {' '}
                        {MobileNo ? MobileNo : ''}
                      </p>
                    </div>

                    <div
                      style={{
                        display: 'flex',
                        justifyContent: 'flex-end',
                        textDecoration: 'underline',
                        color: 'green',
                        fontSize: '12px',
                        cursor: 'pointer',
                        columnGap: '0.2rem',
                        alignItems: 'center',
                      }}
                      onClick={getViewMore}
                    >
                      More Info <CgMoreO />{' '}
                    </div>

                    {moreInfo && (
                      <>
                        <DefaultModal
                          open={moreInfo}
                          footer={false}
                          children={
                            <>
                              <div>
                                <div
                                  style={{
                                    display: 'flex',
                                    flexWrap: 'wrap',
                                    gap: '1rem',
                                  }}
                                  className="adduserinfo"
                                >
                                  <div>
                                    <InputField
                                      fieldState={true}
                                      fieldApi={true}
                                      autocomplete="off"
                                      label="Company / Billing Name"
                                      id="Company"
                                      field="Company"
                                      value={CompanyName}
                                      isOnChange={CompanyName ? true : false}
                                      onChange={(e) => setCompanyNames(e)}
                                    />
                                  </div>
                                  <div
                                    className={
                                      addresscondit ? 'NoError' : 'ShowError'
                                    }
                                  >
                                    <div>
                                      <TextAreaInput
                                        field="Address"
                                        autoComplete="off"
                                        label="Address"
                                        fieldState={true}
                                        fieldApi={true}
                                        value={address}
                                        isOnChange={address ? true : false}
                                        onChange={(e) => setaddresss(e)}
                                      />
                                      {addresscondit ? (
                                        ''
                                      ) : (
                                        <p
                                          style={{
                                            color: '#FF4D4F',
                                            fontSize: '12px',
                                            margin: '-10px 0px 0px 13px',
                                          }}
                                        >
                                          Enter Address
                                        </p>
                                      )}
                                    </div>
                                  </div>

                                  <div
                                    className={
                                      gstcondit ? 'NoError' : 'ShowError'
                                    }
                                  >
                                    <div>
                                      <InputField
                                        fieldState={true}
                                        fieldApi={true}
                                        autocomplete="off"
                                        type="numeric"
                                        label="GST"
                                        value={gst}
                                        isOnChange={gst ? true : false}
                                        onChange={(e) =>
                                          checkCondition1(e?.target?.value)
                                        }
                                      />
                                      {gstcondit ? (
                                        ''
                                      ) : (
                                        <p
                                          style={{
                                            color: '#FF4D4F',
                                            fontSize: '12px',
                                            margin: '-10px 0px 0px 13px',
                                          }}
                                        >
                                          Enter Valid Gst
                                        </p>
                                      )}
                                    </div>
                                  </div>

                                  <div
                                    className={
                                      zipcondit ? 'NoError' : 'ShowError'
                                    }
                                  >
                                    <div>
                                      <InputField
                                        fieldState={true}
                                        fieldApi={true}
                                        autocomplete="off"
                                        type="numeric"
                                        label="Zip"
                                        maxLength="6"
                                        value={zipcode}
                                        isOnChange={zipcode ? true : false}
                                        onChange={(e) =>
                                          checkCondition(e?.target?.value)
                                        }
                                      />
                                      {zipcondit ? (
                                        ''
                                      ) : (
                                        <p
                                          style={{
                                            color: '#FF4D4F',
                                            fontSize: '12px',
                                            margin: '-10px 0px 0px 13px',
                                          }}
                                        >
                                          Enter Valid Zipcode
                                        </p>
                                      )}
                                    </div>
                                  </div>

                                  <div
                                    className={
                                      citycondit ? 'NoError' : 'ShowError'
                                    }
                                  >
                                    <div>
                                      <InputField
                                        fieldState={City ? City : false}
                                        fieldApi={true}
                                        autocomplete="off"
                                        label="City"
                                        id="city"
                                        field="city"
                                        onChange={(e) =>
                                          setCitys(e?.target?.value)
                                        }
                                        value={City}
                                        isOnChange={City ? true : false}
                                        disabled={City ? true : false}
                                      />
                                      {citycondit ? (
                                        ''
                                      ) : (
                                        <p
                                          style={{
                                            color: '#FF4D4F',
                                            fontSize: '12px',
                                            margin: '-10px 0px 0px 13px',
                                          }}
                                        >
                                          Enter City
                                        </p>
                                      )}
                                    </div>
                                  </div>

                                  <div
                                    className={
                                      statecondit ? 'NoError' : 'ShowError'
                                    }
                                  >
                                    <div>
                                      <InputField
                                        fieldState={State ? State : false}
                                        fieldApi={true}
                                        autocomplete="off"
                                        label="State"
                                        id="state"
                                        field="state"
                                        onChange={(e) =>
                                          setStates(e?.target?.value)
                                        }
                                        value={State}
                                        isOnChange={State ? true : false}
                                        disabled={State ? true : false}
                                      />
                                      {statecondit ? (
                                        ''
                                      ) : (
                                        <p
                                          style={{
                                            color: '#FF4D4F',
                                            fontSize: '12px',
                                            margin: '-10px 0px 0px 13px',
                                          }}
                                        >
                                          Enter State
                                        </p>
                                      )}
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </>
                          }
                          handleCancel={handleCancel}
                        />
                      </>
                    )}
                  </div>
                </div>

                <div style={{ background: ' ' }}>
                  <div className="Invoice-PaymentOption-MasterDiv">
                    <div className="Invoice-PaymentOption-Div">
                      <div className="Invoice-PaymentOption" style={{}}>
                        Payment options
                      </div>
                      {PaymentDetails?.map((item, index) => (
                        <div
                          className="Invoice-PaymentOptions"
                          key={index}
                          style={{
                            borderLeft:
                              selectedOption === index
                                ? '5px solid #52C41A'
                                : 'none',
                            backgroundColor:
                              selectedOption === index ? ' #52c41a2e' : ' ',
                            color: selectedOption === index ? ' #000' : ' ',
                          }}
                          onClick={() => {
                            setselectedOption(index);
                            setItemsdata(PaymentDetails?.[index]?.Details);
                            setCardName();
                            setValue();
                          }}
                        >
                          <div>
                            {item?.MethodName == 'EMI' && (
                              <img src={Emi} alt="emi" />
                            )}
                            {item?.MethodName == 'CreditCard' && (
                              <img src={CrediCard} alt="CrediCard" />
                            )}
                            {item?.MethodName == 'DebitCard' && (
                              <img src={DebitCard} alt="DebitCard" />
                            )}
                            {item?.MethodName == 'NetBanking' && (
                              <img src={NetBank} alt="NetBanking" />
                            )}
                            {item?.MethodName == 'CashCard' && (
                              <img src={CashCard} alt="CashCard" />
                            )}
                            {item?.MethodName == 'Wallet' && (
                              <img src={Wallet} alt="Wallet" />
                            )}
                            {item?.MethodName == 'UPI' && (
                              <img src={Upi} alt="Wallet" />
                            )}
                          </div>
                          <div class="paymentoptions">
                            <div style={{ fontSize: '16px' }}>
                              {item?.MethodName}
                            </div>
                            <div
                              style={{
                                fontSize: '10px',
                                fontWeight: '400',
                                fontFamily: 'Poppins',
                              }}
                            >
                              Google Pay PhonePe & More
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>

                    <div className="Invoice-PaymentProcess-Div">
                      {selectedOption != undefined && (
                        <div className="Invoice-PaymentProcess-UPI">
                          {PaymentDetails?.[selectedOption]?.CardType !=
                            'UPI' && (
                            <Search
                              placeholder={
                                PaymentDetails?.[selectedOption]?.CardType ==
                                  'CRDC' ||
                                PaymentDetails?.[selectedOption]?.CardType ==
                                  'DBCRD'
                                  ? 'Search Your Card'
                                  : PaymentDetails?.[selectedOption]
                                        ?.CardType == 'WLT'
                                    ? 'Search Your Wallet'
                                    : 'Search Your Bank'
                              }
                              onSearchChange={onSearchChange}
                              prefix={<CiSearch />}
                            />
                          )}

                          <div className="Invoice-PaymentProcess-UPI-collapse">
                            {PaymentDetails?.[selectedOption]?.CardType !=
                              'UPI' && (
                              <Collapse
                                items={items}
                                defaultActiveKey={['1']}
                              />
                            )}
                          </div>
                          <div className="Invoice-PaymentProcess-UPI-body">
                            <div className="OverallAMtCount">
                              {' '}
                              INR
                              {PurchasedDetails?.[0]?.ExistingPlanNetPrice > 0
                                ? `₹ ${PurchasedDetails?.[0]?.ExistingPlanNetPrice}`
                                : '₹ 0.00'}
                            </div>
                            <div className="pricedetails-prcedbutton">
                              <div>
                                <Buttons
                                  type="submit"
                                  buttonText="PROCEED TO PAY"
                                  className="sbmt-btn"
                                  handleSubmit={onSubmit}
                                  icon={<ArrowRightOutlined />}
                                ></Buttons>

                                <a className="prcdPay">
                                  {' '}
                                  By proceeding, you agree to our Privacy
                                  Policy{' '}
                                </a>
                              </div>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </div>}


              {activeBusinessUpiDetails?.length > 0 &&
                <>

                  <div style={{ display: "flex", flexDirection: "column", width: "70%" }}>
                    <div
                      style={{
                        background: ' ',
                        display: 'flex',
                        flexDirection: 'column',
                        rowGap: '1rem',
                      }}
                    >
                      <div
                        style={{
                          backgroundColor: '#52c41a2e',
                          padding: '1rem 1rem',
                          borderRadius: '10px',
                          display: 'flex',
                          flexDirection: 'row',
                          rowGap: '2rem',
                          justifyContent: 'space-between',
                          flexWrap: "wrap"
                        }}
                      >
                        <div
                          style={{
                            display: 'flex',
                            flexDirection: 'column',
                            rowGap: '0.2rem',
                          }}
                        >
                          <div>
                            <button
                              className="planchange-btn"
                              onClick={navigatetoPricing}
                            >
                              Change Plan
                            </button>
                          </div>

                          <div
                            style={{
                              display: 'flex',
                              fontFamily: 'Gilroy',
                              fontSize: 'clamp(18px, 2.5vw, 25px)',
                              fontWeight: '600',
                              color: 'green',
                              borderRadius: '3px',
                              alignItems: 'center',
                              columnGap: '0.2rem',
                            }}
                          >
                            <AiOutlineFileDone />
                            {PurchasedDetails?.[0]?.PricingName} /{' '}
                            {PurchasedDetails?.[0]?.NoOfDays > 30
                              ? 'Yearly'
                              : 'Monthly'}
                          </div>
                          <div>
                            <div
                              style={{
                                display: 'flex',
                                alignItems: 'center',
                                columnGap: '0.5rem',
                                color: 'green',
                              }}
                            >
                              <p
                                style={{
                                  fontSize: 'clamp(16px, 2.5vw, 20px)',
                                  fontWeight: '500',
                                }}
                              >
                                {PurchasedDetails?.[0]?.ExistingPlanNetPrice > 0
                                  ? `₹ ${PurchasedDetails?.[0]?.ExistingPlanNetPrice}`
                                  : '₹ 0.00'}
                              </p>
                              <p> to Pay </p>
                            </div>
                          </div>
                        </div>

                        <div>
                          <div className={emailcondit ? 'NoError' : 'ShowError'}>
                            {UserDetails?.[0]?.MailId ? (
                              <p
                                style={{
                                  fontSize: 'clamp(16px, 2.5vw, 17px)',
                                  fontWeight: '500',
                                  color: 'green',
                                }}
                              >
                                {UserDetails?.[0]?.MailId}
                              </p>
                            ) : (
                              <div>
                                <InputField
                                  fieldState={true}
                                  fieldApi={true}
                                  autocomplete="off"
                                  value={email}
                                  label="Email"
                                  className="mailInpt"
                                  id="Email"
                                  field="Email"
                                  onChange={handleInputChange}
                                />
                                {emailcondit ? (
                                  ''
                                ) : (
                                  <p
                                    style={{
                                      color: '#FF4D4F',
                                      fontSize: '12px',
                                      margin: '-10px 0px 0px 13px',
                                    }}
                                  >
                                    Enter Valid Email
                                  </p>
                                )}
                              </div>
                            )}
                          </div>

                          <div
                            style={{
                              display: 'flex',
                              alignItems: 'center',
                              columnGap: '0.2rem',
                              fontSize: '20px',
                              fontWeight: '600',
                              color: 'green',
                            }}
                          >
                            <IoPhonePortraitOutline />
                            <p
                              style={{
                                fontFamily: 'Poppins',
                                fontSize: 'clamp(16px, 2.5vw, 20px)',
                                fontWeight: '500',
                                color: 'green',
                                borderRadius: '3px',
                              }}
                            >
                              {' '}
                              {MobileNo ? MobileNo : ''}
                            </p>
                          </div>

                          <div
                            style={{
                              display: 'flex',
                              justifyContent: 'flex-end',
                              textDecoration: 'underline',
                              color: 'green',
                              fontSize: '12px',
                              cursor: 'pointer',
                              columnGap: '0.2rem',
                              alignItems: 'center',
                            }}
                            onClick={getViewMore}
                          >
                            More Info <CgMoreO />{' '}
                          </div>

                          {moreInfo && (
                            <>
                              <DefaultModal
                                open={moreInfo}
                                footer={false}
                                children={
                                  <>
                                    <div>
                                      <div
                                        style={{
                                          display: 'flex',
                                          flexWrap: 'wrap',
                                          gap: '1rem',
                                        }}
                                        className="adduserinfo"
                                      >
                                        <div>
                                          <InputField
                                            fieldState={true}
                                            fieldApi={true}
                                            autocomplete="off"
                                            label="Company / Billing Name"
                                            id="Company"
                                            field="Company"
                                            value={CompanyName}
                                            isOnChange={CompanyName ? true : false}
                                            onChange={(e) => setCompanyNames(e)}
                                          />
                                        </div>
                                        <div
                                          className={
                                            addresscondit ? 'NoError' : 'ShowError'
                                          }
                                        >
                                          <div>
                                            <TextAreaInput
                                              field="Address"
                                              autoComplete="off"
                                              label="Address"
                                              fieldState={true}
                                              fieldApi={true}
                                              value={address}
                                              isOnChange={address ? true : false}
                                              onChange={(e) => setaddresss(e)}
                                            />
                                            {addresscondit ? (
                                              ''
                                            ) : (
                                              <p
                                                style={{
                                                  color: '#FF4D4F',
                                                  fontSize: '12px',
                                                  margin: '-10px 0px 0px 13px',
                                                }}
                                              >
                                                Enter Address
                                              </p>
                                            )}
                                          </div>
                                        </div>

                                        <div
                                          className={
                                            gstcondit ? 'NoError' : 'ShowError'
                                          }
                                        >
                                          <div>
                                            <InputField
                                              fieldState={true}
                                              fieldApi={true}
                                              autocomplete="off"
                                              type="numeric"
                                              label="GST"
                                              value={gst}
                                              isOnChange={gst ? true : false}
                                              onChange={(e) =>
                                                checkCondition1(e?.target?.value)
                                              }
                                            />
                                            {gstcondit ? (
                                              ''
                                            ) : (
                                              <p
                                                style={{
                                                  color: '#FF4D4F',
                                                  fontSize: '12px',
                                                  margin: '-10px 0px 0px 13px',
                                                }}
                                              >
                                                Enter Valid Gst
                                              </p>
                                            )}
                                          </div>
                                        </div>

                                        <div
                                          className={
                                            zipcondit ? 'NoError' : 'ShowError'
                                          }
                                        >
                                          <div>
                                            <InputField
                                              fieldState={true}
                                              fieldApi={true}
                                              autocomplete="off"
                                              type="numeric"
                                              label="Zip"
                                              maxLength="6"
                                              value={zipcode}
                                              isOnChange={zipcode ? true : false}
                                              onChange={(e) =>
                                                checkCondition(e?.target?.value)
                                              }
                                            />
                                            {zipcondit ? (
                                              ''
                                            ) : (
                                              <p
                                                style={{
                                                  color: '#FF4D4F',
                                                  fontSize: '12px',
                                                  margin: '-10px 0px 0px 13px',
                                                }}
                                              >
                                                Enter Valid Zipcode
                                              </p>
                                            )}
                                          </div>
                                        </div>

                                        <div
                                          className={
                                            citycondit ? 'NoError' : 'ShowError'
                                          }
                                        >
                                          <div>
                                            <InputField
                                              fieldState={City ? City : false}
                                              fieldApi={true}
                                              autocomplete="off"
                                              label="City"
                                              id="city"
                                              field="city"
                                              onChange={(e) =>
                                                setCitys(e?.target?.value)
                                              }
                                              value={City}
                                              isOnChange={City ? true : false}
                                              disabled={City ? true : false}
                                            />
                                            {citycondit ? (
                                              ''
                                            ) : (
                                              <p
                                                style={{
                                                  color: '#FF4D4F',
                                                  fontSize: '12px',
                                                  margin: '-10px 0px 0px 13px',
                                                }}
                                              >
                                                Enter City
                                              </p>
                                            )}
                                          </div>
                                        </div>

                                        <div
                                          className={
                                            statecondit ? 'NoError' : 'ShowError'
                                          }
                                        >
                                          <div>
                                            <InputField
                                              fieldState={State ? State : false}
                                              fieldApi={true}
                                              autocomplete="off"
                                              label="State"
                                              id="state"
                                              field="state"
                                              onChange={(e) =>
                                                setStates(e?.target?.value)
                                              }
                                              value={State}
                                              isOnChange={State ? true : false}
                                              disabled={State ? true : false}
                                            />
                                            {statecondit ? (
                                              ''
                                            ) : (
                                              <p
                                                style={{
                                                  color: '#FF4D4F',
                                                  fontSize: '12px',
                                                  margin: '-10px 0px 0px 13px',
                                                }}
                                              >
                                                Enter State
                                              </p>
                                            )}
                                          </div>
                                        </div>
                                      </div>
                                    </div>
                                  </>
                                }
                                handleCancel={handleCancel}
                              />
                            </>
                          )}
                        </div>
                      </div>

                    </div>

                    <div className="pricedetails-prcedbutton" style={{ gap: "10px" }}>
                      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", paddingTop: "10px" }}>
                        <Buttons
                          type="submit"
                          buttonText="PROCEED TO PAY"
                          className="sbmt-btn"
                          handleSubmit={onSubmitBusinessUpi}
                          icon={<ArrowRightOutlined />}
                        ></Buttons>

                        {/* <a className="prcdPay">
                          {' '}
                          By proceeding, you agree to our Privacy
                          Policy{' '}
                        </a> */}
                      </div>
                    </div>
                  </div>

                </>

              }
            </div>
          </div>
        </div>
        <DefaultModal
          open={businessUpiModal}
          handleCancel={() => { }}
          footer={false}
          width={500}
          children={<>
            <PaymentGatewayEmbedded
              orderId={OrderId}
              setBusinessUPIOrderId={setOrderId}
              businessUPILink={PaymentPageLink}
              setBusinessUPI={setBusinessUpiModal}
              setPaymentSuccess={setPaymentSuccess}
              paymentSucess={paymentSucess}
              ClearAllGlobalStateDatas={() => { }}
              Type='P'

            />
          </>}
        />
      </div>
    </>
  );
};

export default PricingPage;
