import React, { useState, useEffect, useRef } from "react";
import RenameInput from "./inputs/RenameInput";
import { ArrowIcon } from "../icons/ExportCommonIcons";
import MenuBar from "./menu/menu";
import { ProjectIcon } from "../icons/HeaderIcons";
import { useProjectName, useSocketStore } from "../../store/builder/store";
import { useParams } from "react-router-dom";
import { getAllProjects } from "../../services/dashboard/getAllProjects";
import { updateProject } from "../../services/dashboard/updateProject";
import { getUserData } from "../../functions/getUserData";

const FileMenu: React.FC = () => {
  const [openMenu, setOpenMenu] = useState(false);
  const containerRef = useRef<HTMLButtonElement>(null);
  let clickTimeout: NodeJS.Timeout | null = null;
  const { projectName, setProjectName } = useProjectName();
  const { dashBoardSocket } = useSocketStore();
  const { projectId } = useParams();
  const { userId, organization, email } = getUserData();

  const handleClick = () => {
    if (clickTimeout) return;
    setOpenMenu((prev) => !prev);
    clickTimeout = setTimeout(() => {
      clickTimeout = null;
    }, 800);
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        containerRef.current &&
        !containerRef.current.contains(event.target as Node)
      ) {
        setOpenMenu(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleProjectRename = async (projectName: string) => {
    setProjectName(projectName);
    if (!projectId) return;

    // localStorage.setItem("projectName", newName);

    try {
      if (!email || !userId) return;

      const projects = await getAllProjects(userId, organization);
      if (!projects || !projects.Projects) return;
      // console.log('projects: ', projects);
      let projectUuid = projects.Projects.find(
        (val: any) => val.projectUuid === projectId || val._id === projectId
      );

      const updateProjects = {
        projectId: projectUuid?._id,
        organization,
        userId,
        projectName,
        thumbnail: undefined,
      };

      // if (dashBoardSocket) {
      //   const handleResponse = (data: any) => {
      //     console.log('Project update response:', data);
      //     dashBoardSocket.off("v1-project:response:update", handleResponse); // Clean up
      //   };
      //   dashBoardSocket.on("v1-project:response:update", handleResponse);
      //   dashBoardSocket.emit("v1:project:update", updateProjects);
      // }

      //API for projects rename

      const updatedProjectName = await updateProject(
        projectId,
        userId,
        organization,
        undefined,
        projectName
      );
    } catch (error) {
      console.error("Error updating project name:", error);
    }
  };
  return (
    <button
      id="project-dropdown-button"
      className="project-dropdowm-container"
      ref={containerRef}
      onClick={handleClick}
    >
      <div className="project-name">
        <div className="icon">
          <ProjectIcon />
        </div>
        <RenameInput value={projectName} onRename={handleProjectRename} />
      </div>
      <div className="more-options-button">
        <ArrowIcon />
        {openMenu && <MenuBar setOpenMenu={setOpenMenu} />}
      </div>
    </button>
  );
};

export default FileMenu;
