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

  return (
    <button
      className="project-dropdowm-container"
      ref={containerRef}
      onClick={handleClick}
    >
      <div className="project-name">
        <div className="icon">
          <ProjectIcon />
        </div>
        <RenameInput value="untitled" />
      </div>
      <div className="more-options-button">
        <ArrowIcon />
        {openMenu && <MenuBar setOpenMenu={setOpenMenu} />}
      </div>
    </button>
  );
};

export default FileMenu;
