"use client";

import AppHeader from "@comp/AppHeader/page";
import AppContext from "@ctx/AppContext";
import Avatar from "boring-avatars";
import moment from "jalali-moment";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import FormatJalaliDate from "plugins/FormatJalaliDate/page";
import HasPermission from "plugins/HasPermission/page";
import NothingFound from "plugins/NothingFound/page";
import PersianNumber from "plugins/PersianNumber";

import React, { useContext, useEffect, useState } from "react";

const Shifts = (props) => {
  const CTX = useContext(AppContext);
  const router = useRouter();
  const permissions = CTX.state.profile?.permissions;

  const [shiftplans, setShiftplans] = useState([]);
  const [shiftPlansSelect, setShiftPlansSelect] = useState(0);
  const [shifilterShifPlaneSelect, setFilterShifPlaneSelect] = useState(0);

  const shiftplansData = CTX.state.shiftPlansData;

  const handleFilterGetShifPlane = (num, index) => {
    setFilterShifPlaneSelect(index);
    CTX.GetShifPlans(0, num);
  };

  const groupObjectsByPlanFor = (responseData) => {
    const groupedData = {};

    // Iterate through the array
    responseData.forEach((obj) => {
      const { planFor } = obj;

      // If the planFor value is not in the groupedData object, create a new array
      if (!groupedData[planFor]) {
        groupedData[planFor] = [obj];
      } else {
        // If the planFor value already exists, push the object into the existing array
        groupedData[planFor].push(obj);
      }
    });

    // Sort the objects within each group by the planFor date
    Object.keys(groupedData).forEach((key) => {
      groupedData[key].sort(
        (a, b) => new Date(a.planFor) - new Date(b.planFor)
      );
    });

    // Convert the groupedData object into an array of objects
    const groupedArray = Object.keys(groupedData).map((key) => ({
      planFor: key,
      data: groupedData[key],
    }));

    // Sort the groupedArray by the planFor date
    groupedArray.sort((a, b) => new Date(a.planFor) - new Date(b.planFor));

    setShiftplans(groupedArray);
  };

  function checkDateStatus(planFor) {
    // Get today's date
    const today = new Date();
    // Get yesterday's date
    const yesterday = new Date(today);
    yesterday.setDate(today.getDate() - 1);
    // Get tomorrow's date
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);

    // Parse the "planFor" date from the API response
    const planForDate = new Date(planFor);

    // Check if the planForDate is today
    const isToday = planForDate.toDateString() === today.toDateString();

    // Check if the planForDate is yesterday
    const isYesterday = planForDate.toDateString() === yesterday.toDateString();

    // Check if the planForDate is tomorrow
    const isTomorrow = planForDate.toDateString() === tomorrow.toDateString();

    return {
      today: isToday,
      yesterday: isYesterday,
      tomorrow: isTomorrow,
    };
  }

  useEffect(() => {
    CTX.GetUnReadNotif();
    CTX.GetShifPlans(0, 12);
    setFilterShifPlaneSelect(1);
  }, []);

  useEffect(() => {
    groupObjectsByPlanFor(shiftplansData);
  }, [shiftplansData]);

  useEffect(() => {
    const indextoday = shiftplans.findIndex(
      (e) => new Date(e.planFor).toDateString() == new Date().toDateString()
    );

    setShiftPlansSelect(indextoday);
  }, [shiftplans]);

  return (
    <>
      <div className="pb-20">
        <AppHeader
          title="شیفتــــ های مجموعه"
          sub="شما 12 نفر شیفت متفاوت دارید"
          // icon1={true}
          // iconName1="PLUS"
          // iconHref1="#"
          // iconEvent1={() => {
          //   CTX.setBottomSheetCreateShiftsOpen(true);
          // }}
        />

        <div className="bg-white overflow-hidden p-5 rtl">
          {HasPermission("ManageShiftPlans", permissions) && (
            <>
              <Link href={"/shifts/manage-shift"}>
                <div className="bg-secondary-950 p-4 rounded-2xl ">
                  <p className="mb-0 text-center text-white text-sm font-medium">
                    شیفت بندی هفته{" "}
                  </p>
                </div>
              </Link>
            </>
          )}
          <div
            className="flex justify-start whitespace-nowrap overflow-auto pb-4 mt-1"
            id="swich-shifts"
          >
            <div
              className={`border-2  px-2 py-1 w-fit rounded-full flex mt-2 tr03 mr-1 ${
                shifilterShifPlaneSelect == 1
                  ? " bg-primary-200 border-secondary-300"
                  : "opacity-50 border-secondary-400"
              }`}
              onClick={() => handleFilterGetShifPlane(12, 1)}
            >
              <div className="mr-1">
                <p className="mb-0 text-[12px] text-secondary-900 font-medium">
                  شیفت های هفته{" "}
                </p>
              </div>
            </div>

            <div
              className={`border-2  px-2 py-1 w-fit rounded-full flex mt-2 tr03 mr-1 ${
                shifilterShifPlaneSelect == 6
                  ? " bg-primary-200 border-secondary-300"
                  : "opacity-50 border-secondary-400"
              }`}
              onClick={() => handleFilterGetShifPlane(22, 6)}
            >
              <div className="mr-1">
                <p className="mb-0 text-[12px] text-secondary-900 font-medium">
                  شیفت های ماه{" "}
                </p>
              </div>
            </div>

            <div
              className={`border-2  px-2 py-1 w-fit rounded-full flex mt-2 tr03 mr-1 ${
                shifilterShifPlaneSelect == 2
                  ? " bg-primary-200 border-secondary-300"
                  : "opacity-50 border-secondary-400"
              }`}
              onClick={() => handleFilterGetShifPlane(11, 2)}
            >
              <div className="mr-1">
                <p className="mb-0 text-[12px] text-secondary-900 font-medium">
                  شیفت های هفته بعد{" "}
                </p>
              </div>
            </div>

            <div
              className={`border-2  px-2 py-1 w-fit rounded-full flex mt-2 tr03 mr-1 ${
                shifilterShifPlaneSelect == 3
                  ? " bg-primary-200 border-secondary-300"
                  : "opacity-50 border-secondary-400"
              }`}
              onClick={() => handleFilterGetShifPlane(10, 3)}
            >
              <div className="mr-1">
                <p className="mb-0 text-[12px] text-secondary-900 font-medium">
                  شیفت های هفته قبل{" "}
                </p>
              </div>
            </div>

            <div
              className={`border-2  px-2 py-1 w-fit rounded-full flex mt-2 tr03 mr-1 ${
                shifilterShifPlaneSelect == 4
                  ? " bg-primary-200 border-secondary-300"
                  : "opacity-50 border-secondary-400"
              }`}
              onClick={() => handleFilterGetShifPlane(20, 4)}
            >
              <div className="mr-1">
                <p className="mb-0 text-[12px] text-secondary-900 font-medium">
                  شیفت های ماه قبل{" "}
                </p>
              </div>
            </div>

            <div
              className={`border-2  px-2 py-1 w-fit rounded-full flex mt-2 tr03 mr-1 ${
                shifilterShifPlaneSelect == 5
                  ? " bg-primary-200 border-secondary-300"
                  : "opacity-50 border-secondary-400"
              }`}
              onClick={() => handleFilterGetShifPlane(21, 5)}
            >
              <div className="mr-1">
                <p className="mb-0 text-[12px] text-secondary-900 font-medium">
                  شیفت های ماه بعد{" "}
                </p>
              </div>
            </div>
          </div>
          {shiftplans.length <= 0 ? (
            <NothingFound />
          ) : (
            <>
              {shiftplans?.map((e, index) => (
                <>
                  <div
                    className={` px-3 py-5  tr03  ${
                      shiftPlansSelect == index
                        ? "h-fit bg-secondary-50 rounded-b-2xl "
                        : "border-b border-gray-200"
                    }`}
                  >
                    <div
                      className={`flex justify-between   ${
                        shiftPlansSelect == index ? "" : ""
                      }`}
                      onClick={() => setShiftPlansSelect(index)}
                    >
                      <div className="flex">
                        <PersianNumber
                          number={FormatJalaliDate(e.planFor, true)}
                        />
                        <div className="w-[2px] h-5 mx-2 bg-primary-200 opacity-75 "></div>

                        <div className="  h-fit">
                          <p className="mb-0 text-sm text-secondary-600 ">
                            <PersianNumber
                              number={e.data.length}
                              style={"ml-1"}
                            />
                            شیفت
                          </p>
                        </div>

                        <p className="mb-0 mt-[-3px] mx-1">
                          {checkDateStatus(e.planFor).today ? (
                            <small className="!text-primary-300 ">
                              (امروز)
                            </small>
                          ) : (
                            ""
                          )}
                        </p>
                      </div>

                      <div>
                        <div className="">
                          <svg
                            width="12"
                            height="12"
                            viewBox="0 0 151 89"
                            fill="none"
                            xmlns="http://www.w3.org/2000/svg"
                            className="opacity-60 mt-1 mx-auto"
                          >
                            <path
                              d="M13.0444 13.1674L75.3606 75.8506L138.044 13.5345"
                              stroke="#424242"
                              stroke-opacity="0.81"
                              stroke-width="25"
                              stroke-linecap="round"
                              stroke-linejoin="round"
                            />
                          </svg>
                        </div>
                      </div>
                    </div>

                    {shiftPlansSelect == index && (
                      <>
                        {e.data.map((e) => (
                          <div>
                            <div className="flex justify-between">
                              <div className="ml-2  rounded-xl  mt-3 p-2">
                                <p className="text-sm mb-0 text-gray-700 font-medium">
                                  {" "}
                                  {e.shiftTitle}
                                </p>
                              </div>
                            </div>

                            <div className="flex flex-wrap">
                              {e.users.map((i) => (
                                <div className="flex bg-gray-50 p-1 rounded-full m-1 justify-start mb-2 w-fit ">
                                  <div className="w-[25px] h-[25px] rounded-full bg-gray-400 ">
                                    <Avatar
                                      size={25}
                                      name={i.positionName}
                                      variant="beam"
                                      colors={["#9d9f88", "#83af96", "#b2de93"]}
                                    />
                                  </div>

                                  <div>
                                    <p className="mb-0 px-3 text-sm mt-1">
                                      {i.userFullName}{" "}
                                    </p>
                                  </div>
                                </div>
                              ))}

                              <div className="flex bg-primary-400 p-1 rounded-full m-1 justify-start mb-2 w-fit ">
                                <div className="px-4 h-[30px] rounded-full bg-primary-200 ">
                                  <p className="mb-0 text-center   mt-[2px] text-sm">
                                    سوپروایزر
                                  </p>
                                </div>

                                <div>
                                  <p className="mb-0 px-3 text-sm mt-1 text-white">
                                    {e.supervisorFullName}
                                  </p>
                                </div>
                              </div>
                            </div>
                          </div>
                        ))}

                        {checkDateStatus(e.planFor).yesterday && (
                          <Link href={"/shifts/complete-shift?day=yesterday"}>
                            <div className="mt-6">
                              <button className="btn bg-secondary-950 text-primary-300 w-full font-bold rounded-2xl text-sm p-3">
                                بستن و تایید شیفت
                              </button>
                            </div>
                          </Link>
                        )}

                        {checkDateStatus(e.planFor).today && (
                          <Link href={"/shifts/complete-shift"}>
                            <div className="mt-6">
                              <button className="btn bg-secondary-950 text-primary-300 w-full font-bold rounded-2xl text-sm p-3">
                                بستن و تایید شیفت
                              </button>
                            </div>
                          </Link>
                        )}

                        {checkDateStatus(e.planFor).tomorrow && (
                          <Link href={"/shifts/complete-shift?day=tomorrow"}>
                            <div className="mt-6">
                              <button className="btn bg-secondary-950 text-primary-300 w-full font-bold rounded-2xl text-sm p-3">
                                بستن و تایید شیفت
                              </button>
                            </div>
                          </Link>
                        )}
                      </>
                    )}
                  </div>
                </>
              ))}
            </>
          )}
        </div>
      </div>
    </>
  );
};

export default Shifts;
