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

import { Form, Formik } from "formik";
import * as Yup from "yup";
import ReferralTable from "../MyWallet/WalletComponent/ReferralTable";

const validationSchema = Yup.object().shape({
  email: Yup.string()
    .email("Wrong email format")
    .min(3, "Minimum 3 characters")
    .max(50, "Maximum 50 characters")
    .required("Email is required"),
  firstname: Yup.string()
    .min(3, "Minimum 3 characters")
    .max(25, "Maximum 25 characters")
    .required("Firstname is required"),
  lastname: Yup.string()
    .min(3, "Minimum 3 characters")
    .max(25, "Maximum 25 characters")
    .required("Lastname is required"),
});

const initialValues = {
  firstname: "",
  lastname: "",
  email: "",
};

function ReferralDisplay() {
  const apiCall = new usersService(); // GET API CALL
  const navigate = useNavigate();

  let [refHistoryReload, setRefHistoryReload] = useState(false); // Determines when referral history reloads

  // STATE TO HOLD REFERRAL HISTORY
  let [referralList, setReferralList] = useState({
    loading: true,
    error: false,
    data: [],
  });

  let [error, setError] = useState({
    message: "",
    loading: false,
    status: false,
  }); // for displaying error message on the page

  //function to call referral history API
  const allReferrals = () => {
    setReferralList({
      loading: true,
      error: false,
      data: [],
    });
    apiCall
      .getReferralHx()
      .then((res) => {
        setReferralList((prev) => {
          return { ...prev, loading: false, data: [...res.data.result_list] };
        });
      })
      .catch((error) => {
        setReferralList((prev) => ({ ...prev, loading: false, error: true }));
      });
  };

  //FUNCTION TO SEND REFERRAL MESSAGE
  const sendReferralMsg = (postData) => {
    apiCall
      .sendReferralMsg(postData)
      .then((res) => {
        if (res.data.internal_return < 0) {
          setError({
            message: "Email already referred",
            loading: false,
            status: false,
          });
          return;
        } else {
          toast.success("Message Sent");
          setError({ message: "", loading: false, status: true });
          setRefHistoryReload((prev) => !prev);
        }
      })
      .catch((error) => {
        setError({
          message: "Opps! an error occured, try again later",
          loading: false,
          status: false,
        });
      });
  };

  //FUNCTION TO HANDLE SUBMIT
  const handleSubmit = (values, helpers) => {
    setError({ message: "", loading: true, status: false });

    var postData = {
      uid: localStorage.getItem("uid"),
      member_id: localStorage.getItem("member_id"),
      sessionid: localStorage.getItem("session_token"),
      action: 11032,
      ...values,
    };

    sendReferralMsg(postData); // FUNCTION TO SEND REFERRAL MESSAGE
  };

  useEffect(() => {
    allReferrals();
  }, [refHistoryReload]);

  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="referral w-full  md:p-8 p-4 h-full bg-white dark:bg-dark-white rounded-2xl shadow">
          <h2 className="text-slate-900 dark:text-white text-xl lg:text-2xl font-medium">
            Send Referral
          </h2>
          <Formik
            initialValues={initialValues}
            validationSchema={validationSchema}
            onSubmit={handleSubmit}
          >
            {(props) => (
              <Form className="referral-info">
                {/* Firstname */}
                <div className="field w-full mb-6">
                  <InputCom
                    fieldClass="px-6"
                    label="Firstname"
                    type="text"
                    name="firstname"
                    placeholder="Firstname"
                    value={props.values.firstname}
                    inputHandler={props.handleChange}
                    blurHandler={props.handleBlur}
                  />
                  {props.errors.firstname && props.touched.firstname && (
                    <p className="text-sm text-red-500">
                      {props.errors.firstname}
                    </p>
                  )}
                </div>

                {/* Lastname */}
                <div className="field w-full mb-6">
                  <InputCom
                    fieldClass="px-6"
                    label="Lastname"
                    type="text"
                    name="lastname"
                    placeholder="Lastname"
                    value={props.values.lastname}
                    inputHandler={props.handleChange}
                    blurHandler={props.handleBlur}
                  />
                  {props.errors.lastname && props.touched.lastname && (
                    <p className="text-sm text-red-500">
                      {props.errors.lastname}
                    </p>
                  )}
                </div>

                <div className="field w-full mb-6">
                  <InputCom
                    fieldClass="px-6"
                    label="Email"
                    type="text"
                    name="email"
                    placeholder="Email"
                    value={props.values.email}
                    inputHandler={props.handleChange}
                    blurHandler={props.handleBlur}
                  />
                  {props.errors.email && props.touched.email && (
                    <p className="text-sm text-red-500">{props.errors.email}</p>
                  )}
                </div>

                <hr />
                {error.message != "" && (
                  <p className="text-base text-red-500 py-2">{error.message}</p>
                )}
                <div className="referral-btn flex justify-end items-center py-4 border-b-4">
                  {error.loading ? (
                    <LoadingSpinner size="6" color="sky-blue" />
                  ) : (
                    <button
                      type="submit"
                      className="text-lg text-white bg-sky-blue p-2 hover:opacity-90 rounded-md"
                    >
                      Send Message
                    </button>
                  )}
                </div>
              </Form>
            )}
          </Formik>
        </div>
      </div>

      <div className="lg:w-1/2 w-full mb-10 lg:mb-0">
        <div className="referral w-full md:p-8 p-4 h-full max-h-[700px] bg-white dark:bg-dark-white overflow-y-auto rounded-2xl shadow">
          <h2 className="mb-2 text-slate-900 dark:text-white text-xl lg:text-2xl font-medium">
            Referral List
          </h2>
          {referralList.loading ? (
            <LoadingSpinner size="32" color="sky-blue" />
          ) : (
            <ReferralTable history={referralList} />
          )}
        </div>
      </div>
    </div>
  );
}

export default ReferralDisplay;
