"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 CheckBoxBriz from "plugins/CheckBoxBriz/page";
import Buttonbriz from "plugins/Buttonbriz/page";
import { toast } from "react-toastify";
import PersianNumber from "plugins/PersianNumber";
import moment from "jalali-moment";

const BottomSheetReportManageShift = (props) => {
  const CTX = useContext(AppContext);
  const shiftplansData = CTX.state.shiftPlansData;
  const [shiftplans, setShiftplans] = useState([]);
  const [type, setType] = useState(0);

  // const reportDetail = CTX.state.reportDetail;

  // const handleSendReport_SHIFTPLAN = () => {
  //   CTX.ReportShiftPlan(reportDetail?.shiftId);
  //   CTX.setBottomSheetReportManageShiftOpen(false);
  // };

  // const handleSendReport_TASK = () => {
  //   CTX.ReportTask();
  //   CTX.setBottomSheetReportManageShiftOpen(false);
  // };

  const handleBottomSheetCreateRole = (e) => {
    if (e.type == "OPEN") {
      CTX.GetShifPlans(0, 12);
    } else if (e.type == "CLOSE") {
      setType(0);
    }
  };

  const handleReportManageShift = (num, filterId) => {
    setType(num);
    CTX.GetShifPlans(0, filterId);
  };

  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);
  };

  const formatShiftPlans = () => {
    let formattedText = "";

    shiftplans.forEach((e, dayIndex) => {
      if (dayIndex > 0) {
        formattedText += "\n\n\n"; // Add three newlines between each day
      }

      formattedText += `${moment(e.planFor)
        .locale("fa")
        .format("dddd، jD jMMMM jYYYY")}\n\n`;

      e.data.forEach((shift, shiftIndex) => {
        if (shiftIndex > 0) {
          formattedText += "\n"; // Add one newline between each shift
        }
        formattedText += `${shift.shiftTitle}\n`;

        shift.users.forEach((user) => {
          formattedText += `${user.positionName} : ${user.userFullName}\n`;
        });

        formattedText += `سوپروایزر : ${shift.supervisorFullName}\n`;
      });
    });

    return formattedText.trim(); // Trim the final result to remove any leading/trailing newlines
  };

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

  return (
    <BottomSheet
      onSpringStart={(e) => handleBottomSheetCreateRole(e)}
      open={CTX.state.BottomSheetReportManageShiftOpen}
      onDismiss={() => CTX.setBottomSheetReportManageShiftOpen(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="flex bg-gray-100 rounded-xl m-3 rtl">
        <div
          className={` p-2 w-full rounded-xl tr03 ${
            type == 0 ? "bg-secondary-950" : ""
          } `}
          onClick={() => handleReportManageShift(0, 12)}
        >
          <p
            className={`mb-0 text-center  text-sm ${
              type == 0 ? "text-white" : " text-secondary-900"
            }`}
          >
            همین هفته{" "}
          </p>
        </div>
        <div
          className={` p-2 w-full rounded-xl tr03 ${
            type == 1 ? "bg-secondary-950" : ""
          } `}
          onClick={() => handleReportManageShift(1, 11)}
        >
          <p
            className={`mb-0 text-center text-sm ${
              type == 1 ? "text-white" : " text-secondary-900"
            }`}
          >
            هفته بعد{" "}
          </p>
        </div>
      </div>
      <div className="px-3 pt-10 ">
        <p id="MYTEXT" className="mb-0 text-center text-sm font-light">
          {shiftplans?.map((e, index) => (
            <div key={index} className="mb-4 h-fit mb-10">
              <div className="flex justify-between rtl mb-2">
                <div className="flex">
                  <PersianNumber
                    number={moment(e.planFor)
                      .locale("fa")
                      .format("dddd، jD jMMMM jYYYY")}
                  />
                </div>
              </div>
              {e.data.map((shift, shiftIndex) => (
                <div key={shiftIndex} className="rtl mb-3">
                  <div className="flex justify-between mb-2">
                    <div className="ml-2 rounded-xl">
                      <p className="text-sm mb-0 text-gray-700 font-medium">
                        {shift.shiftTitle}
                      </p>
                    </div>
                  </div>
                  <div className="flex flex-wrap mb-2">
                    {shift.users.map((user, userIndex) => (
                      <div
                        key={userIndex}
                        className="flex p-1 rounded-full w-fit"
                      >
                        <p className="mb-0 text-[12px] font-medium">
                          {user.positionName} : {user.userFullName}
                        </p>
                      </div>
                    ))}
                    <div className="flex p-1 rounded-full w-fit">
                      <p className="mb-0 text-[12px] font-medium text-red-600">
                        سوپروایزر : {shift.supervisorFullName}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ))}
        </p>
      </div>

      <div className=" p-4">
        <Buttonbriz
          title="کپی کردن متن "
          color="INFO"
          icon="CHECK"
          buttonEvent={() => {
            const text = formatShiftPlans();
            navigator.clipboard
              .writeText(text)
              .then(() => {
                toast.success("کپی شد");
              })
              .catch((err) => {});
          }}
        />
      </div>
    </BottomSheet>
  );
};

export default BottomSheetReportManageShift;
