import Calendar from "Components/Calendar/Calendar";
import React, { useEffect, useState } from "react";
import { ClipLoader } from "react-spinners";
import { GlobalContext } from "Src/globalContext";
import { retrieveAllProjectAPI } from "Src/services/projectService";
import { AuthContext, tokenExpireError } from "../authContext";

const ProjectCalendar = () => {
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [isLoading, setIsLoading] = React.useState(false);
  const [events, setEvents] = useState([]);

  const getAllProjects = async () => {
    try {
      const result = await retrieveAllProjectAPI(1, 2000, {});
      if (!result.error) {
        setEvents(result.list);
      } else {
        setEvents([]);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

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

    (async function () {
      setIsLoading(true);
      await getAllProjects();
      setIsLoading(false);
    })();
  }, []);

  return (
    <div className="max-w-screen w-full p-4 xl:p-8">
      <div className="w-full">
        {isLoading ? (
          <div className="flex h-[calc(100vh-160px)] w-full items-center justify-center">
            <ClipLoader color="#fff" size={30} />
          </div>
        ) : (
          <Calendar events={events} />
        )}
      </div>
    </div>
  );
};

export default ProjectCalendar;
