"use client";
import AppHeader from "@comp/AppHeader/page";
import ActivityCard from "@comp/TaskPage/ActivityCard/page";
import ActivityCardCloseShift from "@comp/TaskPage/ActivityCardCloseShift/page";
import AppContext from "@ctx/AppContext";
import moment from "jalali-moment";
import { useParams, useSearchParams } from "next/navigation";
import Buttonbriz from "plugins/Buttonbriz/page";
import GoBack from "plugins/GoBack/page";
import PersianNumber from "plugins/PersianNumber";
import Slider from "rc-slider";
import React, { useCallback, useContext, useEffect, useState } from "react";
import InfiniteScroll from "react-infinite-scroll-component";
import { toast } from "react-toastify";

const CompleteShift = () => {
  const CTX = useContext(AppContext);
  const searchParams = useSearchParams();
  const day = searchParams.get("day");

  const [closeShiftScore, setCloseShiftScore] = useState(50);
  const [activeShifPlan, setActiveShifPlan] = useState(-1);
  const [selectDayForShift, setSelectDayForShift] = useState(-1);

  const currentDate = new Date();

  const siftsData = CTX.state.shiftsData;
  const activitiesData = CTX.state.activitiesData;
  const stopGetActivities = CTX.state.stopGetActivities;
  const pageGetActivity = CTX.state.pageGetActivity;

  const circularHandleStyle = {
    backgroundColor: "green",
    border: "2px solid #ffffff",
    boxShadow: "0 0 5px #333",
    cursor: "pointer",
    height: 30, // Adjust the height in pixels
    width: 30, // Adjust the width to maintain a circular shape
    marginTop: -10, // Adjust the margin to center the handle
    borderRadius: "50%", // Make the handle circular
  };

  const railStyle = {
    backgroundColor: "rgba(255, 0, 37, 0.54)", // Overall track color
    height: 10,
  };

  const trackStyle = {
    backgroundColor: "rgba(0, 165, 0, 0.7)", // Color between handles
    height: 10,
  };

  const body = {
    completeDescription: "",
    completeActivities: CTX.state.completeActivities,
    completePercent: closeShiftScore,
  };

  const getTodayPersianDate = () => {
    return moment().locale("fa").format("D MMMM YYYY");
  };

  const getYesterdayPersianDate = () => {
    const yesterday = moment().locale("fa").subtract(1, "day");
    return yesterday.format("D MMMM YYYY");
  };

  const getTomorrowPersianDate = () => {
    const tomorrow = moment().locale("fa").add(1, "day");
    return tomorrow.format("D MMMM YYYY");
  };

  const handleOpenShift = (isCompleted, id, index, hasCurrentShiftPlan) => {
    CTX.setStopGetActivities(false);
    CTX.setPageGetActivity(0);
    if (isCompleted) {
      toast.warning(`شیفت بسته شده است `, {
        position: "bottom-right",
        closeOnClick: true,
      });
    } else if (!hasCurrentShiftPlan) {
      toast.warning(`شیفت نا مشخص است `, {
        position: "bottom-right",
        closeOnClick: true,
      });
    } else {
      handleActivityCloseShift(id, index);
    }
  };
  const handleActivityCloseShift = (id, index) => {
    CTX.setCompleteActivities([]);
    setCloseShiftScore(50);
    if (activeShifPlan == index) {
      setActiveShifPlan(-1);
    } else {
      setActiveShifPlan(index);

      if (selectDayForShift == 0) {
        CTX.GetActivity(
          moment().locale("fa").subtract(1, "day").unix() * 1000,
          siftsData[index].currentShiftPlanId,
          0
        );
      } else if (selectDayForShift == 1) {
        CTX.GetActivity(
          moment().locale("fa").startOf("day").unix() * 1000,
          siftsData[index].currentShiftPlanId,
          0
        );
      } else if (selectDayForShift == 2) {
        CTX.GetActivity(
          moment().locale("fa").add(1, "day").unix() * 1000,
          siftsData[index].currentShiftPlanId,
          0
        );
      }
    }
  };

  const handleDayCloseShift = (index) => {
    setSelectDayForShift(index);
    setActiveShifPlan(-1);

    if (index == 0) {
      CTX.GetShifts(moment().locale("fa").subtract(1, "day").unix() * 1000);
    } else if (index == 1) {
      CTX.GetShifts(moment().locale("fa").startOf("day").unix() * 1000);
    } else if (index == 2) {
      CTX.GetShifts(moment().locale("fa").add(1, "day").unix() * 1000);
    }
  };

  const handleCloseShift = useCallback(
    () => {
      CTX.CloseShift(body, siftsData[activeShifPlan]?.currentShiftPlanId);
      setActiveShifPlan(-1);
      handleDayCloseShift(1);
      CTX.GetShifts(moment().locale("fa").startOf("day").unix() * 1000);
    },
    [siftsData[activeShifPlan]?.currentShiftPlanId],
    body
  );

  const handleGoToReport = (title, shiftId) => {
    CTX.setReportDetail({
      title: title,
      shiftId: shiftId,
      typeReport: "SHIFTPLAN",
    });
    CTX.setBottomSheetReportOpen(true);
  };

  useEffect(() => {
    if (day == "tomorrow") {
      handleDayCloseShift(2);
    } else if (day == "yesterday") {
      handleDayCloseShift(0);
    } else {
      handleDayCloseShift(1);
    }
  }, []);

  useEffect(() => {
    if (activitiesData.length > 0) {
      CTX.setCompleteActivities(
        activitiesData.map((activity) => ({
          activityId: activity?.id,
          isCompleted: activity?.isDone,
          performanceDescription: activity?.performanceDescription,
        }))
      );
    }
  }, [activitiesData]);

  const handleInfiniteNextFetchActivity = () => {
    CTX.setPageGetActivity((e) => e + 1);

    if (selectDayForShift == 0) {
      CTX.GetActivity(
        moment().locale("fa").subtract(1, "day")?.unix() * 1000,
        siftsData[activeShifPlan].currentShiftPlanId,
        pageGetActivity + 1
      );
    } else if (selectDayForShift == 1) {
      CTX.GetActivity(
        moment().locale("fa").startOf("day").unix() * 1000,
        siftsData[activeShifPlan].currentShiftPlanId,
        pageGetActivity + 1
      );
    } else if (selectDayForShift == 2) {
      CTX.GetActivity(
        moment().locale("fa").add(1, "day").unix() * 1000,
        siftsData[activeShifPlan].currentShiftPlanId,
        pageGetActivity + 1
      );
    }
  };

  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="flex overflow-auto whitespace-nowrap mb-7 mt-4">
          <div
            className={` shadow-sm relative block  max-w-max ml-2  rounded-full mt-2 px-4 py-1 tr03 border-2 ${
              selectDayForShift == 0
                ? " bg-primary-200 border-secondary-300"
                : "opacity-50 border-secondary-400"
            }`}
            onClick={() => handleDayCloseShift(0)}
          >
            <PersianNumber number={getYesterdayPersianDate()} />
          </div>
          <div
            className={` shadow-sm relative block  max-w-max ml-2  rounded-full mt-2 px-4 py-1 tr03 border-2 ${
              selectDayForShift == 1
                ? " bg-primary-200 border-secondary-300"
                : "opacity-50 border-secondary-400"
            }`}
            onClick={() => handleDayCloseShift(1)}
          >
            <p className="mb-0">
              <PersianNumber number={getTodayPersianDate()} />
              <small className="text-sm mx-2"> ( امروز )</small>
            </p>
          </div>

          <div
            className={` shadow-sm relative block  max-w-max ml-2  rounded-full mt-2 px-4 py-1 tr03 border-2 ${
              selectDayForShift == 2
                ? " bg-primary-200 border-secondary-300"
                : "opacity-50 border-secondary-400"
            }`}
            onClick={() => handleDayCloseShift(2)}
          >
            <PersianNumber number={getTomorrowPersianDate()} />
          </div>
        </div>

        {siftsData?.map((e, index) => (
          <div className="mt-3">
            <div
              className={`bg-gray-50 p-2 rounded-xl flex  justify-between ${
                activeShifPlan == index ? "bg-gray-300 " : "bg-gray-200 "
              }  `}
            >
              <div
                className="flex w-full justify-between"
                onClick={() =>
                  handleOpenShift(
                    e?.isCompleted,
                    e?.id,
                    index,
                    e?.hasCurrentShiftPlan
                  )
                }
              >
                <p className="mb-0 font-medium text-sm mt-1 pr-2">
                  {e?.title}{" "}
                  <small className="text-red-900">
                    ({e?.currentSupervisorFullName})
                  </small>{" "}
                </p>
                <div className="flex">
                  <div
                    className={`bg-gray-400 rounded-full mr-1 ${
                      e?.isCompleted
                        ? "w-[30px] h-[30px] text-center pt-[2px]"
                        : ""
                    }`}
                  >
                    <p className="mb-0 text-[12px] p-1 text-white ">
                      {" "}
                      <PersianNumber
                        number={e?.totalActivitiesCount}
                        style="mx-1 !text-[12px]"
                      />
                    </p>
                  </div>

                  {e?.undoneActivitiesCount != 0 && (
                    <div className="bg-red-700 w-[30px] h-[30px] rounded-full mr-1">
                      <p className="mb-0 text-[12px] p-1 text-white text-center mt-[2px]">
                        {" "}
                        <PersianNumber
                          number={e?.undoneActivitiesCount}
                          style="mx-1 !text-[12px]"
                        />
                      </p>
                    </div>
                  )}
                </div>
              </div>

              <div className={` ${e?.isCompleted ? "" : ""}`}>
                {e?.isCompleted && (
                  <div
                    className="bg-sky-600 w-fit px-2 h-[30px]  rounded-full mr-1 !z-50 relative"
                    onClick={() =>
                      handleGoToReport(e.title, e.currentShiftPlanId)
                    }
                  >
                    <p className="mb-0 text-[12px] p-1 text-white text-center mt-[2px]">
                      {" "}
                      گزارش{" "}
                    </p>
                  </div>
                )}
              </div>
            </div>
            {activeShifPlan == index && (
              <>
                <InfiniteScroll
                  dataLength={siftsData[activeShifPlan]?.totalActivitiesCount}
                  next={handleInfiniteNextFetchActivity}
                  hasMore={!stopGetActivities}
                >
                  {activitiesData?.map((e) => (
                    <ActivityCardCloseShift data={e} />
                  ))}
                </InfiniteScroll>

                <div className=" mt-5">
                  <div className=" p-3 relative top-[20px] ">
                    <Slider
                      min={0}
                      max={100}
                      defaultValue={[50]}
                      step={10}
                      handleStyle={[circularHandleStyle, circularHandleStyle]}
                      railStyle={railStyle}
                      trackStyle={[trackStyle, trackStyle]}
                      onChange={(e) => setCloseShiftScore(e)}
                    />
                  </div>

                  <Buttonbriz
                    title={` بستن شیفت با امتیاز  ${closeShiftScore}`}
                    color="PRIMARY"
                    icon="CHECK"
                    buttonEvent={() => handleCloseShift()}
                  />
                </div>
              </>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

export default CompleteShift;
