"use client";

import React, { useContext, useEffect, useState } from "react";
import moment from "jalali-moment";
import "moment/locale/fa"; // Set the locale to Farsi (Persian)
import AppHeader from "@comp/AppHeader/page";
import { Swiper, SwiperSlide } from "swiper/react";
import PersianNumber from "plugins/PersianNumber";
import { PersianD, PersianDay, PersianM, holidays } from "datacalender";
import AppContext from "@ctx/AppContext";
import Input from "plugins/Input/page";
import { toast } from "react-toastify";
import Avatar from "boring-avatars";
import BottomManageShift from "plugins/BottomSheet/BottomManageShift";
import BottomSheetAddUserToPositionShiftPlan from "plugins/BottomSheet/BottomSheetAddUserToPositionShiftPlan";
import Buttonbriz from "plugins/Buttonbriz/page";
import GoBack from "plugins/GoBack/page";
import Chapar from "plugins/Chapar";

const Calendar = () => {
  const CTX = useContext(AppContext);
  const searchUserChoose = CTX.state.searchUserChoose;
  const usersData = CTX.state.usersData;
  const routinesData = CTX.state.routinesData;
  const positionsData = CTX.state.positionsData;
  const shiftPlanData = CTX.state.shiftPlanData;
  const shiftplansData = CTX.state.shiftPlansData;

  const [daysUntilWeek, setDaysUntilWeek] = useState([]);
  const [selectDay, setSelectDay] = useState(null);
  const [selectShift, setselectShift] = useState(-1);
  const [selectRoutine, setSelectRoutine] = useState(-1);
  const [shiftsCurrentDaysData, setShiftsCurrentDaysData] = useState([]);
  const [daysManageShiftData, setDaysManageShiftData] = useState([]);

  const [editManageShift, setEditManageShift] = useState(false);
  const [superId, setSuperId] = useState(null);
  const [superData, setSuperData] = useState(false);
  const [shiftPlanSteps, setShiftPlanSteps] = useState(0);

  const [positionSelectNameBottomSheet, setPositionSelectNameBottomSheet] =
    useState([]);
  const [positionSelectIdBottomSheet, setPositionSelectIdBottomSheet] =
    useState([]);
  const [userAndPositionIds, setUserAndPositionIds] = useState([]);
  const [idRoutineShiftPlan, setIdRoutineShiftPlan] = useState(null);
  const [currentShiftPlanId, setCurrentShiftPlanId] = useState(null);

  const transformData = (responseArray) => {
    // console.log("responseArray", responseArray);

    const daysArray = [];
    return responseArray.map((item) => {
      const date = moment(item.dateTime).locale("fa");
      const isToday = date.isSame(moment(), "day");

      daysArray.push({
        checkDay: date.format("jYYYY/jM/jD"),
        date: date.format("jD / jM"),
        dayOfWeek: date.format("dddd"),
        isToday: isToday,
        totalShiftPercent: (item.totalShiftPlans / item.totalShifts) * 100,
      });

      return setDaysUntilWeek(daysArray);
    });
  };

  // Existing GetListDaysWithShiftByRoutine function
  const GetListDaysWithShiftByRoutine = async (id) => {
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/page/app/shifting?routineId=${id}`,
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );

      setDaysManageShiftData(data);
      transformData(data);

      if (data && data.length > 0) {
        // Find the first shift that is not completed
        for (let i = 0; i < data.length; i++) {
          const shifts = data[i].shifts;
          for (let j = 0; j < shifts.length; j++) {
            if (!shifts[j].hasCurrentShiftPlan) {
              setSelectDay(i);
              setShiftPlanSteps(2);
              setShiftsCurrentDaysData(data[i]?.shifts);
              handleSelectShift(j);
              setShiftPlanSteps(3);
              return;
            }
          }
        }
      }

      return data; // Ensure this returns the data for further processing
    } catch (error) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      CTX.setLoading(false);
      return []; // Return an empty array in case of an error
    }
  };

  const body = {
    planDate:
      daysUntilWeek[selectDay]?.checkDay &&
      moment.utc(daysUntilWeek[selectDay].checkDay, "jYYYY-jMM-jDDTHH").unix() *
        1000,
    shiftId: shiftsCurrentDaysData && shiftsCurrentDaysData[selectShift]?.id,
    routineId: routinesData && routinesData[selectRoutine]?.id,
    supervisionUserId: superId,
    userAndPositionIds,
  };

  const bodyUpdate = {
    planDate:
      daysUntilWeek[selectDay]?.checkDay &&
      moment.utc(daysUntilWeek[selectDay].checkDay, "jYYYY-jMM-jDDTHH").unix() *
        1000,
    shiftId: shiftsCurrentDaysData && shiftsCurrentDaysData[selectShift]?.id,
    routineId: routinesData && routinesData[selectRoutine]?.id,
    userAndPositionIds,
    supervisionUserId: superId,
    id: currentShiftPlanId,
  };

  const handleRoutineShiftPlan = (index, id) => {
    setSelectRoutine(index);
    setShiftPlanSteps(1);
    setIdRoutineShiftPlan(id);
    GetListDaysWithShiftByRoutine(id);
  };

  const handleRoutineShiftPlanWithDay = (index) => {
    setSelectDay(index);
    setShiftPlanSteps(2);
    setShiftsCurrentDaysData(daysManageShiftData[index]?.shifts);
    setselectShift(-1);

    // CTX.GetRoutineShiftPlan(
    //   idRoutineShiftPlan,
    //   moment(daysUntilWeek[index]?.checkDay, "jYYYY-jM-jD").unix() * 1000
    // );
  };

  const handleSelectShift = (index) => {
    // console.log("usersData.length", usersData.length);
    setselectShift(index);
    setShiftPlanSteps(3);
    if (usersData.length <= 0) {
      // User data is not in state, send request to get user
      CTX.GetUsers();
    }

    if (positionsData.length <= 0) {
      CTX.GetPositions();
    }
  };

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

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

      CTX.setShiftPlanData(id);

      setSelectDay(null);
      setSuperId(null);
      setUserAndPositionIds([]);
      setShiftPlanSteps(1);
      GetListDaysWithShiftByRoutine(idRoutineShiftPlan);

      CTX.setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}dsdsdsds`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      CTX.setLoading(false);
    }
  };
  const CreateShiftPlan = async (body) => {
    CTX.setLoading(true);
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/shift/plan`,
        JSON.stringify(body),
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`مدیریت شیفت ساخته شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setSelectDay(null);
      setSuperId(null);
      setUserAndPositionIds([]);
      setShiftPlanSteps(1);
      CTX.setLoading(false);
      GetListDaysWithShiftByRoutine(idRoutineShiftPlan);

      // router.push("/shifts");
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      CTX.setLoading(false);
    }
  };

  // const updateDaysAndShifts = async () => {
  //   const currentShiftId = shiftsCurrentDaysData[selectShift]?.id;
  //   const filteredShifts = shiftsCurrentDaysData.filter(
  //     (shift) => shift.id !== currentShiftId
  //   );
  //   const allCompleted = filteredShifts.every((shift) => shift.isCompleted);

  //   if (allCompleted && selectDay <= daysManageShiftData?.length - 1) {
  //     setSelectDay(selectDay + 1);
  //     setSuperId(null);
  //     setUserAndPositionIds([]);
  //     setShiftPlanSteps(2);
  //     setselectShift(-1);
  //     CTX.setLoading(false);
  //   }
  // };

  const handleCreateShiftPlan = (update) => {
    if (update == "UPDATE") {
      UpdateShiftPlan(bodyUpdate);
    } else {
      CreateShiftPlan(body);
    }
  };

  const handleDeleteUser = (id) => {
    const updatedUsers = userAndPositionIds.filter((user) => user.key !== id);
    setUserAndPositionIds(updatedUsers);
  };

  useEffect(() => {
    CTX.GetRoutines();
    setSelectDay(-1);
  }, []);

  useEffect(() => {
    // console.log("11111", shiftsPlan && shiftsPlan[selectShift]);
    setEditManageShift(false);
    CTX.setShiftPlanData(null);
    if (
      shiftsCurrentDaysData &&
      shiftsCurrentDaysData[selectShift]?.hasCurrentShiftPlan
    ) {
      setEditManageShift(true);
      setCurrentShiftPlanId(
        shiftsCurrentDaysData[selectShift]?.currentShiftPlanId
      );
      CTX.GetShiftPlan(shiftsCurrentDaysData[selectShift]?.currentShiftPlanId);
    }
  }, [selectShift]);

  useEffect(() => {
    setUserAndPositionIds(
      shiftPlanData?.users?.map((e) => ({
        key: e.positionId,
        value: e.userId,
      }))
    );

    setSuperId(shiftPlanData?.supervisorId);
  }, [shiftPlanData]);

  useEffect(() => {
    const userJustSuper = usersData?.filter(
      (obj) =>
        obj.roleNames.includes("سوپروایزر") || obj.roleNames.includes("مدیریت")
    );
    setSuperData(
      userJustSuper?.map((item) => ({
        key: item.firstName + " " + item.lastName,
        value: item.userId,
      }))
    );
  }, [usersData]);

  // console.log(
  //   "hiftsCurrentDaysData[selectShift]",
  //   shiftsCurrentDaysData[selectShift]
  // );
  return (
    <div className="pb-20">
      <AppHeader
        title=" شیفت بندی های هفتگی"
        sub={`شیفت بندی`}
        icon2={true}
        iconName2="ARROW"
        iconHref2="#"
        iconEvent2={() => {
          GoBack();
        }}
      />

      <div className="bg-white overflow-hidden px-5 rtl">
        <div className="font-medium text-right mt-5">
          <p className="mb-0 text-sm">روتین را انتخاب کنید:</p>
        </div>
        <div
          className="flex overflow-auto whitespace-nowrap "
          id="swich-shifts"
        >
          {routinesData?.map((e, index) => (
            <div
              className={` shadow-sm relative block  max-w-max ml-2  rounded-full mt-2 px-4 py-1 tr03 border-2 ${
                selectRoutine == index
                  ? " bg-primary-200 border-secondary-300"
                  : "opacity-50 border-secondary-400"
              }`}
              onClick={() => {
                if (shiftPlanSteps >= 1) {
                  toast.error("برای تغییر روتین باید رفرش کنید", {
                    position: "bottom-right",
                    autoClose: 2000,
                    hideProgressBar: false,
                    closeOnClick: true,
                    pauseOnHover: true,
                    draggable: true,
                    progress: undefined,
                  });
                } else {
                  handleRoutineShiftPlan(index, e.id);
                }
              }}
            >
              <p className="mb-0 text-sm">{e.name}</p>
            </div>
          ))}
        </div>
      </div>

      {shiftPlanSteps >= 1 && (
        <div className="  overflow-hidden px-5 rtl mt-5  ">
          <>
            <div className="font-medium text-right  ">
              <p className="mb-0 text-sm">تاریخ را انتخاب کنید:</p>
            </div>
            <Swiper
              spaceBetween={10}
              slidesPerView={4.3}
              // onSlideChange={() => }
              // onSwiper={(swiper) => }
            >
              {daysUntilWeek?.map((e, index) => (
                <SwiperSlide>
                  <div
                    className={`h-[85px] tr03 border-2 rounded-xl  mt-4 ${
                      selectDay == index
                        ? " bg-primary-200 border-secondary-300"
                        : "opacity-70 border-secondary-400"
                    }`}
                    key={index}
                    onClick={() => {
                      if (shiftPlanSteps >= 1) {
                        handleRoutineShiftPlanWithDay(index);
                      } else {
                        toast.error(`ابتدا روتین را انتخاب کنید`, {
                          position: "bottom-right",
                          closeOnClick: true,
                        });
                      }
                    }}
                  >
                    <div className="pt-3">
                      <p className="mb-0 text-center ">
                        <PersianNumber
                          number={e.date}
                          style={`text-[20px] ${
                            selectDay == index
                              ? "font-bold"
                              : !!holidays.y1402?.find(
                                  (b) => b.date == e.checkDay
                                )
                              ? "text-red-500"
                              : ""
                          } `}
                        />
                      </p>
                    </div>

                    <div
                      className={`w-fit mx-auto  sahdow  px-1 rounded-full ${
                        selectDay == index
                          ? " text-secondary-800"
                          : " text-gray-600"
                      }`}
                    >
                      <p className="mb-0 text-center text-sm  ">
                        {/* {PersianD.find((i) => i == e.dayOfWeek)} */}
                        {e.dayOfWeek}
                      </p>
                    </div>

                    <div className={`mt-5 relative w-8/12 mx-auto `}>
                      <div className="absolute w-full  mt-[-10px]">
                        <div className="bg-secondary-400 p-1 rounded-full "></div>
                      </div>

                      <div
                        className={`absolute ${
                          e.totalShiftPercent === 0
                            ? "w-0"
                            : e.totalShiftPercent > 0 &&
                              e.totalShiftPercent < 50
                            ? "w-5/12"
                            : e.totalShiftPercent === 50
                            ? "w-1/2"
                            : e.totalShiftPercent > 50 &&
                              e.totalShiftPercent < 100
                            ? "w-9/12"
                            : e.totalShiftPercent === 100
                            ? "w-full"
                            : `w-[${e.totalShiftPercent}%]`
                        } mt-[-10px]`}
                      >
                        <div
                          className={`bg-primary-400 ${
                            e.totalShiftPercent !== 0 ? "p-1" : ""
                          }  rounded-full `}
                        ></div>
                      </div>
                    </div>
                  </div>
                </SwiperSlide>
              ))}
            </Swiper>
          </>
        </div>
      )}

      {shiftPlanSteps > 1 && (
        <>
          <div className=" overflow-hidden px-5 mt-5 rtl">
            <>
              <div className="font-medium text-right ">
                <p className="mb-0 text-sm">شیفت را انتخاب کنید:</p>
              </div>
              {shiftsCurrentDaysData.length > 0 ? (
                <div
                  className="flex overflow-auto whitespace-nowrap"
                  id="swich-shifts"
                >
                  {shiftsCurrentDaysData?.map((e, index) => (
                    <div
                      className={` shadow-sm relative block  max-w-max ml-2  rounded-full mt-2 px-4 py-1 tr03 border-2 ${
                        selectShift == index
                          ? " bg-primary-200 border-secondary-300"
                          : " border-secondary-400"
                      } ${
                        e.hasCurrentShiftPlan
                          ? "!bg-primary-600 text-white !border-secondary-50"
                          : ""
                      }`}
                      onClick={() => {
                        handleSelectShift(index);
                      }}
                    >
                      <p className="mb-0 text-sm">{e?.title}</p>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="flex justify-center ">
                  <div className="bg-gray-300  mt-5 w-fit rounded-full    p-2 !px-4">
                    <p className="mb-0 text-gray-600 text-sm">
                      شما شیفتی دراین روز ندارید
                    </p>
                  </div>
                </div>
              )}
            </>
          </div>
        </>
      )}

      {shiftPlanSteps >= 3 && (
        <div className="  p-4 rtl   sm:h-auto  pb-20">
          <div className=" flex justify-start mb-5">
            <div className="  rounded-xl w-fit mr-0 px-3">
              <p className="mb-0 text-right text-sm rtl opacity-80">
                ویرایش برای{" "}
                <small className=" text-sm font-bold">
                  {shiftsCurrentDaysData[selectShift]?.title}
                </small>{" "}
                تاریخ{" "}
                <small className=" text-sm font-bold  text-primary-500 bg-white px-2 rounded-full">
                  <PersianNumber
                    number={daysUntilWeek && daysUntilWeek[selectDay]?.checkDay}
                  />
                </small>{" "}
                میباشد
              </p>
            </div>
          </div>

          <div className="font-medium text-right  pb-4">
            <p className="mb-0 text-sm">پرسنل را انتخاب کنید:</p>
          </div>

          {positionsData.map((e) => (
            <div className="">
              <div className="flex justify-between  border-b border-gray-200 p-2 ">
                <div className="flex p-2">
                  <div className="">
                    <h4 className="text-sm font-bold mt-[2px]">{e.name} </h4>
                  </div>
                </div>

                <div
                  className="w-[30px] h-[30px] bg-secondary-50 shadow-sm rounded-lg  ml-3 "
                  onClick={() => {
                    setPositionSelectIdBottomSheet(e.id);
                    setPositionSelectNameBottomSheet(e.name);
                    CTX.setBottomSheetAddUserToPositionShiftPlanOpen(true);
                  }}
                >
                  <svg
                    width="15"
                    height="15"
                    viewBox="0 0 16 16"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                    className="mx-auto mt-2 opacity-70"
                  >
                    <path
                      d="M8 1V15M1 8H15"
                      stroke="#2B2B2B"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    />
                  </svg>
                </div>
              </div>

              <div
                className={`flex j flex-wrap mt-2 rtl ${
                  userAndPositionIds?.length > 0 ? "" : "justify-center"
                }`}
              >
                {userAndPositionIds?.length > 0
                  ? userAndPositionIds?.map((item) => (
                      <>
                        {e.id == item.key && (
                          <div
                            className="flex bg-gray-100 p-1 rounded-full m-1 justify-start mb-7 "
                            onClick={() => handleDeleteUser(item.key)}
                          >
                            <div
                              className="w-[30px] h-[30px] rounded-full bg-gray-400 "
                              // onClick={() => deleteSearchUser(e)}
                            >
                              <Avatar
                                size={30}
                                name={
                                  usersData.find(
                                    (b) => b?.userId == item?.value
                                  )?.firstName
                                }
                                variant="beam"
                                colors={["#9d9f88", "#83af96", "#b2de93"]}
                              />
                            </div>

                            <div>
                              <p className="mb-0 px-3 text-sm mt-1">
                                {
                                  usersData.find((b) => b.userId == item?.value)
                                    ?.firstName
                                }
                              </p>
                            </div>
                          </div>
                        )}
                      </>
                    ))
                  : ""}
              </div>
            </div>
          ))}
          <div className="mt-8">
            <div className=" text-right mt-3">
              <p className="mb-0 font-medium font-sm">
                سوپروایزر را انتخاب کنید
              </p>
              <p className="mb-0 text-right text-[11px] text-secondary-700">
                شیفت توسط سوپروایزر بسته میشود لطفا برای هر شیفت آن را مشخص کنید
              </p>
            </div>

            <div className="">
              <Input
                lable="سوپروایزر"
                id="superId-id"
                name="superId"
                type={"text"}
                value={superId}
                inputEvent={(e) => {
                  setSuperId(e.target.value);
                }}
                style="text-right"
                select={true}
                selectData={superData}
                defaultValue={"انتخاب کنید"}
                theme={1}
                mt={5}
              />
            </div>
          </div>

          <div className="mt-5">
            {editManageShift ? (
              <Buttonbriz
                title="ویرایش فعالیت"
                color="INFO"
                icon="CHECK"
                buttonEvent={() => handleCreateShiftPlan("UPDATE")}
              />
            ) : (
              <Buttonbriz
                title="ثبت فعالیت"
                color="PRIMARY"
                icon="CHECK"
                buttonEvent={() => handleCreateShiftPlan()}
              />
            )}
          </div>
        </div>
      )}
      <BottomManageShift />
      <BottomSheetAddUserToPositionShiftPlan
        positionName={positionSelectNameBottomSheet}
        positionId={positionSelectIdBottomSheet}
        userAndPositionIds={userAndPositionIds}
        setUserAndPositionIds={setUserAndPositionIds}
        usersData={usersData}
      />
    </div>
  );
};

export default Calendar;
