import { Field, Form, Formik } from "formik";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import * as Yup from "yup";
import SiteService from "../../services/SiteService";
import InputCom from "../Helpers/Inputs/InputCom/index";
import ModalCom from "../Helpers/ModalCom";
import LoadingSpinner from "../Spinners/LoadingSpinner";
import Detail from "./popoutcomponent/Detail";

const validationSchema = Yup.object().shape({
  family: Yup.string().required("This is required "),
  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"
    )
    .required("Email is required"),
  group: Yup.string(),
});

function JobListPopout({ details, onClose, situation }) {
  const [familyList, setFamilyList] = useState([]);
  let [loader, setLoader] = useState({
    member: false,
    jobFields: {
      family: false,
      public: false,
      individual: false,
      group: false,
    },
  });

  const apiCall = useMemo(() => new SiteService(), []);

  // member listing
  const memberList = useCallback(async () => {
    setLoader({ member: true, jobFields: false });
    try {
      let reqData = {
        limit: 20,
        offset: 0,
        action: 22010,
      };

      let res = await apiCall.familyListings(reqData);
      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: "",
  };

  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 family member" } });
    } finally {
      setTimeout(() => {
        setErrMsg({ jobFields: "" });
      }, 3000);
    }
  };

  const jobFieldHandler = async (values, helpers) => {
    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,
        action: 13025,
        assign_mode: 110011,
      };
      setLoader({ jobFields: { family: true } });
    } else if (values?.public !== "") {
      // for public input
      reqData = {
        ...jobReq,
        duration: Number(values?.public),
        action: 13025,
        assign_mode: 110022,
      };
      setLoader({ jobFields: { public: true } });
    } else if (values?.individual !== "") {
      // for individual input
      reqData = {
        ...jobReq,
        email: values?.individual,
        action: 13025,
        assign_mode: 110033,
      };
      setLoader({ jobFields: { individual: true } });
    } else if (values?.group !== "") {
      // for group input
      reqData = {
        ...jobReq,
        email: values?.individual,
        action: 13025,
        assign_mode: 110033,
      };
      setLoader({ jobFields: { group: true } });
    } else {
      return;
    }

    try {
      const res = await apiCall.assignJobTask(reqData);
      let { data } = await res;
      setLoader({ jobFields: false });
      onClose();
      throw new Response(data);
    } catch (error) {
      setLoader({ jobFields: false });
      throw new Error(error);
    }
  };

  // console.log("Job List P >> ", details)
  return (
    <ModalCom action={onClose} situation={situation} className="job-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 overflow-y-auto">
        <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">
          <h1 className="text-base md:text-lg font-bold text-dark-gray dark:text-white tracking-wide">
            {details.title}
          </h1>
          <button
            type="button"
            className="text-[#374557] dark:text-red-500"
            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:flex bg-white dark:bg-dark-white rounded-lg shadow-lg">
          <div className="p-4 w-full md:w-2/4 md:border-r-2">
            {/* <p className='text-lg font-semibold text-slate-900 tracking-wide'>{details.title}</p> */}

            {/* INPUT SECTION */}
            <div className="my-3 md:flex">
              <Detail label="Description" value={details.description} />
            </div>

            <div className="my-3 md:flex">
              <Detail label="Price" value={details.thePrice} />
            </div>

            <div className="my-3 md:flex">
              <Detail
                label="Timeline"
                value={`${details.timeline_days} day(s)`}
              />
            </div>

            <div className="my-3 md:flex">
              <Detail
                label="Created"
                value={new Date(details?.created).toDateString()}
                />
            </div>

            <div className="my-3">
              <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>

          {/* ACTION SECTION */}
          <div className="p-4 w-full md:w-2/4 h-full">
            <Formik
              initialValues={initialValues}
              validationSchema={validationSchema.fields.family}
              onSubmit={jobFieldHandler}
            >
              {(props) => {
                return (
                  <Form className="mb-4 hidden">
                    {/* Assign to Family */}
                    <JobFieldInput
                      label="Assign to family"
                      select={true}
                      inputName="family"
                      value={props?.values.family}
                      data={familyList}
                      btnText="Assign to family"
                      optionText="Select Family"
                      loader={loader?.jobFields.family}
                      errorHandler={errorHandler}
                    />
                    <p className="h-4 text-[13px] font-light italic text-red-600 tracking-wide">
                      {" "}
                      {props?.values.family === "" && (
                        <span>{errMsg.jobFields.family}</span>
                      )}
                    </p>{" "}
                  </Form>
                );
              }}
            </Formik>

            <Formik
              initialValues={initialValues}
              validationSchema={validationSchema.fields.public}
              onSubmit={jobFieldHandler}
            >
              {(props) => {
                return (
                  <Form className="mb-4">
                    {/* Offer this job to public input */}
                    <JobFieldInput
                      label="Offer this job to public"
                      select={true}
                      inputName="public"
                      value={props?.values.public}
                      data={publicArray}
                      btnText="Show Task to Public"
                      optionText="Select Duration"
                      loader={loader?.jobFields.public}
                      errorHandler={errorHandler}
                    />
                    <p className="h-4 text-[13px] font-light italic text-red-600 tracking-wide">
                      {" "}
                      {props?.values.public === "" && (
                        <span>{errMsg.jobFields.public}</span>
                      )}
                    </p>{" "}
                  </Form>
                );
              }}
            </Formik>

            <Formik
              initialValues={initialValues}
              validationSchema={validationSchema.fields.individual}
              onSubmit={jobFieldHandler}
            >
              {(props) => {
                return (
                  <Form className="mb-4">
                    {/* Offer this job to individual input */}
                    <JobFieldInput
                      label="Offer this job to individual"
                      input={true}
                      inputName="individual"
                      value={props?.values.individual}
                      placeholder="Enter email of individual"
                      inputHandler={props?.handleChange}
                      btnText="Send Offer to Individual"
                      loader={loader?.jobFields.individual}
                      errorHandler={errorHandler}
                    />
                    <p className="h-4 text-[13px] font-light italic text-red-600 tracking-wide">
                      {" "}
                      {props?.values.individual === "" && (
                        <span>{errMsg.jobFields.individual}</span>
                      )}
                    </p>{" "}
                  </Form>
                );
              }}
            </Formik>
            
            { process.env.REACT_APP_SHOW_OFFER_GROUP_JOB != 0 &&
            <Formik
              initialValues={initialValues}
              validationSchema={validationSchema.fields.group}
              onSubmit={jobFieldHandler}
            >
              {(props) => {
                return (
                  <Form className="mb-4">
                    {/* Offer this job to your group input */}
                    <JobFieldInput
                      label="Offer this job to your Group"
                      select={true}
                      inputName="group"
                      value={props?.values.group}
                      btnText="Send Order to Group"
                      optionText="Group"
                      loader={loader?.jobFields.group}
                      errorHandler={errorHandler}
                    />
                    <p className="h-4 text-[13px] font-light italic text-red-600 tracking-wide">
                      {" "}
                      {props?.values.group === "" && (
                        <span>{errMsg.jobFields.group}</span>
                      )}
                    </p>
                  </Form>
                );
              }}
            </Formik>
            }
          </div>
          {/* END OF ACTION SECTION */}
        </div>
      </div>
    </ModalCom>
  );
}

