import { Field, Form, Formik } from "formik";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import * as Yup from "yup";
import usersService from "../../services/UsersService";
import { tableReload } from "../../store/TableReloads";
import InputCom from "../Helpers/Inputs/InputCom/index";
import ModalCom from "../Helpers/ModalCom";
import LoadingSpinner from "../Spinners/LoadingSpinner";
import Detail from "./popoutcomponent/Detail";
import { SocketValues } from "../Contexts/SocketIOContext";

// .required("This is required ")

const validationSchema = Yup.object().shape({
  family: Yup.string(),
  public: Yup.string(),
  individual: Yup.string()
    .email("Invalid email format")
    .matches(
      /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
      "Invalid email format"
    ),
  group: Yup.string(),
  depend_uid: Yup.string(),
});

function JobListPopout({
  details,
  onClose,
  situation,
  openWallet,
  setWalletItem,
  myJobList
}) {

  let {marketUpdate} = SocketValues() // destructures 'SEND MESSAGE' and 'JOIN ROOM' FUNCTIONS FROM SOCKET

  const [selectedTab, setSelectedTab] = useState("public");
  const tabs = ["public", "individual", "group"];

  const dispatch = useDispatch();

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

  const [familyList, setFamilyList] = useState([]);
  let [loader, setLoader] = useState({
    member: false,
    jobFields: false
  });

  const apiCall = useMemo(() => new usersService(), []);
  const { walletDetails } = useSelector((state) => state.walletDetails);

  const getWalletDetail = (currency) => {
    // A FUNCTION TO GET USER BALANCE BASED ON TASK CURRENCY
    const walletChecker = walletDetails?.data.find(
      (item) => item.description === currency
    );
    return walletChecker
      ? {
          description: walletChecker.description,
          country: walletChecker.country,
          code: walletChecker.code,
          amount: walletChecker.amount,
        }
      : 0;
  };

  const taskWalletSelector = getWalletDetail(details?.currency);

  const openCreditPopup = () => {
    onClose();
    setWalletItem(taskWalletSelector);
    openWallet();
  };

  // member listing
  const memberList = useCallback(async () => {
    setLoader({ member: true, jobFields: false });
    try {
      let res = await apiCall.familyListings();
      const { data } = res;
      if (data?.internal_return >= 0 && data?.status == "OK") {
        let { result_list } = data;
        setFamilyList(result_list);
        setLoader({ member: false, jobFields: false });
      } else return;
    } catch (error) {
      setLoader({ member: false, jobFields: false });
      throw new Error(error);
    }
  }, [apiCall]);

  useEffect(() => {
    memberList();
  }, [memberList]);

  let initialValues = {
    family: "",
    public: "",
    individual: "",
    group: "",
    depend_uid: ''
  };

  let [textArea, setTextArea] = useState(details?.job_detail);
  const [errMsg, setErrMsg] = useState({
    deliveryDetail: "",
    jobFields: {
      family: "",
      public: "",
      individual: "",
      group: "",
    },
  });

  const handleInputChange = ({ target: { value } }) => {
    setTextArea(value);
  };

  const errorHandler = ({ target: { name } }) => {
    try {
      if (name === "family")
        setErrMsg({ jobFields: { family: "please select a family member" } });
      else if (name === "public")
        setErrMsg({ jobFields: { public: "please select duration" } });
      else if (name === "individual")
        setErrMsg({ jobFields: { individual: "please enter email" } });
      else if (name === "group")
        setErrMsg({ jobFields: { group: "please select a group" } });
    } finally {
      setTimeout(() => {
        setErrMsg({ jobFields: "" });
      }, 5000);
    }
  };

  const jobFieldHandler = async (values, helpers) => {
    setLoader({ jobFields: true });
    let { job_id, job_uid } = details;

    if (!textArea) {
      setErrMsg({ deliveryDetail: "delivery detail is required!" });
      return;
    }

    let jobReq = {
      job_id,
      job_uid,
      job_description: textArea,
    };

    let reqData;

    // for family input
    if (values?.family !== "") {
      reqData = {
        ...jobReq,
        family_uid: values?.family,
        assign_mode: 110011,
      };
    } else if (values?.public !== "") {
      // for public input
      reqData = {
        ...jobReq,
        duration: Number(values?.public),
        assign_mode: 110022,
        depend_uid: values?.depend_uid
      };
    } else if (values?.individual !== "") {
      // for individual input
      reqData = {
        ...jobReq,
        email: values?.individual,
        assign_mode: 110033,
      };
    } else if (values?.group !== "") {
      // for group input
      reqData = {
        ...jobReq,
        email: "",
        group_id: values?.group,
        assign_mode: 110044,
        duration: details?.timeline_days,
        // duration: 0,
      };
    } else {
      setLoader({ jobFields: false });
      return;
    }

    try {
      const res = await apiCall.assignJobTask(reqData);
      let { status, data } = await res;
      if (status != 200 || data.internal_return < 0) {
        setRequestStatus({ message: data?.status ? data?.status : "Unable to assign offer", status: false });
        return setTimeout(() => {
          setLoader({ jobFields: false });
          setRequestStatus({ message: "", status: false });
        }, 5000);
      }
      marketUpdate('market', 'full-markets-jobs') // sends an event to the socket to update market lists
      dispatch(tableReload({ type: "JOBTABLE" }));  // reloads my job page
      dispatch(tableReload({ type: "MARKETTABLELIST" })); // reloads market page
      setRequestStatus({ message: data?.status_msg ? data?.status_msg : "Offer Assigned Successful", status: true });
      setTimeout(() => {
        setLoader({ jobFields: false });
        onClose();
        // throw new Response(data);
      }, 5000);
    } catch (error) {
      setRequestStatus({ message: "Unable to complete", status: false });
      setTimeout(() => {
        setRequestStatus({ message: "", status: false });
        setLoader({ jobFields: false });
        throw new Error(error);
      }, 5000);
    }
  };

  const [groupList, setGroupList] = useState({
    loading: true,
    groups: [],
    members: [],
  });

  const DetailsSection = ({ label, value }) => (
    <div className="my-3 md:flex">
      <Detail label={label} value={value} />
    </div>
  );

  // FUNCTION TO POPULATE USER GROUP LIST
  useEffect(() => {
    // setGroupList({loading: true, groups: [], members: []})
    apiCall
      .jobGroupList({})
      .then((res) => {
        const { status, data } = res;
        if (status != 200 || data?.internal_return < 0) {
          setGroupList({ loading: false, groups: [], members: [] });
          return;
        }
        if (data.result_list.length < 0) {
          setGroupList({ loading: false, groups: [], members: [] });
          return;
        }
        setGroupList({
          loading: false,
          groups: data.result_list,
          members: data.result_list_member,
        });
      })
      .catch((error) => {
        setGroupList({ loading: false, groups: [], members: [] });
      });
  }, []);

  const DetailsComponent = () => {
    const detailsArray = [
      { label: "Description", value: details.description },
      { label: "Reward", value: details.thePrice },
      { label: "Timeline", value: `${details.timeline_days} day(s)` },
      { label: "Created", value: new Date(details?.created).toDateString() },
    ];

    return (
      <div className="px-4 pb-3 w-full md:border-r-2">
        {/* <p className='text-lg font-semibold text-slate-900 tracking-wide'>{details.title}</p> */}

        {/* INPUT SECTION */}
        {detailsArray.map((detail, index) => (
          <DetailsSection
            key={index}
            label={detail.label}
            value={detail.value}
          />
        ))}

        <div className="">
          <label className="w-full text-slate-900 dark:text-white tracking-wide font-semibold">
            Delivery Detail
          </label>
          <textarea
            className={`p-2 w-full text-sm text-slate-900 dark:text-white bg-transparent outline-none border border-slate-300 rounded-md`}
            rows="7"
            style={{ resize: "none" }}
            value={textArea}
            onChange={handleInputChange}
          />
          <p>{errMsg.deliveryDetail}</p>
        </div>
      </div>
    );
  };

  return (
    <ModalCom action={onClose} situation={situation} className="">
      <div className="logout-modal-wrapper w-[90%] md:w-[768px] bg-white dark:bg-dark-white lg:rounded-2xl overflow-y-auto">
        <div className="modal-header-con">
          <h1 className="modal-title">
            {details.title}
          </h1>
          <button
            type="button"
            className="modal-close-btn"
            onClick={onClose}
          >
            <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>

        <div className="md:grid grid-cols-2 bg-white dark:bg-dark-white rounded-lg shadow-lg">
          <DetailsComponent />
          <>
            {/* ACTION SECTION */}
            {+taskWalletSelector.amount > +details.price ? (
              <div className="px-4 pb-3 w-full flex flex-col justify-between">
                <h1 className="text-lg mt-3 font-medium tracking-wide text-black dark:text-white">
                  Send this Task to:
                </h1>
                <div className="flex flex-col grow">
                  <div className="grid grid-cols-3 mt-4">
                    {tabs.map((item) => (
                      <TabButton
                        key={item}
                        item={item}
                        selectedTab={selectedTab}
                        setSelectedTab={setSelectedTab}
                      />
                    ))}
                  </div>
                  <div className="grow flex flex-col bg-red-50 dark:bg-[#D85A5A] rounded-b-2xl">

                    <Formik
                      initialValues={initialValues}
                      validationSchema={validationSchema.fields.public}
                      onSubmit={jobFieldHandler}
                    >
                      {(props) => {
                        return (
                          <Form className="p-3">
                            <div className='flex items-center justify-start mt-1 mb-2.5'>
                              <label
                                className="input-label border-2 w-full border-sky-700 rounded py-4 px-2 text-[#181c32] dark:text-white text-[13.975px] leading-[20.9625px] font-semibold block tracking-wide"
                                // htmlFor={''}
                              >
                                {selectedTab == 'family' ?
                                  'Assign to family'
                                  : selectedTab == 'public' ?
                                  'Offer this job to public'
                                  : selectedTab == 'individual' ?
                                  'Offer this job to individual'
                                  : selectedTab == 'group' ?
                                  'Offer this job to your Group'
                                  :
                                  null
                                }
                              </label>
                            </div>
                            <div className='w-full'>
                              {/* ASSIGN TO FAMILY */}
                              {selectedTab == "family" && (
                                <div className='hidden w-full'>
                                  <JobFieldInput
                                    select={true}
                                    inputName="family"
                                    value={props?.values.family}
                                    data={familyList}
                                    optionText="Select Family"
                                    errorHandler={errorHandler}
                                    parentClass="w-full flex flex-col gap-4"
                                  />
                                  <p className="h-4 text-[13px] font-light italic text-red-600 tracking-wide">
                                    {" "}
                                    {props?.values?.family === "" && (
                                      <span>{errMsg?.jobFields?.family}</span>
                                    )}
                                  </p>{" "}
                                </div>
                              )}

                              {/* ASSIGN TO PUBLIC/MARKET */}
                              {selectedTab == "public" && (
                                <div className='w-full'>
                                  <div className='mb-3 w-full flex flex-col xxs:flex-row items-center gap-1'>
                                    <label className='w-full xxs:max-w-[120px] xxs:text-right'>Depends on</label>
                                    {/* <JobFieldInput
                                      input={true}
                                      select={true}
                                      inputName="depend_uid"
                                      value={props?.values.depend_uid}
                                      data={myJobList}
                                      optionText="None"
                                      parentClass="w-full flex flex-col gap-4"
                                    /> */}
                                    <div
                                      className={`input-wrapper border border-[#f5f8fa] dark:border-[#5e6278] w-full rounded-[1rem] h-[42px] overflow-hidden relative font-medium leading-6 bg-clip-padding text-[#5e6278] dark:text-gray-100 bg-[#f5f8fa] dark:bg-[#5e6278] text-base`}
                                    >
                                      <select 
                                        className='px-2 w-full h-full bg-white border-0 outline-0'
                                        name="depend_uid"
                                        value={props?.values.depend_uid}
                                        onChange={props.handleChange}
                                      >
                                        <>
                                          {myJobList.loading ? (
                                            <option value={""}>Loading...</option>
                                          ) : myJobList?.data?.result_list?.length > 0 ? (
                                            <>
                                              <option value="">None</option>
                                              {myJobList?.data?.result_list?.filter(item => item.job_uid != details.job_uid)?.map((item, index) => (
                                                <option value={item?.job_uid} key={item.job_uid}>
                                                  {item?.title}
                                                </option>
                                              ))}
                                            </>
                                          ) : (
                                            <option value="">No Job Found</option>
                                          )}
                                        </>
                                      </select>
                                    </div>
                                  </div>
                                  
                                  <div className='mb-3 w-full flex flex-col xxs:flex-row items-center gap-1'>
                                    <label className='w-full xxs:max-w-[120px] xxs:text-right'>Duration <span className='text-red-600 tracking-wide'>{(props?.values.public === "" && errMsg?.jobFields?.public) && '*'}</span></label>
                                    <div className='w-full'>
                                      <JobFieldInput
                                        select={true}
                                        inputName="public"
                                        value={props?.values.public}
                                        data={publicArray}
                                        optionText="Select Duration"
                                        parentClass="w-full flex flex-col gap-4"
                                      />
                                      {/* <p className="h-4 text-[13px] font-light italic text-red-600 tracking-wide">
                                        {" "}
                                        {props?.values.public === "" && (
                                          <span>{errMsg?.jobFields?.public}</span>
                                        )}
                                      </p>{" "} */}
                                    </div>
                                  </div>
                                </div>
                              )}

                              {/* ASSIGN TO INDIVIDUAL */}
                              {selectedTab == "individual" && (
                                <div className='w-full'>
                                  <JobFieldInput
                                    input={true}
                                    inputName="individual"
                                    value={props?.values.individual}
                                    placeholder="Enter email of individual"
                                    inputHandler={props?.handleChange}
                                    parentClass="w-full flex flex-col gap-4"
                                  />
                                  <p className="h-4 text-[13px] font-light italic text-red-600 tracking-wide">
                                    {" "}
                                    {props?.values.individual === "" && (
                                      <span>{errMsg?.jobFields?.individual}</span>
                                    )}
                                  </p>{" "}
                                </div>
                              )}

                              {/* ASSIGN TO GROUP */}
                              {selectedTab == "group" && (
                                <div className='w-full'>
                                  <JobFieldInput
                                    select={true}
                                    inputName="group"
                                    value={props?.values.group}
                                    optionText="Select Group"
                                    data={groupList}
                                    parentClass="w-full flex flex-col gap-4"
                                  />
                                  <p className="h-4 text-[13px] font-light italic text-red-600 tracking-wide">
                                    {" "}
                                    {props?.values.group === "" && (
                                      <span>{errMsg?.jobFields?.group}</span>
                                    )}
                                  </p>
                                </div>
                              )}
                            </div>
                            <div className="mt-3 mb-1 flex justify-end items-center">
                              <button
                                className={`px-4 h-11 flex justify-center items-center btn-gradient text-base rounded-full text-white`}
                                type="submit"
                                name={
                                  selectedTab == 'family' ?
                                  'family'
                                  : selectedTab == 'public' ?
                                  'public'
                                  : selectedTab == 'individual' ?
                                  'individual'
                                  : selectedTab == 'group' ?
                                  'group'
                                  :
                                  null
                                }
                                onClick={errorHandler}
                                // disabled={!value}
                              >
                                {loader?.jobFields ? 
                                  <LoadingSpinner size={5} /> 
                                  : selectedTab == 'family' ?
                                  'Assign to family'
                                  : selectedTab == 'public' ?
                                  'Show Task to Public'
                                  : selectedTab == 'individual' ?
                                  'Send Offer to Individual'
                                  : selectedTab == 'group' ?
                                  'Send Order to Group'
                                  :
                                  null
                                }
                              </button>
                            </div>
                          </Form>
                        );
                      }}
                    </Formik>
                    <p
                      className={`text-center w-full text-lg ${
                        requestStatus.status
                          ? "text-emerald-600"
                          : "text-red-600"
                      }`}
                    >
                      {requestStatus.message && requestStatus.message}
                    </p>
                  </div>
                </div>
              </div>
            ) : (
              <ZeroBalanceChecker
                {...taskWalletSelector}
                openCreditPopup={openCreditPopup}
              />
            )}

            {/* END OF ACTION SECTION */}
          </>
        </div>
      </div>
    </ModalCom>
  );
}

