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

import ProjectCard from "../../components/Project/ProjectCard";
import ManageProjectInfo from "../../components/Project/ManageProjectInfo";
import showToast from "../../services/toastService";
import Breadcrumb from "../../components/common/Breadcrumb";

import {
  cacheData,
  clearCacheKey,
  getCachedData,
} from "../../slices/apiDataManager";
import ProjectRepository from "../../repositories/ProjectRepository";
import { useProjects } from "../../hooks/useProjects";
import { useDispatch } from "react-redux";
import { changeMaster } from "../../slices/localVariablesSlice";


const ProjectList = () => {
  const { projects,loading,error} = useProjects()
  const dispatch = useDispatch()

  // -------hook-----
// const [projects, setProjects] = useState([]); 
// const [loading, setLoading] = useState(true);
// const [error, setError] = useState("");

  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);

  //const projects_cache = getCachedData("projectslist");

  const openModal = () => {
    console.log("clicked")
    setIsCreateModalOpen(true);
  };

  // Close the modal
  const closeModal = () => {
    setIsCreateModalOpen(false);
    const modalBackdrop = document.querySelector(".modal-backdrop");
    if (modalBackdrop) modalBackdrop.remove();
  };

  // const fetchData = async () => {
  //   const projects_cache = getCachedData("projectslist");
  //   if (!projects_cache) {
  //     ProjectRepository.getProjectList()
  //       .then((response) => {
  //         setProjects(response);
  //         cacheData("projectslist", response);
  //         setLoading(false);
  //       })
  //       .catch((error) => {
  //         console.error(error);
  //         setError("Failed to fetch data.");
  //       });
  //   } else {
  //     if (!projects.length) setProjects(projects_cache);
  //   }
  // };

  const handleFormSubmit = (updatedProject) => {
    delete updatedProject.id;
    //console.log("Form submitted:", updatedProject);
    ProjectRepository.manageProject(updatedProject)
      .then((response) => {
        clearCacheKey("projectslist");
        fetchData();
        showToast("Project updated successfully.", "success");
        closeModal();
      })
      .catch((error) => {
        showToast(error.message, "error");
      });

    // api
    //   .post("/api/project", updatedProject)
    //   .then((data) => {
    //     clearCacheKey("projectslist");
    //     fetchData();
    //     showToast("Project updated successfully.", "success");
    //     closeModal();
    //   })
    //   .catch((error) => {
    //     showToast(error.message, "error");
    //   });
  };

  // useEffect(() => {
  //   fetchData();
  // }, []);


  
  useEffect(() => {
    if (isCreateModalOpen) {
      const modalElement = document.getElementById("create-project-model");
      const modal = new window.bootstrap.Modal(modalElement);
      modal.show(); 
    }
    dispatch(changeMaster("JobRole"))
  }, [isCreateModalOpen]);

  return (
    <>
      {isCreateModalOpen && (
        <div
          className={`modal fade `}
          id="create-project-model"
          tabIndex="-1"
          aria-hidden="true"
        >
          <ManageProjectInfo
            project={null}
            onClose={closeModal}
            onSubmit={handleFormSubmit}
          ></ManageProjectInfo>
        </div>
      )}
      <div className="container-xxl flex-grow-1 container-p-y">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Projects", link: null },
          ]}
        ></Breadcrumb>

        <div className="row">
          <div className="col-md-12 col-lg-12 col-xl-12 order-0 mb-4 text-end">
            {" "}
            <button
              type="button"
              className="btn btn-sm btn-primary"
              data-bs-toggle="modal"
              data-bs-target="#create-project-model"
              onClick={openModal}
            >
              <i className="bx bx-plus-circle me-2"></i>
              Create New Project
            </button>
          </div>
        </div>
        <div className="row">
          {loading && (<p class="text-center">Loading...</p>)}
          {projects?.map((item) => (
            <ProjectCard project={item} key={item.id}></ProjectCard>
          ))}
        </div>
      </div>
    </>
  );
};

export default ProjectList;
