"use client";

import AppHeader from "@comp/AppHeader/page";
import AppContext from "@ctx/AppContext";
import Buttonbriz from "plugins/Buttonbriz/page";
import DatePickerIran from "plugins/DatePickerIran/page";
import Input from "plugins/Input/page";
import PersianNumber from "plugins/PersianNumber";
import React, { useContext, useEffect, useRef, useState } from "react";
import { toast } from "react-toastify";
import SimpleReactValidator from "simple-react-validator";
import moment from "jalali-moment";
import { useRouter, useSearchParams } from "next/navigation";

const AddTask = () => {
  const CTX = useContext(AppContext);
  const query = useSearchParams();

  const [routinesSelectData, setRoutinesSelectData] = useState([]);
  const [routineForTaskCurrent, setRoutineForTaskCurrent] = useState([]);

  const [positionsSelectData, setPositionsSelectData] = useState([]);
  const [positionsForTaskCurrent, setPositionsForTaskCurrent] = useState([]);

  const [shiftsSelectData, setShiftsSelectData] = useState([]);
  const [shiftsForTaskCurrent, setShiftsForTaskCurrent] = useState([]);

  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [scheduleType, setScheduleType] = useState(1);

  const [birthDateTimeStamp, setBirthDateTimeStamp] = useState(0);

  const [shiftsDaysSelectData, setShiftsDaysSelectData] = useState(null);
  const [shiftsDaysCurrent, setShiftsDaysCurrent] = useState(null);

  const [, forceUpdate] = useState();

  const routinesData = CTX.state.routinesData;
  const positionsData = CTX.state.positionsData;
  const shiftsData = CTX.state.shiftsData;
  const routineForTaskChoose = CTX.state.routineForTaskChoose;
  const positionsForTaskChoose = CTX.state.positionsForTaskChoose;
  const shiftsForTaskChoose = CTX.state.shiftsForTaskChoose;
  const shiftsDaysChoose = CTX.state.shiftsDaysChoose;
  const goToEditTask = CTX.state.goToEditTask;
  const taskData = CTX.state.taskData;
  const idEditTask = CTX.state.idEditTask;
  const aqueryNew = query.get("new");

  const schedule = [
    { key: "هفتگی", value: 1 },
    { key: "روزانه", value: 0 },
    { key: "مخصوص یک روز ", value: 2 },
  ];

  const week = [
    { key: "شنبه", value: 6 },
    { key: "یکشنبه", value: 0 },
    { key: "دوشنبه", value: 1 },
    { key: "سه شنبه", value: 2 },
    { key: "چهار شنبه", value: 3 },
    { key: "پنج شنبه", value: 4 },
    { key: "جمعه", value: 5 },
  ];

  const validator = useRef(
    new SimpleReactValidator({
      messages: {
        required: "پر کردن این فیلد الزامی میباشد",
      },
      element: (message) => (
        <>
          <div className="text-right px-1 ">
            <small className="text-red-600 t-ig-small  ">{message}</small>
          </div>
        </>
      ),
    })
  );

  const body = {
    title,
    description,
    routines: routineForTaskChoose,
    positions: positionsForTaskChoose,
    shifts: shiftsForTaskChoose,
    scheduleType,
    setFor:
      birthDateTimeStamp &&
      moment
        .utc(
          [
            birthDateTimeStamp.year,
            birthDateTimeStamp.month,
            birthDateTimeStamp.day,
          ],
          "jYYYY-jMM-jDDTHH"
        )
        .unix(),
    days: shiftsDaysChoose,
  };

  const bodyUpdate = {
    title,
    description,
    routines: routineForTaskChoose,
    positions: positionsForTaskChoose,
    shifts: shiftsForTaskChoose,
    scheduleType,
    setFor:
      birthDateTimeStamp &&
      moment
        .utc(
          [
            birthDateTimeStamp.year,
            birthDateTimeStamp.month,
            birthDateTimeStamp.day,
          ],
          "jYYYY-jMM-jDDTHH"
        )
        .unix(),
    days: shiftsDaysChoose,
    id: idEditTask,
  };

  const clear = () => {
    setPositionsForTaskCurrent([]);
    setPositionsSelectData([]);
    setRoutineForTaskCurrent([]);
    setRoutinesSelectData([]);
    setBirthDateTimeStamp(0);
    setScheduleType([]);
    setDescription([]);
    setTitle("");
    setShiftsForTaskCurrent([]);
    setShiftsSelectData([]);
    setShiftsDaysCurrent([]);
    setShiftsDaysSelectData([]);
    CTX.setRoutineForTaskChoose([]);
    CTX.setPositionsForTaskChoose([]);
    CTX.setShiftsForTaskChoose([]);
    CTX.setShiftsDaysChoose([]);
  };

  const handleCreateTask = (update) => {
    if (scheduleType == 0) {
      validator.current.message("shiftsDaysChoose", true, "required");
      validator.current.message("birthDateTimeStamp", true, "required");
    }

    if (scheduleType == 1) {
      validator.current.message("birthDateTimeStamp", true, "required");
    }

    if (scheduleType == 2) {
      validator.current.message("shiftsDaysChoose", true, "required");
    }

    if (validator.current.allValid()) {
      if (update == "UPDATE") {
        CTX.UpdateTask(bodyUpdate);
      } else {
        CTX.CreateTask(body);
      }
    } else {
      toast.error("پرکردن همه ی فیلد ها واجب است", {
        position: "bottom-right",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });

      validator.current.showMessages();
      forceUpdate(1);
    }
  };

  const deleteRoutineForTask = (value) => {
    CTX.setRoutineForTaskChoose(
      routineForTaskChoose.filter((el) => el !== value)
    );
  };

  const deletePositionForTask = (value) => {
    CTX.setPositionsForTaskChoose(
      positionsForTaskChoose.filter((el) => el !== value)
    );
  };

  const deleteShiftForTask = (value) => {
    CTX.setShiftsForTaskChoose(
      shiftsForTaskChoose.filter((el) => el !== value)
    );
  };

  const deleteShiftsDaysForTask = (value) => {
    CTX.setShiftsDaysChoose(shiftsDaysChoose.filter((el) => el !== value));
  };

  useEffect(() => {
    if (aqueryNew) {
      clear();
    }
    CTX.GetRoutines();
    CTX.GetPositions();
    CTX.GetShifts();
  }, []);

  useEffect(() => {
    setRoutinesSelectData(
      routinesData?.map((item) => ({
        key: item?.name,
        value: item?.id,
      }))
    );
  }, [routinesData]);

  useEffect(() => {
    setPositionsSelectData(
      positionsData?.map((item) => ({
        key: item?.name,
        value: item?.id,
      }))
    );
  }, [positionsData]);

  useEffect(() => {
    setShiftsSelectData(
      shiftsData?.map((item) => ({
        key: item?.title,
        value: item?.id,
      }))
    );
  }, [shiftsData]);

  useEffect(() => {
    setShiftsDaysSelectData(
      shiftsForTaskChoose?.length > 0 &&
        shiftsData
          ?.find((e) => e?.id == shiftsForTaskChoose[0])
          ?.days?.map((item) => ({
            key: week?.find((e) => e.value == item)?.key,
            value: item,
          }))
    );
  }, [shiftsForTaskChoose]);

  useEffect(() => {
    switch (scheduleType) {
      case 0:
        setBirthDateTimeStamp(0);
        CTX.setShiftsDaysChoose([]);

        break;
      case 1:
        setBirthDateTimeStamp(0);

        break;
      case 2:
        CTX.setShiftsDaysChoose([]);

        break;
      default:
        break;
    }
  }, [scheduleType]);

  useEffect(() => {
    // ;

    if (goToEditTask) {
      // const date = moment
      //   .unix(taskData.birthDateTimeStamp)
      //   .locale("fa")
      //   .format("YYYY/MM/DD")
      //   .split("/");

      // setBirthDateTimeStamp({
      //   day: parseInt(date[2]),
      //   month: parseInt(date[1]),
      //   year: parseInt(date[0]),
      // });
      setScheduleType(taskData.scheduleType);
      setDescription(taskData.description);
      setTitle(taskData.title);
      CTX.setRoutineForTaskChoose(
        taskData.routines?.map((item) => item.routineId)
      );
      CTX.setPositionsForTaskChoose(
        taskData.positions?.map((item) => item.positionId)
      );
      CTX.setShiftsDaysChoose(taskData.days?.map((item) => item.dayOfWeek));
      CTX.setShiftsForTaskChoose(taskData.shifts?.map((item) => item.shiftId));
    }
  }, [taskData]);

  return (
    <div className="pb-20">
      <AppHeader
        title=" افزودن فعالیت جدید"
        sub=" قابلیت افزودن فعالیت جدید مختلف"
        icon2={true}
        iconName2="ARROW"
        iconHref2="/home"
      />

      <div className="bg-body-100 relative top-[-30px] rounded-t-3xl overflow-hidden p-4 rtl">
        <div>
          <div className="">
            <Input
              lable="عنوان فعالیت"
              id="title-id"
              name="title"
              type={"text"}
              value={title}
              inputEvent={(e) => {
                setTitle(e.target.value);
                validator.current.showMessageFor("title");
              }}
              style="text-right"
              validator={true}
              validatorData={validator.current.message(
                "title",
                title,
                "required"
              )}
            />
          </div>

          <div className="">
            <Input
              lable=" توضیحات"
              id="description-id"
              name="description"
              type={"text"}
              value={description}
              inputEvent={(e) => {
                setDescription(e.target.value);
                validator.current.showMessageFor("description");
              }}
              textarea={true}
              style="text-right"
            />
          </div>
          {/* ===========routine=============== */}

          <div className="">
            <Input
              lable="روتین فعالیت"
              id="routines-id"
              name="routines"
              type={"text"}
              inputEvent={(e) => {
                setRoutineForTaskCurrent(e.target.value);
                validator.current.showMessageFor("routines");

                if (routineForTaskChoose.length >= 1) {
                  toast.error(
                    "فعلا معلوم نیست بیشتر از یکی بتونی باید با ممد اینا حرف بزنیم",
                    {
                      position: "bottom-right",
                      closeOnClick: true,
                    }
                  );
                } else {
                  if (!!routineForTaskChoose.find((b) => b == e.target.value)) {
                    toast.error("روز  تکراری است", {
                      position: "bottom-right",
                      closeOnClick: true,
                    });
                  } else {
                    CTX.setRoutineForTaskChoose((current) => [
                      ...current,
                      e.target.value,
                    ]);
                  }
                }
              }}
              style="text-right"
              validator={true}
              validatorData={validator.current.message(
                "routines",
                routineForTaskChoose,
                ["required", { min: 1 }]
              )}
              select={true}
              selectData={routinesSelectData}
              defaultValue={"انتخاب کنید"}
            />
          </div>

          <div className="flex flex-wrap  rtl">
            {routineForTaskChoose &&
              routineForTaskChoose.map((e, index) => (
                <div
                  className="flex bg-gray-300 p-1 rounded-full m-1 justify-start mt-3"
                  key={index}
                >
                  <div
                    className="w-[30px] h-[30px] rounded-full bg-gray-400 "
                    onClick={() => deleteRoutineForTask(e)}
                  ></div>

                  <div>
                    <p className="mb-0 px-3 text-sm mt-1">
                      {routinesData?.find((b) => b.id == e)?.name}
                    </p>
                  </div>
                </div>
              ))}
          </div>
          {/* ===========position=============== */}

          <div className="">
            <Input
              lable="پوزیشن فعالیت"
              id="positions-id"
              name="positions"
              type={"text"}
              inputEvent={(e) => {
                setPositionsForTaskCurrent(e.target.value);
                validator.current.showMessageFor("positions");

                if (positionsForTaskChoose.length >= 1) {
                  toast.error(
                    "فعلا معلوم نیست بیشتر از یکی بتونی باید با ممد اینا حرف بزنیم",
                    {
                      position: "bottom-right",
                      closeOnClick: true,
                    }
                  );
                } else {
                  if (
                    !!positionsForTaskChoose.find((b) => b == e.target.value)
                  ) {
                    toast.error("روز  تکراری است", {
                      position: "bottom-right",
                      closeOnClick: true,
                    });
                  } else {
                    CTX.setPositionsForTaskChoose((current) => [
                      ...current,
                      e.target.value,
                    ]);
                  }
                }
              }}
              style="text-right"
              validatorData={validator.current.message(
                "positions",
                positionsForTaskChoose,
                ["required", { min: 1 }]
              )}
              select={true}
              selectData={positionsSelectData}
              defaultValue={"انتخاب کنید"}
            />
          </div>

          <div className="flex flex-wrap  rtl">
            {positionsForTaskChoose &&
              positionsForTaskChoose.map((e, index) => (
                <div
                  className="flex bg-gray-300 p-1 rounded-full m-1 justify-start mt-3"
                  key={index}
                >
                  <div
                    className="w-[30px] h-[30px] rounded-full bg-gray-400 "
                    onClick={() => deletePositionForTask(e)}
                  ></div>

                  <div>
                    <p className="mb-0 px-3 text-sm mt-1">
                      {positionsData?.find((b) => b.id == e)?.name}
                    </p>
                  </div>
                </div>
              ))}
          </div>

          {/* ===========shifts=============== */}
          <div className="">
            <Input
              lable="شیفت فعالیت"
              id="shifts-id"
              name="shifts"
              type={"text"}
              inputEvent={(e) => {
                setShiftsForTaskCurrent(e.target.value);
                validator.current.showMessageFor("shifts");

                if (shiftsForTaskChoose.length >= 1) {
                  toast.error(
                    "فعلا معلوم نیست بیشتر از یکی بتونی باید با ممد اینا حرف بزنیم",
                    {
                      position: "bottom-right",
                      closeOnClick: true,
                    }
                  );
                } else {
                  if (!!shiftsForTaskChoose.find((b) => b == e.target.value)) {
                    toast.error("روز  تکراری است", {
                      position: "bottom-right",
                      closeOnClick: true,
                    });
                  } else {
                    CTX.setShiftsForTaskChoose((current) => [
                      ...current,
                      e.target.value,
                    ]);
                  }
                }
              }}
              style="text-right"
              validatorData={validator.current.message(
                "shifts",
                shiftsForTaskChoose,
                ["required", { min: 1 }]
              )}
              select={true}
              selectData={shiftsSelectData}
              defaultValue={"انتخاب کنید"}
            />
          </div>

          <div className="flex flex-wrap  rtl">
            {shiftsForTaskChoose &&
              shiftsForTaskChoose.map((e, index) => (
                <div
                  className="flex bg-gray-300 p-1 rounded-full m-1 justify-start mt-3"
                  key={index}
                >
                  <div
                    className="w-[30px] h-[30px] rounded-full bg-gray-400 "
                    onClick={() => deleteShiftForTask(e)}
                  ></div>

                  <div>
                    <p className="mb-0 px-3 text-sm mt-1">
                      {shiftsData?.find((b) => b?.id == e)?.title}
                    </p>
                  </div>
                </div>
              ))}
          </div>

          {/* ===========scheduleType=============== */}

          <div className="">
            <Input
              lable="تکرار پذیری فعالیت"
              id="scheduleType-id"
              name="scheduleType"
              type={"text"}
              value={scheduleType}
              inputEvent={(e) => {
                setScheduleType(parseInt(e.target.value));
                validator.current.showMessageFor("scheduleType");
              }}
              style="text-right"
              validator={true}
              validatorData={validator.current.message(
                "scheduleType",
                scheduleType,
                ["required"]
              )}
              select={true}
              selectData={[
                { key: "هفتگی", value: 1 },
                { key: "روزانه", value: 0 },
                { key: "مخصوص یک روز ", value: 2 },
              ]}
              defaultValue={"انتخاب کنید"}
            />
          </div>

          {/* <div className="flex flex-wrap mt-3 rtl">
            <div className="flex bg-gray-300 p-1 rounded-full m-1 justify-start">
              <div>
                <p className="mb-0 px-3 text-sm mt-1">
                  {schedule?.find((b) => b.value == scheduleType)?.key}
                </p>
              </div>
            </div>
          </div> */}

          {/* ===========scheduleType setFor=============== */}

          {scheduleType == 2 && (
            <DatePickerIran
              title="تاریخ مورد نظر فعالیت"
              name="birthDateTimeStamp"
              datePickerEvent={(e) => {
                setBirthDateTimeStamp(e);
                validator.current.showMessageFor("birthDateTimeStamp");
              }}
              date={birthDateTimeStamp}
              zindex="z-[101]"
              validator={true}
              validatorData={validator.current.message(
                "birthDateTimeStamp",
                birthDateTimeStamp,
                ["required"]
              )}
            />
          )}
        </div>
        {/* ===========shiftsDaysTask=============== */}
        {scheduleType == 1 && (
          <>
            <div className="">
              <Input
                lable="انتخاب روزهای این قعالیت در هفته"
                id="shiftsDaysChoose-id"
                name="shiftsDaysChoose"
                type={"text"}
                value={shiftsDaysChoose}
                inputEvent={(e) => {
                  setShiftsDaysCurrent(e.target.value);
                  validator.current.showMessageFor("shiftsDaysChoose");

                  if (!!shiftsDaysChoose.find((b) => b == e.target.value)) {
                    toast.error("روز  تکراری است", {
                      position: "bottom-right",
                      closeOnClick: true,
                    });
                  } else {
                    CTX.setShiftsDaysChoose((current) => [
                      ...current,
                      parseInt(e.target.value),
                    ]);
                  }
                }}
                validator={true}
                validatorData={validator.current.message(
                  "shiftsDaysChoose",
                  shiftsDaysChoose,
                  ["required", { min: 1 }]
                )}
                style="text-right"
                select={true}
                selectData={shiftsDaysSelectData}
                defaultValue={"انتخاب کنید"}
              />
            </div>

            <div className="flex flex-wrap mt-3 rtl">
              {shiftsDaysChoose &&
                shiftsDaysChoose.map((e, index) => (
                  <div
                    className="flex bg-gray-300 p-1 rounded-full m-1 justify-start"
                    key={index}
                  >
                    <div
                      className="w-[30px] h-[30px] rounded-full bg-gray-400 "
                      onClick={() => deleteShiftsDaysForTask(e)}
                    ></div>

                    <div>
                      <p className="mb-0 px-3 text-sm mt-1">
                        {week?.find((b) => b.value == e).key}
                      </p>
                    </div>
                  </div>
                ))}
            </div>
          </>
        )}
        {goToEditTask ? (
          <Buttonbriz
            title="ویرایش فعالبت"
            color="INFO"
            icon="CHECK"
            buttonEvent={() => handleCreateTask("UPDATE")}
            subButton={true}
            subButtonTitle="حذف فعالیت"
            subButtonEvent={() => CTX.DeleteTask(idEditTask)}
          />
        ) : (
          <Buttonbriz
            title="ثبت فعالیت"
            color="PRIMARY"
            icon="CHECK"
            buttonEvent={() => handleCreateTask()}
          />
        )}{" "}
      </div>
    </div>
  );
};

export default AddTask;
