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";
import { sharedWithMeProjects } from "../../services/dashboard/sharedWithMeProject";
import { duplicateProject } from "../../services/dashboard/duplicateProject";
import { generateUniqueId } from "../../functions/generateUniqueId";

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 [sharedwithMeProject, setSharedWithMeProjects] = useState<any>([]);
  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 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 fetchAllProjects = async () => {
    try {
      const projects = await getAllProjects(userId, organization);

      if (!projects || !projects.Projects) return;

      if (JSON.stringify(projects) !== JSON.stringify(workspaceProjects)) {
        setWorkspaceProjects(projects);
      }
    } catch (error) {}
  };

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

      //socket for deleting the project
      if (projectSocket) {
        projectSocket.emit("v1:project:delete", deleteProjects);
      } else {
      }
      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) {}
  };

  const handleDuplicateWorkspaceProject = async (
    projectId: string,
    projectName: string,
    thumbnail: string
  ) => {
    // const duplicatedProject = await duplicateProject(
    //   projectId,
    //   generateUniqueId(),
    //   thumbnail,
    //   projectName
    // );
    // console.log("duplicatedProject: ", duplicatedProject);

    const duplicateProjectData = {
      userId,
      thumbnail,
      organization,
      projectUuid: generateUniqueId(),
      refProjectID: 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}
      />
    ));
  };

  const renderSharedProjects = () => {
    return sharedwithMeProject?.map((project: any) => (
      <DashboardCard
        key={project._id}
        projectName={project.projectName}
        thumbnail={project.thumbnail}
        projectId={project._id}
        createdAt={project.createdAt}
        setIsSearchActive={setIsSearchActive}
        active="shared"
        createdBy={project.createdBy}
        setProjectDuplicateData={setProjectDuplicateData}
        handleDuplicateWorkspaceProject={handleDuplicateWorkspaceProject}
        setActiveFolder={setActiveFolder}
      />
    ));
  };

  const sharedProject = async () => {
    try {
      const sharedWithMe = await sharedWithMeProjects();
      setSharedWithMeProjects(sharedWithMe);
    } catch {}
  };

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

  useEffect(() => {
    if (activeFolder === "shared") {
      sharedProject();
    }
  }, [activeFolder]);

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

      <div
        className="dashboard-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">
          {activeFolder == "myProjects"
            ? renderProjects()
            : renderSharedProjects()}
        </div>

        {projectDuplicateData &&
          Object.keys(projectDuplicateData).length > 0 && (
            <ProjectSocketRes
              setIsSearchActive={setIsSearchActive}
              setWorkspaceProjects={setWorkspaceProjects}
            />
          )}
      </div>
    </div>
  );
};

export default DashboardProjects;
