import React, { useEffect, useState } from "react";
import { getTrash } from "../../../services/dashboard/getTrash";
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";

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

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

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

  const fetchTrashProjects = async () => {
    try {
      const projects = await getTrash(organization);
      console.log("organization: ", organization);
      console.log("trashedprojects: ", projects);

      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 Organization = organization;
      const restoreProject = await restoreTrash(Organization, projectId);

      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 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}
      />
    ));
  };

  useEffect(() => {
    console.log("isSearchActive:trash ", isSearchActive);
    if (!isSearchActive) {
      fetchTrashProjects();
    }
  }, [isSearchActive]);

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

      <div className="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;
