import { FlutterWaveButton, closePaymentModal } from "flutterwave-react-v3";
import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import usersService from "../../../services/UsersService";
import { tableReload } from "../../../store/TableReloads";
import LoadingSpinner from "../../Spinners/LoadingSpinner";

function ThePaymentText({ value, type }) {
  const cardDetails = value;
  value.description =
    type === "new"
      ? cardDetails.cardNum[0] === "4"
        ? "Visa"
        : cardDetails.cardNum[0] == "5"
        ? "Master"
        : "ATM"
      : value.description;
  value.digits = type === "new" ? cardDetails.cardNum.slice(-4) : value.digits;
  return (
    <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 space-x-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>
  );
}

function AmountSection({ currency, amount, country }) {
  const formattedAmount = Number(amount).toFixed(2);
  return (
    <div
      className={`flex items-center ${country == "US" ? "gap-14" : "gap-4"}`}
    >
      <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
        Amount({currency})
      </h1>
      <span className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
        {formattedAmount}
      </span>
    </div>
  );
}

function TransactionFeeSection({ currency, fee, country }) {
  const formattedFee = Number(fee).toFixed(2);
  return (
    <div
      className={`flex items-center border-b border-gray-600 ${
        country == "US" ? "gap-[2.7rem]" : "gap-4"
      }`}
    >
      <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
        Transaction Fee
      </h1>
      <span className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
        {formattedFee}
      </span>
    </div>
  );
}

function TotalSection({ currency, amount, fee, country }) {
  const total = Number(amount) + Number(fee);
  const formattedTotal = total.toFixed(2);
  return (
    <div
      className={`flex items-center ${
        country == "US" ? "gap-[8rem]" : "gap-[6.3rem]"
      }`}
    >
      <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
        Total
      </h1>
      <span className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
        {formattedTotal}
      </span>
    </div>
  );
}

