import { MdOutlineAccessTime } from "react-icons/md";
import { useGetAllsummary } from "../../../../../api/summary";
import { FaPlus } from "react-icons/fa";
import AddProgrammeModalForm from "./Model/AddModel";
import EditProgrammeModalForm from "./Model/EditModel";
import useModalHandler from "../../../../../utils/useModalHandler";
import { ModalEnum } from "../../../../../enums/Model";
import { useObjectToEdit } from "../../../../../zustand/ObjectToEditState";
import dayjs from "dayjs";
import { useParams } from "react-router-dom";
import { Spin } from "antd";
import { useTranslation } from "react-i18next";
import useWeekDays from "./useWeekDays";
import { hasAbility } from "../../../../../utils/hasAbility";
import {
  ABILITIES_ENUM,
  ABILITIES_VALUES_ENUM,
} from "../../../../../enums/abilities";
import { downloadPdf } from "../../../../../utils/downloadPdf";
import { useState } from "react";

const Page = () => {
  const { edu_class_id } = useParams();
  const { data, isLoading } = useGetAllsummary({
    edu_class_id: edu_class_id,
  });
  const { handel_open_model } = useModalHandler();
  const { set_object_to_edit } = useObjectToEdit((state) => state);
  const can_add_session = hasAbility(
    ABILITIES_ENUM.SESSION,
    ABILITIES_VALUES_ENUM.STORE,
  );
  const can_edit_session = hasAbility(
    ABILITIES_ENUM.SESSION,
    ABILITIES_VALUES_ENUM.UPDATE,
  );

  const handelAdd = (day: any) => {
    if (can_add_session) {
      handel_open_model(ModalEnum?.PROGRAMME_ADD);
      // console.log(day, "day");

      set_object_to_edit(day);
    }
  };
  const handelEdit = (day: any) => {
    // console.log(day, "day");
    if (can_edit_session) {
      handel_open_model(ModalEnum?.PROGRAMME_EDIT);
      set_object_to_edit(day);
    }
  };

  const formatTime = (time: any) => {
    return time.format("H:mm");
  };
  const Period_Number = 7;

  const [t] = useTranslation();
  const Period = [
    t("array.Period.Today"),
    t("array.Period.First"),
    t("array.Period.Second"),
    t("array.Period.Third"),
    t("array.Period.Fourth"),
    t("array.Period.Fifth"),
    t("array.Period.Sixth"),
    t("array.Period.Seventh"),
  ];

  const { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } =
    useWeekDays(data);
  const [loading, setLoading] = useState(false);
  const handleDownloadPdf = () => {
    downloadPdf("pdfContent", "myDocument", setLoading);
  };

  if (isLoading) {
    return <Spin />;
  }
  const padArrayWithOrderAndData = (items: any[]) => {
    // Define the number of periods

    // console.log(items,"items");

    // Function to pad the array with additional items
    const paddedArray = (itemsArray: any[]) => {
      if (!itemsArray || itemsArray.length === 0) {
        // If the array is empty, fill it with null items up to Period_Number + 1
        return Array.from({ length: Period_Number + 1 }, (_, i) => ({
          order: i,
          data: null,
          day: itemsArray[0]?.day,
        }));
      }

      // Get the existing orders
      const existingOrders = itemsArray.map((item) => item.order);

      // Find the missing orders from 0 to Period_Number
      const missingOrders = Array.from(
        { length: Period_Number + 1 },
        (_, i) => i,
      ).filter((order) => !existingOrders.includes(order));

      // Create new items for the missing orders
      const newItems = missingOrders.map((order) => ({
        order,
        data: null,
        day: itemsArray[0]?.day,
      }));

      // Concatenate existing items with new items
      const padded = itemsArray.concat(newItems);

      // Sort the padded array by order
      padded.sort((a, b) => a.order - b.order);
      return padded;
    };

    // Call the paddedArray function with the provided items
    const paddedResult = paddedArray(items);

    return paddedResult;
  };

  const renderDay = (day: any) => {
    if (!day || typeof day !== "object") {
      return null;
    }

    switch (day?.order) {
      case 0:
        return <div className="Day_Name block center">{day?.name}</div>;

      default:
        if (day.order > Period_Number) {
          return null;
        }
        if (day?.data === null) {
          return (
            <div
              onClick={() => handelAdd(day)}
              className="Day_Details Add_New_Day block center"
            >
              <span>
                <FaPlus />
              </span>
            </div>
          );
        } else {
          const fromTime = formatTime(dayjs(day.from, "HH:mm"));
          const toTime = formatTime(dayjs(day.to, "HH:mm"));

          return (
            <div className="Day_Details block" onClick={() => handelEdit(day)}>
              <h5>{day?.subject?.name}</h5>
              <h6>{day?.teacher?.name}</h6>
              <div>
                <MdOutlineAccessTime />
                <p>
                  {fromTime} - {toTime}
                </p>
              </div>
            </div>
          );
        }
    }
  };

  const renderDayOrPlaceHolder = (items: any) => {
    const paddedArray = padArrayWithOrderAndData(items);
    return paddedArray.map((item: any, index: any) => (
      <div key={index} className="Day_Item">
        {renderDay(item)}
      </div>
    ));
  };

  return (
    <div className="TableWithHeader">
      <header className="programmer_header">
        <div>{t("header.Weekly_Class_Schedule")}</div>
        <div>
          <button className="button" onClick={() => handleDownloadPdf()}>
            {t("header.Print_Schedule")}
          </button>
        </div>
      </header>
      <div id="pdfContent" className="programme p-2">
        <div className="Periods">
          {Period.map((day, index) => (
            <span className="Period block" key={index}>
              {day}
            </span>
          ))}
        </div>

        <div className="programme_table">
          <div className="Single_Day Saturday_Day">
            {renderDayOrPlaceHolder(Saturday)}
          </div>

          <div className="Single_Day Sunday_Day">
            {renderDayOrPlaceHolder(Sunday)}
          </div>
          <div className="Single_Day Monday_Day">
            {renderDayOrPlaceHolder(Monday)}
          </div>
          <div className="Single_Day Tuesday_Day">
            {renderDayOrPlaceHolder(Tuesday)}
          </div>
          <div className="Single_Day Wednesday_Day">
            {renderDayOrPlaceHolder(Wednesday)}
          </div>
          <div className="Single_Day Thursday_Day">
            {renderDayOrPlaceHolder(Thursday)}
          </div>
          <div className="Single_Day Friday_Day">
            {renderDayOrPlaceHolder(Friday)}
          </div>
        </div>
      </div>
      <AddProgrammeModalForm />
      <EditProgrammeModalForm />
    </div>
  );
};

export default Page;
