"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 Buttonbriz from "plugins/Buttonbriz/page";
import PersianNumber from "plugins/PersianNumber";
import Slider from "rc-slider";
import React, { useContext, useEffect, useState } from "react";
import { toast } from "react-toastify";

const CompleteShift = () => {
  const CTX = useContext(AppContext);

  const [closeShiftScore, setCloseShiftScore] = useState(70);
  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 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
    marginLeft: -15, // Adjust the margin to center the handle
    marginTop: -10, // Adjust the margin to center the handle
    borderRadius: "50%", // Make the handle circular
  };

  const railStyle = {
    backgroundColor: "red", // Overall track color
    height: 10,
  };

  const trackStyle = {
    backgroundColor: "green", // 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) => {
    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(70);
    if (activeShifPlan == index) {
      setActiveShifPlan(-1);
    } else {
      setActiveShifPlan(index);

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

  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 = () => {
    CTX.CloseShift(body, siftsData[activeShifPlan]?.currentShiftPlanId);

    // ;
    // ;
    // ;
    // ;
  };

  useEffect(() => {
    handleDayCloseShift(1);
  }, []);

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

  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 className="flex overflow-auto whitespace-nowrap">
          <div
            className={`mx-1 rtl py-1 px-2 rounded-full font-bold inline-block tr03 ${
              selectDayForShift == 0
                ? "bg-primary-200 text-white"
                : " opacity-60 font-normal"
            }`}
            onClick={() => handleDayCloseShift(0)}
          >
            <PersianNumber number={getYesterdayPersianDate()} />
          </div>
          <div
            className={`mx-1 rtl py-1 px-2 rounded-full font-bold inline-block tr03 ${
              selectDayForShift == 1
                ? "bg-primary-200 text-white"
                : " opacity-60 font-normal"
            }`}
            onClick={() => handleDayCloseShift(1)}
          >
            <p className="mb-0">
              <PersianNumber number={getTodayPersianDate()} />
              <small className="text-sm mx-2"> ( امروز )</small>
            </p>
          </div>

          <div
            className={`mx-1 rtl py-1 px-2 rounded-full font-bold inline-block tr03 ${
              selectDayForShift == 2
                ? "bg-primary-200 text-white"
                : " opacity-60 font-normal"
            }`}
            onClick={() => handleDayCloseShift(2)}
          >
            <PersianNumber number={getTomorrowPersianDate()} />
          </div>
        </div>

        {siftsData?.map((e, index) => (
          <div className="mt-3">
            <div
              className={`bg-gray-200 p-2 rounded-full flex  justify-between ${
                activeShifPlan == index ? "bg-gray-300 " : "bg-gray-200 "
              }  `}
              onClick={() =>
                handleOpenShift(
                  e?.isCompleted,
                  e?.id,
                  index,
                  e?.hasCurrentShiftPlan
                )
              }
            >
              <p className="mb-0">{e?.title} </p>

              <div className="flex">
                <div className="bg-gray-400   rounded-full mr-1">
                  <p className="mb-0 text-sm p-1 text-white ">
                    {" "}
                    <PersianNumber
                      number={e?.totalActivitiesCount}
                      style="mx-1 text-base"
                    />
                    فعالیت
                  </p>
                </div>

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

                {e?.isCompleted && (
                  <div className="bg-yellow-500 w-fit px-2 h-[30px]   rounded-full mr-1">
                    <p className="mb-0 text-sm p-1 text-white text-center mt-[2px]">
                      {" "}
                      بسته شده
                    </p>
                  </div>
                )}
              </div>
            </div>
            {activeShifPlan == index && (
              <>
                {activitiesData?.map((e) => (
                  <ActivityCardCloseShift data={e} />
                ))}

                <div className=" mt-5">
                  <div className=" p-3 relative top-[20px] ">
                    <Slider
                      min={0}
                      max={100}
                      defaultValue={[70]}
                      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;