function ConfirmAddFund({
  confirmCredit,
  onClose,
  walletItem,
  setConfirmCredit,
}) {
  const __confirmData = confirmCredit?.data;
  const __confirmCountry = walletItem?.country;
  const __confirmCardDetails =
    __confirmData.cardType === "prev"
      ? JSON.parse(__confirmData.card)
      : __confirmData.card;

  const apiURL = new usersService();

  const { userDetails } = useSelector((state) => state?.userDetails);

  const navigate = useNavigate();
  const dispatch = useDispatch();

  const [requestStatus, setRequestStatus] = useState({
    message: "",
    loading: false,
    status: false,
  });

  const config = {
    public_key: process.env.REACT_APP_FLUTTERWAVE_APIKEY,
    tx_ref: __confirmData?.credit_reference,
    currency: "NGN",
    amount: Number(__confirmData.amount),
    payment_options: "card,mobilemoney,ussd",
    customer: {
      email: userDetails.email,
      phone_number: userDetails.phone,
      name: `${userDetails.lastname} ${userDetails.firstname}`,
    },
    customizations: {
      title: "WrenchBoard",
      description: "Add Credit Payment",
      logo: "https://www.wrenchboard.com/assets/images/wrench-500-500-icon.png",
    },
  };
  //debugger;
  const fwConfig = {
    ...config,
    text: "Proceed",
    callback: (response) => {
      onSuccessPayment();
      setTimeout(() => {
        closePaymentModal();
      }, 2000);
    },
  };

  const onSuccessPayment = () => {
    setRequestStatus({ message: "", loading: true, status: false });
    const reqData = { tx_ref: __confirmData?.credit_reference };
    console.log("**** onSuccessPayment **** THIS WAS REACHED");
    apiURL
      .resultTopUp(reqData)
      .then((res) => {
        if (res.data.internal_return < 0) {
    console.log("**** internal return **** THIS WAS REACHED");

          setRequestStatus({
            message: "Could not finish transaction",
            loading: false,
            status: false,
          });

          setTimeout(() => {
            setConfirmCredit((prev) => ({
              ...prev,
              show: {
                awaitConfirm: { loader: false, state: false },
                acceptConfirm: { loader: false, state: true },
              },
              data: res,
            }));
          }, 1500);

          toast.success("Opps! something went wrong");
        } else {
          setRequestStatus({
            message: "Topup successful",
            loading: false,
            status: true,
          });
          dispatch(tableReload({ type: "WALLETTABLE" }));
        }
      })
      .catch((err) => {
        setRequestStatus({
          message: "Opps! An Error Occured",
          loading: false,
          status: false,
        });
        toast.success("Opps! something went wrong");
      });
  };

  const handlePrevCard = async () => {
    const { amount, credit_reference, currency } = __confirmData;
    const { card_uid } = __confirmCardDetails;

    const reqData = {
      amount: amount * 100,
      card_uid,
      credit_reference,
      currency,
    };

    try {
      setConfirmCredit((prev) => ({
        ...prev,
        show: {
          acceptConfirm: { loader: true },
        },
      }));
      const res = await apiURL.getPaidPrevCard(reqData);
      const _response = res.data;
      if (res.data.internal_return < 0) {
        setConfirmCredit((prev) => ({
          ...prev,
          show: {
            acceptConfirm: { loader: false },
          },
        }));
        return;
      }

      setTimeout(() => {
        setConfirmCredit((prev) => ({
          ...prev,
          show: {
            awaitConfirm: { loader: false, state: false },
            acceptConfirm: { loader: false, state: true },
          },
          data: _response,
        }));
        dispatch(tableReload({ type: "WALLETTABLE" }));
      }, 1500);
    } catch (error) {
      setConfirmCredit((prev) => ({
        ...prev,
        show: {
          acceptConfirm: { loader: false },
        },
      }));
      console.log(error);
    }
  };

  const handleNewCard = async () => {
    const { amount, credit_reference, uid } = __confirmData;
    const { address, cardNum, cvv, expirationMonth, expirationYear } =
      __confirmCardDetails;

    const reqData = {
      amount: amount * 100,
      cardnumber: cardNum.replace(/\s/g, ""),
      credit_reference,
      cvc: cvv,
      description: address,
      exp_month: expirationMonth,
      exp_year: expirationYear,
      paymenttype: 100,
      uid,
    };

    try {
      setConfirmCredit((prev) => ({
        ...prev,
        show: {
          acceptConfirm: { loader: true },
        },
      }));
      const res = await apiURL.getPaidNewCard(reqData);
      const _response = res.data;
      if (res.data.internal_return < 0) {
        setConfirmCredit((prev) => ({
          ...prev,
          show: {
            awaitConfirm: { loader: false, state: false },
            acceptConfirm: { loader: false, state: true },
          },
          data: _response,
        }));
        return;
      }

      setTimeout(() => {
        setConfirmCredit((prev) => ({
          ...prev,
          show: {
            awaitConfirm: { loader: false, state: false },
            acceptConfirm: { loader: false, state: true },
          },
          data: _response,
        }));
        dispatch(tableReload({ type: "WALLETTABLE" }));
      }, 1500);
    } catch (error) {
      setConfirmCredit((prev) => ({
        ...prev,
        show: {
          acceptConfirm: { loader: false },
        },
      }));
      setTimeout(() => onClose, 10000);
      console.log(error);
    }
  };

  const getBack = () => {
    setConfirmCredit((prev) => ({
      ...prev,
      show: {
        awaitConfirm: { loader: false, state: false },
        acceptConfirm: { loader: false, state: false },
      },
      data: {},
    }));
  };

  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?.awaitConfirm?.state && (
                <div className="flex flex-col gap-2">
                  <AmountSection
                    currency={__confirmData?.currency}
                    amount={__confirmData?.amount}
                    country={__confirmCountry}
                  />
                  <TransactionFeeSection
                    currency={__confirmData?.currency}
                    fee={__confirmData?.fee}
                    country={__confirmCountry}
                  />
                  <TotalSection
                    currency={__confirmData?.currency}
                    amount={__confirmData?.amount}
                    fee={__confirmData?.fee}
                    country={__confirmCountry}
                  />
                  {__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"
                      >
                        Payment Method
                      </label>
                      <span className="text-[#181c32] dark:text-white">
                        <ThePaymentText
                          value={__confirmCardDetails}
                          type={__confirmData?.cardType}
                        />
                      </span>
                    </div>
                  )}
                  <div
                    className={`${
                      __confirmCountry === "US"
                        ? "gap-[3.7rem]"
                        : "gap-[1.81rem]"
                    } 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>
              )}
            </div>
          </div>

          <div
            className={
              __confirmCountry === "US" ? "min-h-[96px]" : "min-h-[157px]"
            }
          ></div>
          <hr />
          <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={getBack}
            >
              Back
            </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
                    : handleNewCard
                }
              >
                {confirmCredit?.show?.acceptConfirm?.loader ? (
                  <LoadingSpinner size="6" color="sky-blue" />
                ) : (
                  "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>
  );
}

export default ConfirmAddFund;
