import { useState } from "react";
import { useDispatch } from "react-redux";
import usersService from "../../../services/UsersService";
import { tableReload } from "../../../store/TableReloads";
import InputCom from "../../Helpers/Inputs/InputCom";
import ModalCom from "../../Helpers/ModalCom";
import LoadingSpinner from "../../Spinners/LoadingSpinner";

function ConfirmNairaWithdraw({
  payment,
  wallet,
  action,
  situation,
  state,
  setShowNairaWithdraw,
}) {
  const apiURL = new usersService();
  const dispatch = useDispatch();

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

  const [completeNairaWithdraw, setShowCompleteNairaWithdraw] = useState({
    show: false,
    load: false,
    state: {},
  }); // DETERMINES WHEN CONFIRM NAIRA WITHDRAWAL POPS UP

  //FUNCTION TO HANDLE SUBMIT
  const handleSubmit = () => {
    setRequestStatus({ message: "", loading: true, status: false });
    setShowCompleteNairaWithdraw({ load: true });
    let reqData = {
      amount: Number(state.amount * 100),
      Fee: Number(state.fee),
      wallet_uid: wallet.wallet_uid,
    };

    if (state?.choice === "prev") {
      reqData.recipient_uid = state.details?.recipient_uid;
      reqData.mode = 100;
    }

    if (state?.choice === "new") {
      reqData.account_no = state?.details?.accountNumber;
      reqData.account_type = Number(state?.details?.accountType);
      reqData.bank_uid = state?.details?.bank_uid;
      reqData.country = state?.details?.country;
      reqData.state = state?.details?.state;
      reqData.city = state?.details?.city;
      reqData.mode = 500;
    }

    apiURL
      .sendMoney(reqData)
      .then((res) => {
        if (res.data.internal_return < 0) {
          // if (res.data?.status_message?.toLowerCase().includes("limit")) {
          //   setRequestStatus({
          //     message: ,
          //     loading: false,
          //     status: false,
          //   });
          // }
          return setTimeout(() => {
            setRequestStatus({
              message: "",
              loading: false,
              status: false,
            });
            setShowCompleteNairaWithdraw({
              show: true,
              load: false,
              state: res.data,
            });
          }, 5000);
        }

        setTimeout(() => {
          setRequestStatus({
            message: "",
            loading: false,
            status: false,
          });
          setShowCompleteNairaWithdraw({
            show: true,
            load: false,
            state: res.data,
          });
        }, 5000);
        dispatch(tableReload({ type: "WALLETTABLE" }));
        return;
      })
      .catch((error) => {
        setRequestStatus({
          message: "Opps! something went wrong! Try Again",
          loading: false,
          status: false,
        });
      });
  };

  return (
    <ModalCom action={action} situation={situation} className="edit-popup">
      <div className="logout-modal-wrapper lw-[90%] md:w-[768px] h-full lg:h-auto bg-white dark:bg-dark-white lg:rounded-2xl">
        <div className="w-full">
          <div className="logout-modal-header w-full flex items-center justify-between lg:p-6 px-[30px] py-[23px] border-b dark:border-[#5356fb29]  border-light-purple">
            <h2 className="text-26 font-bold text-dark-gray dark:text-white tracking-wide">
              {completeNairaWithdraw.load ? (
                "Confirming..."
              ) : (
                <>
                  {" "}
                  {completeNairaWithdraw.show
                    ? completeNairaWithdraw?.state?.internal_return >= 0
                      ? "Transfer Success"
                      : "Transfer Error"
                    : `Withdraw from ${wallet.description} Wallet : ${
                        wallet.symbol
                      }${(wallet.amount * 0.01).toFixed(2)}`}
                </>
              )}
            </h2>
            <button
              type="button"
              className="text-[#374557] dark:text-red-500"
              onClick={action}
            >
              <svg
                width="36"
                height="36"
                viewBox="0 0 36 36"
                fill="none"
                className="fill-current"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M36 16.16C36 17.4399 36 18.7199 36 20.0001C35.7911 20.0709 35.8636 20.2554 35.8385 20.4001C34.5321 27.9453 30.246 32.9248 22.9603 35.2822C21.9006 35.6251 20.7753 35.7657 19.6802 35.9997C18.4003 35.9997 17.1204 35.9997 15.8401 35.9997C15.5896 35.7086 15.2189 35.7732 14.9034 35.7093C7.77231 34.2621 3.08728 30.0725 0.769671 23.187C0.435002 22.1926 0.445997 21.1199 0 20.1599C0 18.7198 0 17.2798 0 15.8398C0.291376 15.6195 0.214408 15.2656 0.270759 14.9808C1.71321 7.69774 6.02611 2.99691 13.0428 0.700951C14.0118 0.383805 15.0509 0.386897 15.9999 0C17.2265 0 18.4532 0 19.6799 0C19.7156 0.124041 19.8125 0.136067 19.9225 0.146719C27.3 0.868973 33.5322 6.21922 35.3801 13.427C35.6121 14.3313 35.7945 15.2484 36 16.16ZM33.011 18.0787C33.0433 9.77105 26.3423 3.00309 18.077 2.9945C9.78479 2.98626 3.00344 9.658 2.98523 17.8426C2.96667 26.1633 9.58859 32.9601 17.7602 33.0079C26.197 33.0577 32.9787 26.4186 33.011 18.0787Z"
                  fill=""
                  fillOpacity="0.6"
                />
                <path
                  d="M15.9309 18.023C13.9329 16.037 12.007 14.1207 10.0787 12.2072C9.60071 11.733 9.26398 11.2162 9.51996 10.506C9.945 9.32677 11.1954 9.0811 12.1437 10.0174C13.9067 11.7585 15.6766 13.494 17.385 15.2879C17.9108 15.8401 18.1633 15.7487 18.6375 15.258C20.3586 13.4761 22.1199 11.7327 23.8822 9.99096C24.8175 9.06632 26.1095 9.33639 26.4967 10.517C26.7286 11.2241 26.3919 11.7413 25.9133 12.2178C24.1757 13.9472 22.4477 15.6855 20.7104 17.4148C20.5228 17.6018 20.2964 17.7495 20.0466 17.9485C22.0831 19.974 24.0372 21.8992 25.9689 23.8468C26.9262 24.8119 26.6489 26.1101 25.4336 26.4987C24.712 26.7292 24.2131 26.3441 23.7455 25.8757C21.9945 24.1227 20.2232 22.3892 18.5045 20.6049C18.0698 20.1534 17.8716 20.2269 17.4802 20.6282C15.732 22.4215 13.9493 24.1807 12.1777 25.951C11.7022 26.4262 11.193 26.7471 10.4738 26.4537C9.31345 25.9798 9.06881 24.8398 9.98589 23.8952C11.285 22.5576 12.6138 21.2484 13.9387 19.9355C14.5792 19.3005 15.2399 18.6852 15.9309 18.023Z"
                  fill="#"
                  fillOpacity="0.6"
                />
              </svg>
            </button>
          </div>
          <hr />
          <div className="add-fund w-full bg-white dark:bg-dark-white rounded-2xl shadow">
            {completeNairaWithdraw.load ? (
              <div className="h-[35rem] flex items-center justify-center">
                <LoadingSpinner size="12" color="sky-blue" />
              </div>
            ) : completeNairaWithdraw.show ? (
              <div className="px-4 md:p-8 py-4 add-fund-info">
                <div className="field w-full mb-3 min-h-[23rem]">
                  <div className="flex items-center w-full justify-center mb-3">
                    {completeNairaWithdraw.state?.sendmoney_message
                      ?.toLowerCase()
                      ?.includes("completed") ? (
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="100"
                        height="100"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="green"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        className="feather feather-check-circle"
                      >
                        <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
                        <polyline points="22 4 12 14.01 9 11.01"></polyline>
                      </svg>
                    ) : (
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        viewBox="0 0 24 24"
                        fill="none"
                        width="100"
                        height="100"
                        stroke="red"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        className="feather feather-x-circle"
                      >
                        <circle cx="12" cy="12" r="10"></circle>
                        <line x1="15" y1="9" x2="9" y2="15"></line>
                        <line x1="9" y1="9" x2="15" y2="15"></line>
                      </svg>
                    )}
                  </div>

                  {completeNairaWithdraw.state?.internal_return >= 0 ? (
                    <>
                      <div className={`flex items-center`}>
                        <h1 className="text-xl font-semibold text-dark-gray dark:text-white tracking-tighter my-1">
                          {completeNairaWithdraw.state?.sendmoney_message || ""}
                        </h1>
                      </div>
                      <div className="flex items-center gap-8">
                        <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                          Amount(
                          {completeNairaWithdraw.state
                            ?.terminatingcountrycode || ""}
                          )
                        </h1>
                        <span className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                          {Number(
                            completeNairaWithdraw.state?.TerminatingAmount *
                              0.01
                          ).toLocaleString() || ""}
                        </span>
                      </div>
                      <div className="flex items-center gap-8">
                        <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                          Recipient
                        </h1>
                        <span className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                          {completeNairaWithdraw.state?.recitient}
                        </span>
                      </div>
                      <div className="flex items-center gap-8">
                        <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                          Confirmation Number
                        </h1>
                        <span className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                          {completeNairaWithdraw.state?.confirmation}
                        </span>
                      </div>{" "}
                    </>
                  ) : (
                    <>
                      <div className={`flex items-center`}>
                        <h1 className="text-xl font-semibold text-dark-gray dark:text-white tracking-tighter my-1">
                          {completeNairaWithdraw.state?.status_message
                            ?.toLowerCase()
                            .includes("not_found")
                            ? "Wallet Error Occurred"
                            : completeNairaWithdraw.state?.status_message
                                ?.toLowerCase()
                                .includes("recipient_add_error")
                            ? "Recipient Error Occurred"
                            : completeNairaWithdraw.state?.status_message
                                ?.toLowerCase()
                                .includes("limit")
                            ? "Transfer limit Error"
                            : completeNairaWithdraw.state?.bad_param
                                ?.toLowerCase()
                                .includes("balance")
                            ? "Insufficient Balance"
                            : "An Error Occurred"}{" "}
                        </h1>
                      </div>
                      <div className="flex items-center gap-8">
                        <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                          Message:
                        </h1>
                        <span className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                          {completeNairaWithdraw.state?.status_message
                            ?.toLowerCase()
                            .includes("not_found")
                            ? "This Wallet is not Found"
                            : completeNairaWithdraw.state?.status_message
                                ?.toLowerCase()
                                .includes("recipient_add_error")
                            ? "No Recipient Found"
                            : completeNairaWithdraw.state?.status_message
                                ?.toLowerCase()
                                .includes("limit")
                            ? "The transfer limit has been exceeded"
                            : completeNairaWithdraw.state?.bad_param
                                ?.toLowerCase()
                                .includes("balance")
                            ? "Insufficient Balance for Transaction"
                            : "Could not perform transaction"}
                        </span>
                      </div>
                    </>
                  )}
                </div>
              </div>
            ) : (
              <div className="px-4 md:px-8 py-4 add-fund-info">
                <h2 className="my-2 text-slate-900 dark:text-white text-sm xl:text-xl font-medium">
                  {/* Confirm Withdraw to Account */}
                </h2>
                {/* AMOUNT */}
                <div className="field w-full mb-3">
                  <InputCom
                    fieldClass="px-6"
                    label="Amount:"
                    type="text"
                    name="amount"
                    value={state?.amount || ""}
                    disable={true}
                  />
                </div>

                {state?.choice === "prev" && (
                  <>
                    {/* RECIPIENT ACC: */}
                    <div className="field w-full mb-3">
                      <InputCom
                        fieldClass="px-6"
                        label="Recipient Acc:"
                        type="text"
                        name="recipient"
                        value={state?.details?.recipient || ""}
                        disable={true}
                      />
                    </div>
                  </>
                )}

                {state?.choice === "new" && (
                  <>
                    {/* RECIPIENT ACC: */}
                    <div className="field w-full mb-3">
                      <InputCom
                        fieldClass="px-6"
                        label="Bank Acc:"
                        type="text"
                        name="bank"
                        value={
                          `${state?.details?.name} ${state?.details?.country}` ||
                          ""
                        }
                        disable={true}
                      />
                    </div>
                  </>
                )}

                {/* PROCESSING FEE: */}
                <div className="field w-full mb-3">
                  <InputCom
                    fieldClass="px-6"
                    label="Processing Fee:"
                    type="text"
                    name="processingFee"
                    value={(state?.fee * 0.01).toFixed(2) || ""}
                    disable={true}
                  />
                </div>

                {/* TOTAL */}
                <div className="field w-full mb-3">
                  <InputCom
                    fieldClass="px-6"
                    label="Total"
                    type="text"
                    name="total"
                    value={(state?.total * 0.01).toFixed(2) || ""}
                    disable={true}
                  />
                </div>

                {/* COMMENT/NOTE */}
                <div className="field w-full mb-3">
                  <InputCom
                    fieldClass="px-6"
                    label="Comment/Note:"
                    type="text"
                    name="comment"
                    value={state?.comment || ""}
                    disable={true}
                  />
                </div>
              </div>
            )}

            {!completeNairaWithdraw.load && (
              <>
                {" "}
                <hr />
                <p
                  className={`text-base ${
                    requestStatus.status ? "text-green-500" : "text-red-500"
                  } px-4 md:px-8 py-4 h-5`}
                >
                  {requestStatus.message && requestStatus.message}
                </p>
                <div className="px-4 md:px-8 py-4 add-fund-btn flex justify-end items-center gap-2">
                  {!completeNairaWithdraw.show && (
                    <button
                      type="button"
                      onClick={action}
                      className="px-4 py-1 h-11 max-w-[100px] w-full flex justify-center items-center bg-[#f5a430] text-black text-base rounded-full"
                    >
                      Cancel
                    </button>
                  )}

                  <button
                    onClick={
                      completeNairaWithdraw.show
                        ? action
                        : completeNairaWithdraw?.state?.internal_return < 0
                        ? action
                        : handleSubmit
                    }
                    className="btn-gradient text-base tracking-wide px-4 py-2 rounded-full text-white cursor-pointer min-w-[100px]"
                  >
                    {requestStatus.loading ? (
                      <LoadingSpinner size="6" color="sky-blue" />
                    ) : completeNairaWithdraw.show ? (
                      "Okay"
                    ) : completeNairaWithdraw?.state?.internal_return < 0 ? (
                      "Cancel"
                    ) : (
                      "Transfer"
                    )}
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </ModalCom>
  );
}

export default ConfirmNairaWithdraw;
