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";

const FileMenu: React.FC = () => {
  const [openMenu, setOpenMenu] = useState(false);
  const containerRef = useRef<HTMLButtonElement>(null);
  let clickTimeout: NodeJS.Timeout | null = null;

  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);
  }, []);

  // project
  const [projectName, setProjectName] = useState("Demo Project");

  // Load project name from localStorage on mount
  useEffect(() => {
    const savedName = localStorage.getItem("projectName");
    if (savedName) {
      setProjectName(savedName);
    }
  }, []);

  const handleProjectRename = (newName: string) => {
    setProjectName(newName);
    localStorage.setItem("projectName", newName);
  };

  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;
