import React, { useEffect, useState } from "react";
import DashboardNavBar from "./DashboardNavBar";
import DashboardCard from "./DashboardCard";
import { getUserData } from "../../functions/getUserData";
import { useSocketStore } from "../../store/builder/store";
import { getAllProjects } from "../../services/dashboard/getAllProjects";
import { searchProject } from "../../services/dashboard/searchProjects";
import { deleteProject } from "../../services/dashboard/deleteProject";
import ProjectSocketRes from "./socket/projectSocketRes.dev";

interface Project {
  _id: string;
  projectName: string;
  thumbnail: string;
  createdBy: string;
  projectUuid?: string;
  createdAt: string;
}

interface WorkspaceProjects {
  [key: string]: Project[];
}

const DashboardProjects: React.FC = () => {
  const [workspaceProjects, setWorkspaceProjects] = useState<WorkspaceProjects>(
    {}
  );
  const [projectDuplicateData, setProjectDuplicateData] = useState<Object>({});
  const [isSearchActive, setIsSearchActive] = useState<boolean>(false);
  const [activeFolder, setActiveFolder] = useState<string>("myProjects");
  const { projectSocket } = useSocketStore();
  const { userId, organization } = getUserData();

  const fetchAllProjects = async () => {
    try {
      const projects = await getAllProjects(userId, organization);

      if (JSON.stringify(projects) !== JSON.stringify(workspaceProjects)) {
        setWorkspaceProjects(projects);
      }
    } catch (error) {
      console.error("Error fetching projects:", error);
    }
  };

  const handleProjectsSearch = async (inputValue: string) => {
    if (!inputValue.trim()) {
      setIsSearchActive(false);
      return;
    }
    if (!setWorkspaceProjects || !setIsSearchActive) return;

    const searchedProject = await searchProject(organization, userId, inputValue);
    setIsSearchActive(true);
    setWorkspaceProjects(searchedProject.message ? {} : searchedProject);
  };

  const handleDeleteProject = async (projectId: any) => {
    try {
      // const deletedProject = await deleteProject(
      //   projectId,
      //   userId,
      //   organization
      // );
      // console.log('deletedProject: ', deletedProject);
      const deleteProjects = {
        projectId,
        organization,
        userId,
      };

      //socket for deleting the project
      if (projectSocket) {
        projectSocket.emit("v1:project:delete", deleteProjects);
      } else {
        console.error("Socket is not connected.");
      }
      setWorkspaceProjects((prevDiscardedProjects: WorkspaceProjects) => {
        if (!Array.isArray(prevDiscardedProjects?.Projects)) {
          return prevDiscardedProjects;
        }
        const updatedProjectDatas = prevDiscardedProjects.Projects.filter(
          (project) => project._id !== projectId
        );
        return {
          ...prevDiscardedProjects,
          Projects: updatedProjectDatas,
        };
      });
      setIsSearchActive(false);
    } catch (error) {
      console.error("Error deleting project:", error);
    }
  };

  const handleDuplicateWorkspaceProject = async (
    projectId: string,
    projectName: string,
    thumbnail: string
  ) => {
    // await handleDuplicateProjects({
    //   userId,
    //   organization,
    //   projectId,
    //   projectName,
    //   projectSocket,
    //   thumbnail,
    //   setWorkspaceProjects,
    //   setIsSearchActive
    // });
    const duplicateProjectData = {
      userId,
      thumbnail,
      organization,
      projectUuid: projectId,
      projectName,
    };
    projectSocket.emit("v1:project:Duplicate", duplicateProjectData);
  };

  const renderProjects = () => {
    if (activeFolder !== "myProjects") return null;

    const projectList = workspaceProjects[Object.keys(workspaceProjects)[0]];

    if (!projectList?.length) {
      return <div className="empty-state">No projects found</div>;
    }

    return projectList.map((project) => (
      <DashboardCard
        key={project._id}
        projectName={project.projectName}
        thumbnail={project.thumbnail}
        projectId={project._id}
        createdAt={project.createdAt}
        handleDeleteProject={handleDeleteProject}
        setIsSearchActive={setIsSearchActive}
        handleDuplicateWorkspaceProject={handleDuplicateWorkspaceProject}
        setProjectDuplicateData={setProjectDuplicateData}
      />
    ));
  };

  useEffect(() => {
    if (!isSearchActive) {
      fetchAllProjects();
    }
  }, [isSearchActive]);

  return (
    <div className="dashboard-home-container">
      <DashboardNavBar
        page="projects"
        handleProjectsSearch={handleProjectsSearch}
      />

      <div className="container" style={{ height: "calc(100% - 87px)" }}>
        <div className="header-wrapper" style={{ display: "flex", gap: "7px" }}>
          <button
            className={`header ${activeFolder === "myProjects" && "active"}`}
            onClick={() => setActiveFolder("myProjects")}
          >
            My Projects
          </button>
          <button
            className={`header ${activeFolder === "shared" && "active"}`}
            onClick={() => setActiveFolder("shared")}
          >
            Shared with me
          </button>
        </div>
        <div className="cards-container">{renderProjects()}</div>
        {projectDuplicateData && Object.keys(projectDuplicateData).length > 0 && (
          <ProjectSocketRes
            setIsSearchActive={setIsSearchActive}
            setWorkspaceProjects={setWorkspaceProjects}
          />
        )}
      </div>
    </div>
  );
};

export default DashboardProjects;