
import React, { useState, useEffect } from "react";
import "../../components/Project/ProjectInfra.css";

import ProjectRepository from "../../repositories/ProjectRepository";
import Breadcrumb from "../../components/common/Breadcrumb";
import InfraPlanning from "../../components/Activities/InfraPlanning";
import { cacheData, getCachedData } from "../../slices/apiDataManager";

var  projectId;
const TaskPlannng = () => {


  const [project, setProject] = useState(null);
  const [projectDetails, setProjectDetails] = useState(null);
  const [activities, setActivities] = useState(null);

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const fetchActivities = async () => {
    try {
      const activities_cache = getCachedData("activitiesMaster");

      if (!activities_cache) {
        ActivityeRepository.getActivities()
          .then((response) => {
            setActivities(response.data);
            cacheData("activitiesMaster", response.data);
          })
          .catch((error) => {
            setError("Failed to fetch data.");
          });
      } else {
        setActivities(activities_cache);
      }
    } catch (err) {
      setError("Failed to fetch activities.");
    } finally {
      // setLoading(false);
    }
  };

  const fetchData = async () => {
    try {
      const project_cache = getCachedData(`projectinfo-${1}`);
      if (!project_cache) {
        ProjectRepository.getProjectByprojectId(1)
          .then((response) => {
            setProjectDetails(response);
            setProject(response);
            cacheData(`projectinfo-${projectId}`, response);
          })
          .catch((error) => {
            console.error(error);
            setError("Failed to fetch data.");
          });
      } else {
        setProjectDetails(project_cache);
      }
    } catch (err) {
      console.log(err)
      setError("Failed to fetch data.");
    } finally {
      setLoading(false);
    }
  };

  const [activePill, setActivePill] = useState("profile");

  const handlePillClick = (pillKey) => {
    setActivePill(pillKey);
  };

  const handleDataChange = (data) => {
    fetchData();
  };
  
   useEffect(() => {
    projectId =1
      fetchData();
      fetchActivities();
    }, []);


  return (
    <>    
      <div className="container-xxl flex-grow-1 container-p-y">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Daily Task Planning", link: "/task" },
    
          ]}
        ></Breadcrumb>
             <InfraPlanning 
               data={projectDetails}
               activityMaster={activities}
               onDataChange={handleDataChange} 
            /> 
      </div>
    </>
  );
};

export default TaskPlannng;
