"use client";

import React, { useContext, useEffect, useRef, useState } from "react";
import { BottomSheet } from "react-spring-bottom-sheet";
import Input from "plugins/Input/page";
import AppContext from "@ctx/AppContext";
import SimpleReactValidator from "simple-react-validator";
import { toast } from "react-toastify";
import Buttonbriz from "plugins/Buttonbriz/page";
import { useRouter } from "next/navigation";
import DatePickerIran from "plugins/DatePickerIran/page";
import moment from "jalali-moment";
import Chapar from "plugins/Chapar";

const BottomSheetCreateTask = (props) => {
  const CTX = useContext(AppContext);

  const router = useRouter();

  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 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 CreateTask = async (body) => {
    CTX.setLoading(true);
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/task`,
        JSON.stringify(body),
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`فعالیت ساخته شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      clear();
      CTX.setBottomSheetCreateTaskOpen(false);
      CTX.setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      CTX.setLoading(false);
    }
  };

  const UpdateTask = async (body) => {
    CTX.setLoading(true);
    try {
      const data = await Chapar.put(
        `${process.env.NEXT_PUBLIC_API_URL}/task`,
        body,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`فعالیت ویرایش شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });

      // router->

      CTX.setLoading(false);

      CTX.setStopGetTasks(false);
      CTX.setPageGetTasks(0);
      CTX.setBottomSheetCreateTaskOpen(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };

  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") {
        UpdateTask(bodyUpdate);
      } else {
        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));
  };

  const handleBottomSheetCreateTaskOpen = (e) => {
    if (e.type == "OPEN") {
      CTX.GetRoutines();
      CTX.GetPositions();
    } else if (e.type == "CLOSE") {
      clear();
    }
  };

  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 (
    <BottomSheet
      onSpringStart={(e) => handleBottomSheetCreateTaskOpen(e)}
      open={CTX.state.BottomSheetCreateTaskOpen}
      onDismiss={() => CTX.setBottomSheetCreateTaskOpen(false)}
      blocking={true}
    >
      <div className="text-center py-2 bg-secondary-950  ">
        <p className="mb-0 text-primary-300 relative top-[-5px]">
          افزودن تسک جدید{" "}
        </p>
      </div>
      <div className="bg-white overflow-hidden p-5 rtl">
        <div>
          <div className="">
            <Input
              lable="عنوان فعالیت"
              theme={1}
              mt={6}
              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=" توضیحات"
              theme={1}
              mt={6}
              id="description-id"
              name="description"
              type={"text"}
              value={description}
              inputEvent={(e) => {
                setDescription(e.target.value);
              }}
              textarea={true}
              style="text-right"
            />
          </div>
          {/* ===========routine=============== */}

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

                if (!!routineForTaskChoose.find((b) => b == e.target.value)) {
                  toast.error("روز  تکراری است", {
                    position: "bottom-right",
                    closeOnClick: true,
                  });
                } else {
                  CTX.setRoutineForTaskChoose(() => [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">
                      {routinesData?.find((b) => b.id == e)?.name}
                    </p>
                  </div>
                </div>
              ))}
          </div>
          {/* ===========position=============== */}

          <div className="">
            <Input
              lable="پوزیشن فعالیت"
              theme={1}
              mt={6}
              id="positions-id"
              name="positions"
              value={setPositionsForTaskCurrent}
              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-[20px] h-[20px] rounded-full bg-gray-400 "
                    onClick={() => deletePositionForTask(e)}
                  ></div>

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

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

                if (!!shiftsForTaskChoose.find((b) => b == e.target.value)) {
                  toast.error("روز  تکراری است", {
                    position: "bottom-right",
                    closeOnClick: true,
                  });
                } else {
                  CTX.setShiftsForTaskChoose(() => [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-[20px] h-[20px] rounded-full bg-gray-400 "
                    onClick={() => deleteShiftForTask(e)}
                  ></div> */}

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

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

          <div className="">
            <Input
              lable="تکرار پذیری فعالیت"
              id="scheduleType-id"
              theme={1}
              mt={6}
              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="انتخاب روزهای این فعالیت در هفته"
                theme={1}
                mt={6}
                id="shiftsDaysChoose-id"
                name="shiftsDaysChoose"
                type={"text"}
                value={setShiftsDaysCurrent}
                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-[20px] h-[20px] rounded-full bg-gray-400 "
                      onClick={() => deleteShiftsDaysForTask(e)}
                    ></div>

                    <div>
                      <p className="mb-0 px-3 text-sm ">
                        {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>
    </BottomSheet>
  );
};

export default BottomSheetCreateTask;