export default JobListPopout;

const JobFieldInput = ({
  value,
  inputHandler,
  inputName,
  inputClass,
  placeholder,
  input,
  select,
  label,
  labelClass,
  parentClass,
  optionText,
  data,
}) => {
  return (
    <div className="field w-full flex flex-col justify-between gap-4">
      {select && (
        <>
          <div className={`input-com ${parentClass}`}>
            <div
              className={`input-wrapper border border-[#f5f8fa] dark:border-[#5e6278] w-full rounded-[1rem] h-[42px] overflow-hidden relative font-medium leading-6 bg-clip-padding text-[#5e6278] dark:text-gray-100 bg-[#f5f8fa] dark:bg-[#5e6278] text-base ${inputClass}`}
            >
              <Field
                component="select"
                name={inputName}
                className={`options-default`}
                value={value}
              >
                {/* <option value="">{optionText}</option> */}
                {(inputName == "family" || inputName == "public") &&
                  Array.isArray(data) && (
                    <>
                      <option value="">{optionText}</option>
                      {data?.map((item, idx) => (
                        <React.Fragment key={idx}>
                          {inputName === "family" &&
                            item?.last_login !== "" && (
                              <option value={item?.family_uid} key={idx}>
                                {`${item?.firstname} ${item?.lastname}`}
                              </option>
                            )}
                          {inputName === "public" && (
                            <option value={item?.duration} key={idx}>
                              {item?.name}
                            </option>
                          )}
                        </React.Fragment>
                      ))}
                    </>
                  )}
                {inputName == "group" && (
                  <>
                    {data.loading ? (
                      <option value={""}>Loading...</option>
                    ) : data?.groups?.length > 0 ? (
                      <>
                        <option value="">{optionText}</option>
                        {data?.groups?.map((item, index) => (
                          <option value={item?.group_id} key={index}>
                            {`${item?.group_name} (${
                              item?.member_count == null
                                ? "0"
                                : ' ' + item.member_count + ' '
                            })`}
                          </option>
                        ))}
                      </>
                    ) : (
                      <option value="">No Group Found</option>
                    )}
                  </>
                )}
              </Field>
            </div>
          </div>
        </>
      )}

      {input && (
        <InputCom
          fieldClass="px-6"
          type="email"
          name={inputName}
          placeholder={placeholder}
          value={value}
          inputHandler={inputHandler}
          inputBg="bg-white"
          parentClass={`${parentClass}`}
        />
      )}
    </div>
  );
};

