import React, { useState } from "react";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import InputCom from "../Helpers/Inputs/InputCom";

import usersService from "../../services/UsersService";

import { FlutterWaveButton, closePaymentModal } from "flutterwave-react-v3";

function ConfirmAddFund({ confirmCredit, onClose, walletItem }) {
  let { userDetails } = useSelector((state) => state.userDetails); // TO GET LOGGEDIN USER DETAILS

  let [pageLoading, setPageLoading] = useState(true);

  let [requestStatus, setRequestStatus] = useState({
    message: "",
    loading: false,
    status: false,
  }); // STATE FOR API REQUEST

  const apiURL = new usersService();
  const navigate = useNavigate();

  //FUNCTION TO HANDLE SUBMIT
  const onSuccessPayment = () => {
    setRequestStatus({ message: "", loading: true, status: false });
    let reqData = { amount: confirmCredit?.data?.account, currency: "NGN" };
    apiURL
      .startTopUp(reqData)
      .then((res) => {
        if (res.data.internal_return < 0) {
          setRequestStatus({
            message: "Could not finish transaction",
            loading: false,
            status: false,
          });
          toast.success("Opps! something went wrong");
        }
        // do something
        setRequestStatus({
          message: "Topup successful",
          loading: false,
          status: true,
        });
        toast.success("Account Topup was sucessful");
        setTimeout(() => {
          navigate("/my-wallet", { replace: true });
        }, 1000);
      })
      .catch((err) => {
        // do something
        setRequestStatus({
          message: "Opps! An Error Occured",
          loading: false,
          status: false,
        });
        toast.success("Opps! something went wrong");
      });
  };

  const config = {
    public_key: process.env.REACT_APP_FLUTTERWAVE_APIKEY,
    tx_ref: Date.now(),
    amount: confirmCredit?.data?.amount,
    currency: "NGN",
    payment_options: "card,mobilemoney,ussd",
    customer: {
      email: `${userDetails.email}`,
      phone_number: userDetails.phone,
      name: `${userDetails.lastname} ${userDetails.firstname}`,
    },
    customizations: {
      title: "WrenchBoard",
      description: "Topup Payment",
      logo: "https://st2.depositphotos.com/4403291/7418/v/450/depositphotos_74189661-stock-illustration-online-shop-log.jpg",
    },
  };

  const fwConfig = {
    ...config,
    text: "Proceed",
    callback: (response) => {
      onSuccessPayment();
      closePaymentModal(); // this will close the modal programmatically
    },
    onClose: () => {},
  };

  // useEffect(() => {
  //   // what happens if not data redirect user
  //   if (!data) {
  //     navigate("/my-wallet/add-fund", { replace: true });
  //   } else {
  //     setPageLoading(false);
  //   }
  // }, []);

  let __confirmCard = JSON.parse(confirmCredit?.data.card);
  const ThePaymentText = ({ value }) => (
    <div className="my-2 flex items-center gap-5">
      <div className="card-details flex items-center gap-3">
        <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
          {value.description} Card
        </h1>
        <p className="text-base font-bold text-dark-gray dark:text-white tracking-wide">
          Bank **************{value.digits}
        </p>
      </div>
    </div>
  );

  return (
    <div className="content-wrapper w-full h-[32rem]">
      <div className="w-full mb-10">
        <div className="add-fund w-full bg-white dark:bg-dark-white rounded-2xl">
          {/* <h2 className="md:p-8 p-4 text-slate-900 dark:text-white text-xl lg:text-2xl font-medium">
              Confirm Add Fund To Account
            </h2>
            <hr /> */}
          <div className="px-4 md:p-8 py-4 add-fund-info">
            <div className="field w-full mb-3 min-h-[45px]">
              {confirmCredit?.show ? (
                <div className="flex flex-col gap-4">
                  <div className="flex items-center gap-4">
                    <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                      {confirmCredit?.data?.currency == "naira"
                        ? "Amount (Naira):"
                        : "Amount (Dollars):"}
                    </h1>
                    <span className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                      {`${walletItem?.symbol} ${
                        Number(confirmCredit?.data?.amount).toLocaleString() ||
                        ""
                      }`}
                    </span>
                  </div>
                  <div className="flex items-center gap-4">
                    {/* <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1"> */}
                    <label
                      htmlFor="payment"
                      className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1"
                    >
                      {confirmCredit?.data?.currency && "Payment Method:"}
                    </label>
                    <span className="text-[#181c32] dark:text-white ">
                      {__confirmCard && (
                        <ThePaymentText value={__confirmCard} />
                      )}
                    </span>
                  </div>
                </div>
              ) : (
                <InputCom
                  fieldClass="px-6"
                  label={
                    confirmCredit?.data?.currency == "naira"
                      ? "Amount (Naira):"
                      : "Amount (Dollars):"
                  }
                  type="text"
                  name="amount"
                  value={confirmCredit?.data?.amount || ""}
                  disable={true}
                />
              )}
            </div>
          </div>
          {/* <h1 className="mb-2 text-xl font-bold text-dark-gray dark:text-white px-4 h-5">
            {confirmCredit?.data?.currency && "Payment Method"}
          </h1> */}
          {/* <hr /> */}
          <div className="min-h-[220px]"></div>
          <div className="md:p-8 p-4 add-fund-btn flex justify-end items-center py-4 gap-4">
            <button
              className="px-4 h-11 flex justify-center items-center border-gradient text-base rounded-full"
              onClick={onClose}
            >
              Cancel
            </button>
            {confirmCredit?.data?.currency == "naira" ? (
              <FlutterWaveButton
                {...fwConfig}
                className="px-2 py-1 h-11 flex justify-center items-center btn-gradient text-base rounded-full text-white"
              />
            ) : (
              <button
                className="px-4 py-1 h-11 flex justify-center items-center btn-gradient text-base rounded-full text-white"
                onClick={() => console.log("WORKING")}
              >
                Continue
              </button>
            )}
          </div>
        </div>
      </div>

      {/* <div className="w-full mb-10">
        <div className="wallet w-full  md:p-8 p-4 h-full bg-white dark:bg-dark-white rounded-2xl shadow">
          <h2 className="text-gray-900 dark:text-white text-xl lg:text-2xl font-medium">
            Recent Activity
          </h2>
          <p className='text-base text-gray-600 dark:text-white'>Activity Report</p>
          {payment.loading ? (
            <LoadingSpinner size="16" color="sky-blue" />
          ) : (
            <RecentActivityTable payment={payment} />
          )}
        </div>
      </div> */}
    </div>
  );
}

export default ConfirmAddFund;
