import Calendar from "Components/Calendar/Calendar";
import React from "react";
import { GlobalContext } from "Src/globalContext";
import {
  getAllMembersForManager,
  retrieveAllForProjectCalendarForManager,
} from "Src/services/managerServices";
import { AuthContext, tokenExpireError } from "../../authContext";

const ManagerProjectCalendar = () => {
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [members, setMembers] = React.useState([]);
  const [selectedMemberId, setSelectedMemberId] = React.useState("");
  const [isLoading, setIsLoading] = React.useState(false);
  const [events, setEvents] = React.useState([]);

  const getAllProjects = async (members) => {
    try {
      if (selectedMemberId) {
        const result = await retrieveAllForProjectCalendarForManager(1, 4000, {
          user_id: selectedMemberId && Number(selectedMemberId),
        });
        if (!result.error) {
          setEvents(result.list);
        } else {
          setEvents([]);
        }
      } else {
        const result = await retrieveAllForProjectCalendarForManager(
          1,
          4000,
          {}
        );
        if (!result.error) {
          console.log(members.map((elem) => elem.id));
          const filteredObjects = result.list.filter((obj) =>
            members.map((elem) => elem.id).includes(obj.user_id)
          );
          console.log(filteredObjects);
          setEvents(filteredObjects);
        } else {
          setEvents([]);
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const retrieveAllUsers = async () => {
    try {
      let filter = {
        role: "member",
      };
      const result = await getAllMembersForManager(
        localStorage.getItem("user")
      );
      if (!result.error) {
        if (result.list.length > 0) {
          let list = result.list;
          // concat first_name and last_name into user_name
          // then sort by ascending order of user_name
          list = list.map((row) => {
            row.user_name = row.first_name + " " + row.last_name;
            return row;
          });
          list = list.sort((a, b) => {
            return a.user_name.localeCompare(b.user_name);
          });

          setMembers(list);
          return list;
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "project-calendar",
      },
    });

    (async function () {
      setIsLoading(true);
      const list = await retrieveAllUsers();
      await getAllProjects(list);
      setIsLoading(false);
    })();
  }, []);

  React.useEffect(() => {
    (async function () {
      setIsLoading(true);
      await getAllProjects(members);
      setIsLoading(false);
    })();
  }, [selectedMemberId]);

  return (
    <div className="max-w-screen w-full p-4 xl:p-8">
      <div className="w-full">
        {/* Header with Member Selection */}

        {/* Calendar Section */}

        <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
          <Calendar events={events} isLoading={isLoading} />
        </div>
      </div>
    </div>
  );
};

export default ManagerProjectCalendar;
