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";
import { useProfile } from "../../hooks/useProfile";
import { useDispatch, useSelector } from "react-redux";
import { useProjectDetails, useProjects } from "../../hooks/useProjects";
import { setProjectId } from "../../slices/localVariablesSlice";
import showToast from "../../services/toastService";

const TaskPlannng = () => {
  const { profile } = useProfile();
  const {
    projects,
    loading: project_listLoader,
    error: projects_error,
  } = useProjects();
  const dispatch = useDispatch();
  const selectedProject = useSelector(
    (store) => store.localVariables.projectId
  );


  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");
      if (!project_cache || !project_cache.projectId == selectedProject) {
        ProjectRepository.getProjectByprojectId(selectedProject)
          .then((response) => {
            setProjectDetails(response);
            setProject(response);
            cacheData("projectInfo", {
              data: response.data,
              projectId: selectedProject,
            });
          })
          .catch((error) => {
            const message =
            error.response?.data?.message ||
            error.message ||
            "An unexpected error occurred";
            showToast( message, "error" );
          });
      } else {
        setProjectDetails(project_cache);
      }
    } catch (err) {
      setError( "Failed to fetch data." );
        const message =
            error.response?.data?.message ||
            error.message ||
            "An unexpected error occurred";
            showToast( message, "error" );
    } finally {
      setLoading(false);
    }
  };

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

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

  const handleDataChange = (data) => {
    fetchData();
  };

  useEffect(() => {
    if (projects.length != 0 && selectedProject) {
      fetchData();
      fetchActivities();
    }
  }, [selectedProject]);

  return (
    <>
      <div className="container-xxl flex-grow-1 container-p-y">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Daily Task Planning", link: "/activities/task" },
          ]}
        ></Breadcrumb>
        {project_listLoader && <p>Loading..</p>}
        {!project_listLoader && projects.length === 0 && (
          <p>No Project Found.</p>
        )}
        {!project_listLoader && projects.length > 0 && (
          <InfraPlanning
            data={projectDetails}
            activityMaster={activities}
            onDataChange={handleDataChange}
          />
        )}
      </div>
    </>
  );
};

export default TaskPlannng;