export default JobListPopout;

const JobFieldInput = ({
  value,
  inputHandler,
  inputName,
  inputClass,
  placeholder,
  input,
  select,
  label,
  labelClass,
  btnText,
  parentClass,
  optionText,
  errorHandler,
  loader,
  data,
}) => {
  return (
    <div className="field w-full p-3 mb-2 bg-red-50 dark:bg-[#D85A5A] rounded-md">
      {select && (
        <>
          <div className={`input-com ${parentClass}`}>
            <div
              className={`flex items-center justify-start mb-2.5 ${labelClass}`}
            >
              {label && (
                <label
                  className="input-label text-[#181c32] dark:text-white text-[13.975px] leading-[20.9625px] font-semibold block tracking-wide"
                  htmlFor={inputName}
                >
                  {label}
                </label>
              )}
            </div>
            <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={`input-field placeholder:text-base text-dark-gray w-full h-full bg-white outline-none px-2`}
                value={value}
              >
                <option value="">{optionText}</option>
                {Array.isArray(data) &&
                  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>
                      )}
                      {inputName === "group" && (
                        <option value={item?.family_uid} key={idx}>
                          {item?.firstname}
                        </option>
                      )}
                    </React.Fragment>
                  ))}
              </Field>
            </div>
          </div>
        </>
      )}

      {input && (
        <InputCom
          fieldClass="px-6"
          label={label}
          labelClass="tracking-wide"
          type="email"
          name={inputName}
          placeholder={placeholder}
          value={value}
          inputHandler={inputHandler}
          inputBg="bg-white"
        />
      )}

      {/* btn */}
      <div className="my-1 flex justify-end items-center">
        <button
          type="submit"
          name={inputName}
          onClick={errorHandler}
          // className={`px-2 py-1 text-sm text-white btn-gradient tracking-wide rounded-md ${
          //   !value && "disabled:grayscale-[65%] transition duration-300"
          // }`}
          className={`px-4 h-11 flex justify-center items-center btn-gradient text-base rounded-full text-white ${
            !value && ""
          }
          `}
          // disabled={!value}
        >
          {loader ? <LoadingSpinner size={5} /> : btnText}
        </button>
      </div>
    </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" },
];
