import React, { useEffect, useState } from "react";
import DashboardCard from "./DashboardCard";
import DashboardNavBar from "./DashboardNavBar";
import MarketPlaceBanner from "./MarketPlaceBanner";
import { getUserData } from "../../functions/getUserData";
import { useSocketStore } from "../../store/builder/store";
import { recentlyViewed } from "../../services/dashboard/recentlyViewed";
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: { _id: string, userName: string };
  projectUuid?: string;
  createdAt: string;
  isViewed?: string
}

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

const DashboardHome: React.FC = () => {
  const [recentProjects, setRecentProjects] = useState<RecentProjectsData>({});
  const [isSearchActive, setIsSearchActive] = useState<boolean>(false);
  const { userId, organization } = getUserData();
  const { projectSocket } = useSocketStore();
  const [recentDuplicateData, setRecentDuplicateData] = useState<Object>({});


  const fetchRecentProjects = async () => {
    try {
      const projects = await recentlyViewed(organization, userId);

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

  const handleRecentProjectSearch = async (inputValue: string) => {
    if (!inputValue.trim()) {
      setIsSearchActive(false);
      return;
    }
    const filterRecentProcess = await searchProject(
      organization,
      userId,
      inputValue
    );
    setIsSearchActive(true);
    setRecentProjects(filterRecentProcess.message ? {} : filterRecentProcess);
  };

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

      //socket for delete Project
      const deleteProject = {
        projectId,
        organization,
        userId,
      };

      if (projectSocket) {
        projectSocket.emit("v1:project:delete", deleteProject);
      }

      setRecentProjects((prevDiscardedProjects: RecentProjectsData) => {
        if (!Array.isArray(prevDiscardedProjects?.RecentlyViewed)) {
          return prevDiscardedProjects;
        }
        const updatedProjectDatas = prevDiscardedProjects.RecentlyViewed.filter(
          (project) => project._id !== projectId
        );
        return {
          ...prevDiscardedProjects,
          RecentlyViewed: updatedProjectDatas,
        };
      });
      setIsSearchActive(false);
    } catch (error) {
      console.error("Error deleting project:", error);
    }
  };

  const handleDuplicateRecentProject = async (
    projectId: string,
    projectName: string,
    thumbnail: string
  ) => {
    const duplicateRecentProjectData = {
      userId,
      thumbnail,
      organization,
      projectUuid: projectId,
      projectName,
    };
    projectSocket.emit("v1:project:Duplicate", duplicateRecentProjectData);
  };

  const renderProjects = () => {
    const projectList = recentProjects[Object.keys(recentProjects)[0]];

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

    return (
      projectList &&
      projectList.map((project) => (
        <DashboardCard
          key={project._id}
          projectName={project.projectName}
          thumbnail={project.thumbnail}
          projectId={project._id}
          createdBy={project.createdBy}
          createdAt={project.createdAt}
          handleDeleteProject={handleDeleteProject}
          handleDuplicateRecentProject={handleDuplicateRecentProject}
          setRecentDuplicateData={setRecentDuplicateData}
        />
      ))
    );
  };

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

  return (
    <div className="dashboard-home-container">
      <DashboardNavBar
        page="home"
        handleRecentProjectSearch={handleRecentProjectSearch}
      />
      <MarketPlaceBanner />
      <div className="dashboard-container">
        <h2 className="section-header">Recents</h2>
        <div className="cards-container">{renderProjects()}</div>
      </div>
      {recentDuplicateData && Object.keys(recentDuplicateData).length > 0 && (
        <ProjectSocketRes
          setIsSearchActive={setIsSearchActive}
          setRecentProjects={setRecentProjects}
        />
      )}
    </div>
  );
};

export default DashboardHome;