import React, { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import InputCom from "../Helpers/Inputs/InputCom";
import LoadingSpinner from "../Spinners/LoadingSpinner";
import RecentActivityTable from "./WalletComponent/RecentActivityTable";

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

import { Form, Formik } from "formik";
import * as Yup from "yup";

const validationSchema = Yup.object().shape({
  amount: Yup.number()
    .typeError("you must specify a number")
    .min(1, "Amount must be greater than 0")
    .required("Amount is required"),
  recipientID: Yup.string()
    .min(1, "Minimum 1 characters")
    .max(50, "Maximum 50 characters")
    .required("Recipient is required"),
});

const initialValues = {
  amount: "",
  recipientID: "",
  comment: "",
};

function TransferFund({ payment, wallet }) {
  const apiCall = new usersService(); // API CLASS CALL

  const navigate = useNavigate();

  let [requestStatus, setRequestStatus] = useState(false);

  let [recipients, setRecipients] = useState({
    // FOR COUPON HISTORY
    loading: true,
    data: [],
    error: false,
  });

  let [sendMoneyFee, setSendMoneyFee] = useState({
    loading: false,
    fee: 0,
    total: 0,
  }); // HOLD THE VALUE FOR SEND MONEY FEE

  //FUNCTION TO GET RECIPIENT LIST
  const getRecipients = () => {
    apiCall
      .getRecipient()
      .then((res) => {
        if (res.data.internal_return < 0) {
          // success but no data
          setRecipients((prev) => ({ ...prev, loading: false }));
          return;
        }
        setRecipients((prev) => ({
          ...prev,
          loading: false,
          data: res.data.result_list,
        }));
      })
      .catch((error) => {
        setRecipients((prev) => ({ ...prev, loading: false, error: true }));
      });
  };

  //FUNCTION TO GET SEND MONEY FEE
  const getSendMoneyFee = ({ target: { value } }) => {
    setSendMoneyFee({ loading: true, fee: 0, total: 0 });
    let amount = value;
    if (Number(amount) <= 0 || amount == "" || isNaN(amount)) {
      setSendMoneyFee({ loading: false, fee: 0, total: 0 });
      return;
    }
    apiCall
      .getSendMoneyFee(Number(amount))
      .then((res) => {
        setSendMoneyFee({
          loading: false,
          fee: res.data.processing_fee,
          total: res.data.total_amount,
        });
      })
      .catch((error) => {
        setSendMoneyFee({ loading: false, fee: 0, total: 0 });
      });
  };

  //FUNCTION TO HANDLE SUBMIT
  const handleSubmit = (values, helpers) => {
    setRequestStatus(true);
    let recipientDetails = recipients.data?.filter(
      (item) => item.recipient_id == values.recipientID
    );
    let stateData = {
      ...values,
      ...sendMoneyFee,
      details: { ...recipientDetails[0] },
    };

    setTimeout(() => {
      setRequestStatus(false);
      navigate("confirm-transfer", { state: stateData });
    }, 1000);
  };

  useEffect(() => {
    getRecipients();
  }, []);
  return (
    <div className="content-wrapper w-full lg:flex xl:space-x-8 lg:space-x-4 bottomMargin">
      <div className="lg:w-1/2 w-full mb-10 lg:mb-0">
        <div className="add-fund w-full md:p-8 p-4 bg-white dark:bg-dark-white rounded-2xl shadow">
          <Formik
            initialValues={initialValues}
            validationSchema={validationSchema}
            onSubmit={handleSubmit}
          >
            {(props) => {
              return (
                <Form className="transfer-fund-info">
                  {wallet.loading ? (
                    <LoadingSpinner size="8" color="sky-blue" />
                  ) : wallet.data.length ? (
                    <h2 className="my-4 py-2 text-slate-900 dark:text-white text-xl lg:text-2xl font-medium">
                      {wallet.data.map((item) => {
                        if (item.description == "Naira") {
                          return `Withdraw from Naira Wallet : ${item.symbol}${(
                            item.amount * 0.01
                          ).toFixed(2)}`;
                        }
                      })}
                    </h2>
                  ) : wallet.error ? (
                    <h2 className="my-4 py-2 text-slate-900 dark:text-white text-xl lg:text-2xl font-medium">
                      Opps! An Error Occured
                    </h2>
                  ) : (
                    <h2 className="my-4 py-2 text-slate-900 dark:text-white text-xl lg:text-2xl font-medium">
                      No Wallet Information Found!
                    </h2>
                  )}
                  <div className="xl:flex xl:space-x-7 mb-6">
                    <div className="field w-full mb-6 xl:mb-0">
                      <InputCom
                        fieldClass="px-6"
                        label="Amount"
                        type="text"
                        name="amount"
                        placeholder="0"
                        value={props.values.amount}
                        inputHandler={props.handleChange}
                        blurHandler={(e) => {
                          getSendMoneyFee(e);
                        }}
                        // props.handleBlur
                        // onMouseLeave={(e)=>{getSendMoneyFee(e)}}
                      />
                      {props.errors.amount && props.touched.amount && (
                        <p className="text-sm text-red-500">
                          {props.errors.amount}
                        </p>
                      )}
                    </div>

                    <div className="field w-full">
                      <InputCom
                        fieldClass="px-6"
                        label="Fee"
                        type="text"
                        name="fee"
                        value={
                          sendMoneyFee.loading ? "loading" : sendMoneyFee.fee
                        }
                        disable={true}
                      />
                    </div>
                  </div>

                  <div className="md:flex items-center justify-end">
                    <div className="field w-full lg:w-1/2 mb-6">
                      <InputCom
                        fieldClass="px-6"
                        label="Total"
                        type="text"
                        name="total"
                        value={
                          sendMoneyFee.loading ? "loading" : sendMoneyFee.total
                        }
                        disable={true}
                      />
                    </div>
                  </div>

                  <div className="w-full">
                    <div className="relative my-3 md:flex items-center">
                      <div className="transfer-input w-full">
                        <div className="flex items-center justify-start py-2">
                          <label className="text-[#181c32] dark:text-white text-base font-semibold block mb-2.5">
                            Recipient
                            <span className="text-red-500 mx-2">*</span>
                            <span
                              title="Transfer Recipient"
                              className={`text-white text-sm bg-slate-500 w-1 h-1 rounded-full px-3 py-1 cursor-pointer`}
                            >
                              !
                            </span>
                          </label>
                          <Link
                            to="add-recipient"
                            className="mx-1 text-base text-white p-2 bg-[orange] rounded-md hover:opacity-80"
                          >
                            Add New
                          </Link>
                        </div>
                        <select
                          className="w-full text-base p-2 text-dark-gray dark:text-white rounded-md border border-slate-300 outline-0"
                          value={props.values.recipientID}
                          name="recipientID"
                          onChange={props.handleChange}
                          onBlur={props.handleBlur}
                        >
                          {recipients.loading ? (
                            <option className="text-slate-500 text-lg" value="">
                              Loading...
                            </option>
                          ) : recipients.data.length ? (
                            <>
                              <option
                                className="text-slate-500 text-lg"
                                value=""
                              >
                                Select...
                              </option>
                              {recipients.data.map((item, index) => (
                                <option
                                  key={index}
                                  value={item.recipient_id}
                                  className="text-slate-500 text-lg"
                                >
                                  {item.recipient}
                                </option>
                              ))}
                            </>
                          ) : recipients.error ? (
                            <option className="text-slate-500 text-lg" value="">
                              Could'nt Load, try again!
                            </option>
                          ) : (
                            <option className="text-slate-500 text-lg" value="">
                              No Recipient Found! Click Add to Add
                            </option>
                          )}
                        </select>
                      </div>
                    </div>
                    {props.errors.recipientID && props.touched.recipientID && (
                      <p className="text-sm text-red-500">
                        {props.errors.recipientID}
                      </p>
                    )}
                  </div>

                  <div className="field w-full mb-6">
                    {/* <InputCom fieldClass="px-6"
                                            label="Comment"
                                            type="text"
                                            name="comment"
                                            value={inputs.comment}
                                            inputHandler={handleChange}
                                        /> */}
                    <label className="text-[#181c32] dark:text-white text-base font-semibold block mb-2.5">
                      Comment
                    </label>
                    <textarea
                      style={{ resize: "none" }}
                      className="text-base px-6 text-dark-gray dark:text-white w-full bg-slate-100 dark:bg-[#11131F]  focus:ring-0 focus:outline-none"
                      name="comment"
                      value={props.values.comment}
                      onChange={props.handleChange}
                      onBlur={props.handleBlur}
                      cols="30"
                      rows="2"
                    />
                  </div>

                  <div className="transfer-fund-btn flex justify-end items-center py-4">
                    {requestStatus ? (
                      <LoadingSpinner size="8" color="sky-blue" />
                    ) : (
                      <button
                        type="submit"
                        className="text-lg text-white bg-sky-blue px-4 py-2 hover:opacity-90 rounded-md"
                      >
                        Continue
                      </button>
                    )}
                  </div>
                </Form>
              );
            }}
          </Formik>
        </div>
      </div>

      <div className="lg:w-1/2 w-full mb-10 lg:mb-0">
        <div className="wallet w-full  md:p-8 p-4 h-full max-h-[650px] bg-white dark:bg-dark-white overflow-y-auto rounded-2xl shadow">
          <h2 className="text-slate-900 dark:text-white text-xl lg:text-2xl font-medium">
            Recent Activity
          </h2>
          {/* <p className='text-base text-slate-500 dark:text-white'>Activity Report</p> */}
          {payment.loading ? (
            <LoadingSpinner size="16" color="sky-blue" />
          ) : (
            <RecentActivityTable payment={payment} />
          )}
        </div>
      </div>
    </div>
  );
}

export default TransferFund;
