import React, { useEffect, useState } from "react";
import DashboardCard from "./DashboardCard";
import DashboardNavBar from "./DashboardNavBar";
import { getUserData } from "../../functions/getUserData";
import { trashSearchProject } from "../../services/dashboard/trashSearchProject";
import { restoreTrash } from "../../services/dashboard/restoreTrash";
import { getTrash } from "../../services/dashboard/getTrash";
import { deleteTrash } from "../../services/dashboard/deleteTrash";
import { useSocketStore } from "../../store/builder/store";

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

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

const DashboardTrash: React.FC = () => {
  const [discardedProjects, setDiscardedProjects] = useState<DiscardedProjects>({});
  const [isSearchActive, setIsSearchActive] = useState(false);
  const { userId, organization } = getUserData();
  const { projectSocket } = useSocketStore();

  const fetchTrashProjects = async () => {
    try {
      const projects = await getTrash(organization);

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

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

    const filterTrashedProcess = await trashSearchProject(
      organization,
      userId,
      inputValue
    );
    setIsSearchActive(true);
    setDiscardedProjects(
      filterTrashedProcess.message ? {} : filterTrashedProcess
    );
  };

  const handleRestoreProject = async (projectId: any) => {
    try {
      const restoreProject = await restoreTrash(organization, projectId);
      // console.log('restoreProject: ', restoreProject);

      setDiscardedProjects((prevDiscardedProjects: DiscardedProjects) => {
        // Check if TrashDatas exists and is an array
        if (!Array.isArray(prevDiscardedProjects?.TrashDatas)) {
          console.error("TrashDatas is not an array", prevDiscardedProjects);
          return prevDiscardedProjects;
        }
        const updatedTrashDatas = prevDiscardedProjects.TrashDatas.filter(
          (project) => project._id !== projectId
        );
        return {
          ...prevDiscardedProjects,
          TrashDatas: updatedTrashDatas,
        };
      });
      setIsSearchActive(false);
    } catch (error) {
      console.error("Error deleting project:", error);
    }
  };

  const handleTrashDeleteProject = async (projectId: any) => {
    try {
      // const deletedProject = await deleteTrash(
      //   organization, projectId
      // );

      const deleteProjectTrash = {
        projectId,
        organization,
        userId,
      };
      if (projectSocket) {
        projectSocket.emit("v1:trash:delete", deleteProjectTrash);
      }
      setDiscardedProjects((prevDiscardedProjects: DiscardedProjects) => {
        if (!Array.isArray(prevDiscardedProjects?.TrashDatas)) {
          return prevDiscardedProjects;
        }
        const updatedProjectDatas = prevDiscardedProjects.TrashDatas.filter(
          (project) => project._id !== projectId
        );
        // console.log('updatedProjectDatas: ', updatedProjectDatas);
        return {
          ...prevDiscardedProjects,
          TrashDatas: updatedProjectDatas,
        };
      });
      setIsSearchActive(false);
    } catch (error) {
      console.error("Error deleting project:", error);
    }
  };

  const renderTrashProjects = () => {
    const projectList = discardedProjects[Object.keys(discardedProjects)[0]];

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

    return projectList.map((project) => (
      <DashboardCard
        key={project._id}
        projectName={project.projectName}
        thumbnail={project.thumbnail}
        projectId={project._id}
        handleRestoreProject={handleRestoreProject}
        handleTrashDeleteProject={handleTrashDeleteProject}
        active={"trash"}
        createdAt={project.DeletedAt}
      />
    ));
  };

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

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

      <div className="dashboard-container" style={{ height: "calc(100% - 87px)" }}>
        <div className="header" style={{ display: "flex", gap: "7px" }}></div>
        <div className="cards-container">{renderTrashProjects()}</div>
      </div>
    </div>
  );
};

export default DashboardTrash;