const publicArray = [
  { duration: 1, name: "1 day" },
  { duration: 2, name: "2 days" },
  { duration: 3, name: "3 days" },
  { duration: 4, name: "4 days" },
  { duration: 5, name: "5 days" },
  { duration: 6, name: "6 days" },
  { duration: 7, name: "1 week" },
  { duration: 14, name: "2 weeks" },
  { duration: 21, name: "3 weeks" },
  { duration: 28, name: "4 weeks" },
];

const ZeroBalanceChecker = ({ amount, code, country, openCreditPopup }) => {
  return (
    <div className="px-4 pb-3 w-full flex flex-col gap-5 items-center">
      <h1 className="text-lg mt-3 font-medium tracking-wide text-black dark:text-white">
        Wallet Balance:{` ${code} ${(+amount * 0.01).toFixed(2)}`}
      </h1>
      <p className="font-semibold text-center text-red-500 text-lg">
        You do not have sufficient balance to assign this task
      </p>
      <button
        onClick={openCreditPopup}
        className="btn-gradient w-48 h-[46px] text-white rounded-full text-base bg-pink flex justify-center items-center"
      >
        Add Credit to Wallet
      </button>
    </div>
  );
};

const TabButton = ({ item, selectedTab, setSelectedTab }) => (
  <button
    className={`px-4 py-1 rounded-t-2xl border-t-[2px] transition-all duration-200 flex flex-col justify-center items-center ${
      selectedTab === item
        ? "bg-red-50 dark:bg-[#D85A5A] text-slate-600 font-extrabold"
        : "bg-white text-[#000]"
    }`}
    value={item}
    name={item}
    onClick={() => setSelectedTab(item)}
  >
    <div
      className={`mb-[1px] h-6 w-6 border-4 rounded-full transition-all duration-200 ${
        selectedTab === item
          ? "border-white bg-emerald-500"
          : "border-red-50 dark:border-[#D85A5A] bg-white"
      }`}
    ></div>
    {item[0].toUpperCase() + item.slice(1)}
  </button>
);
