import React, { useEffect } from "react";
import { FiFile, FiFolder, FiEdit3, FiTrash2 } from "react-icons/fi";

const MenuItem: React.FC<{
  onClick: () => void;
  danger?: boolean;
  children: React.ReactNode;
}> = ({ onClick, danger, children }) => (
  <div
    onClick={onClick}
    style={{
      padding: "8px 16px",
      cursor: "pointer",
      color: danger ? "#f48771" : "#cccccc",
      fontSize: "13px",
      transition: "background-color 0.1s",
      display: "flex",
      alignItems: "center",
      gap: "10px",
    }}
    onMouseEnter={(e) => {
      e.currentTarget.style.backgroundColor = "#2a2d2e";
    }}
    onMouseLeave={(e) => {
      e.currentTarget.style.backgroundColor = "transparent";
    }}
  >
    {children}
  </div>
);

interface ContextMenuProps {
  x: number;
  y: number;
  onClose: () => void;
  onNewFile: () => void;
  onNewFolder: () => void;
  onRename: () => void;
  onDelete: () => void;
  hasNode: boolean;
}

export const ContextMenu: React.FC<ContextMenuProps> = ({
  x,
  y,
  onClose,
  onNewFile,
  onNewFolder,
  onRename,
  onDelete,
  hasNode,
}) => {
  useEffect(() => {
    const handleClick = () => onClose();
    document.addEventListener("click", handleClick);
    return () => document.removeEventListener("click", handleClick);
  }, [onClose]);

  return (
    <div
      style={{
        position: "fixed",
        top: y,
        left: x,
        backgroundColor: "#252526",
        border: "1px solid #3e3e42",
        borderRadius: "6px",
        boxShadow: "0 4px 12px rgba(0,0,0,0.4)",
        zIndex: 1000,
        minWidth: "180px",
        overflow: "hidden",
      }}
    >
      <MenuItem onClick={onNewFile}>
        <FiFile /> New File
      </MenuItem>
      <MenuItem onClick={onNewFolder}>
        <FiFolder /> New Folder
      </MenuItem>
      {hasNode && (
        <>
          <div
            style={{
              height: "1px",
              backgroundColor: "#3e3e42",
              margin: "4px 0",
            }}
          />
          <MenuItem onClick={onRename}>
            <FiEdit3 /> Rename
          </MenuItem>
          <MenuItem onClick={onDelete} danger>
            <FiTrash2 /> Delete
          </MenuItem>
        </>
      )}
    </div>
  );
};
