import React, { useState } from "react";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";

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

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

function ConfirmAddFund({ confirmCredit, onClose, walletItem }) {
  const __confirmData = confirmCredit?.data;
  const __confirmCountry = walletItem?.country;
  const __confirmCardDetails = __confirmData.card
    ? JSON.parse(__confirmData.card)
    : "";
  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 successful");
        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: () => {},
  };

  const handlePrevCard = () => {
    console.log("Test me");
  };

  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>
  );

  console.log(confirmCredit);

  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">
          <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 ${
                      __confirmCountry == "US" ? "gap-14" : "gap-4"
                    }`}
                  >
                    <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                      Amount({__confirmData?.currency})
                    </h1>
                    <span className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                      {`${walletItem?.symbol} ${
                        Number(__confirmData?.amount).toLocaleString() || ""
                      }`}
                    </span>
                  </div>
                  {__confirmCountry == "US" && (
                    <div className="flex items-center gap-8">
                      <label
                        htmlFor="payment"
                        className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1"
                      >
                        {__confirmCountry == "US" && "Payment Method"}
                      </label>
                      <span className="text-[#181c32] dark:text-white ">
                        {__confirmCardDetails ? (
                          <ThePaymentText value={__confirmCardDetails} />
                        ) : null}
                      </span>
                    </div>
                  )}

                  <div
                    className={`${
                      __confirmCountry == "US" ? "gap-[3.7rem]" : "gap-8"
                    } flex items-center`}
                  >
                    <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                      Reference No
                    </h1>
                    <span className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                      {__confirmData?.credit_reference}
                    </span>
                  </div>
                </div>
              ) : null}
            </div>
          </div>
          {/* <hr /> */}
          <div
            className={
              __confirmCountry == "US" ? "min-h-[163px]" : "min-h-[200px]"
            }
          ></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>
            {__confirmCountry == "US" && (
              <button
                className="px-4 h-11 flex justify-center items-center btn-gradient text-white text-base rounded-full"
                onClick={
                  __confirmData?.cardType === "prev"
                    ? handlePrevCard
                    : () => console.log("Test me")
                }
              >
                Proceed
              </button>
            )}
            {__confirmCountry == "NG" && (
              <FlutterWaveButton
                {...fwConfig}
                className="px-2 py-1 h-11 flex justify-center items-center btn-gradient text-base rounded-full text-white"
              />
            )}
          </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;
