import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import usersService from "../../../services/UsersService";
import Icons from "../../Helpers/Icons";
import InputCom from "../../Helpers/Inputs/InputCom";
import LoadingSpinner from "../../Spinners/LoadingSpinner";
import AddFundDollars from "./AddFundDollars";

function AddFundPop({
  _payment,
  input,
  setInput,
  onClose,
  confirmCredit,
  setConfirmCredit,
  walletItem,
}) {
  const navigate = useNavigate();
  const apiCall = new usersService();
  let countryWallet = walletItem?.country;
  const { payment, currency } = _payment;

  const [inputError, setInputError] = useState("");
  let __awaitComponent = confirmCredit.show.awaitConfirm;

  const handleChange = ({ target: { name, value } }) => {
    setInput(value);
  };

  const handleSubmit = async () => {
    setInputError("");
    setConfirmCredit((prev) => ({
      ...prev,
      show: { awaitConfirm: { loader: true } },
    }));

    if (!input || input === "0") {
      setConfirmCredit((prev) => ({
        ...prev,
        show: { awaitConfirm: { loader: false } },
      }));
      setInputError("Please Enter Amount");
      setTimeout(() => setInputError(""), 5000);
      return;
    }

    if (isNaN(input)) {
      setConfirmCredit((prev) => ({
        ...prev,
        show: { awaitConfirm: { loader: false } },
      }));
      setInputError("Amount must be a Number");
      setTimeout(() => setInputError(""), 5000);
      return;
    }

    let stateData = {
      amount: Number(input) * 100,
      currency: walletItem?.code,
    };

    try {
      const res = await apiCall.getStartCredit(stateData);
      if (res.data.internal_return < 0) {
        setConfirmCredit((prev) => ({
          ...prev,
          show: { awaitConfirm: { loader: false } },
        }));
        setInputError("An Error Occurred");
        setTimeout(() => setInputError(""), 5000);
        return;
      }

      const _response = res.data;
      stateData.amount = Number(input);
      stateData.currency = currency;
      stateData = { ...stateData, ..._response };

      setTimeout(() => {
        setConfirmCredit((prev) => ({
          ...prev,
          show: {
            awaitConfirm: { loader: false, state: true },
            acceptConfirm: { loader: false, state: false },
          },
          data: stateData,
        }));
      }, 1500);
    } catch (error) {
      setConfirmCredit((prev) => ({
        ...prev,
        show: { awaitConfirm: { loader: false } },
      }));
      console.log(error);
    }
  };

  return (
    <div className="h-[33rem] w-full">
      <div className="content-wrapper w-full lg:flex xl:space-x-8 lg:space-x-4 bottomMargin">
        <div className="lg:w-2/2 w-full mb-10 lg:mb-0">
          <div className="add-fund w-full bg-white dark:bg-dark-white rounded-2xl">
            <form className="md:px-8 md:pt-4 px-4 pt-2 add-fund-info flex items-center gap-[2.1rem]">
              <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-tighter my-1">
                Amount({currency})
              </h1>
              <div className="field w-full max-w-[250px]">
                <InputCom
                  fieldClass="px-6"
                  type="text"
                  name="amount"
                  placeholder="0"
                  value={input}
                  inputHandler={handleChange}
                />
                <p className="text-base text-red-500 h-5">
                  {inputError && inputError}
                </p>
              </div>
            </form>

            {countryWallet === "US" && (
              <div className="w-full md:px-8 md:pt-4 px-4 pt-2 bg-white dark:bg-dark-white rounded-2xl">
                <AddFundDollars
                  setInputError={setInputError}
                  walletItem={walletItem}
                  input={input}
                  setInput={setInput}
                  currency={currency}
                  onClose={onClose}
                  confirmCredit={confirmCredit}
                  setConfirmCredit={setConfirmCredit}
                />
              </div>
            )}

            {countryWallet == "NG" && <div className="h-[18rem]"></div>}

            {countryWallet == "NG" && (
              <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 btn-gradient text-base rounded-full text-white"
                  onClick={onClose}
                >
                  Cancel
                </button>
                <button
                  onClick={handleSubmit}
                  type="button"
                  className="px-4 py-1 h-11 flex justify-center space-x-1 items-center btn-gradient text-base rounded-full text-white max-w-[100px] w-full"
                >
                  {__awaitComponent.loader ? (
                    <LoadingSpinner size="6" color="sky-blue" />
                  ) : (
                    <>
                      <span className="text-white">Continue</span>{" "}
                      <Icons name="chevron-right" />
                    </>
                  )}
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default AddFundPop;
