import React, { useRef } from "react";
import { useMenuPosition } from "./hooks/useMenuPosition";
import Portal from "../Portal";

export default function Dropdown({
  children,
  dropDownPortalClassName = "",
  isOpen,
  target,
  onClose,
  disabled,
  containerRef,
  menuRef: externalMenuRef,
  withPortal,
  portalContainer = document.body,
  dropdownButtonRef,
  dropdownPosition, // 'top' | 'bottom' | undefined
  isKeyboardNav,
}) {
  const internalMenuRef = useRef(null);
  // Use external menuRef if provided, otherwise use internal
  const menuRef = externalMenuRef || internalMenuRef;

  // Use the new positioning hook
  const { menuStyle, placement: computedPlacement } = useMenuPosition({
    isOpen: isOpen && !disabled,
    triggerRef: dropdownButtonRef,
    menuRef,
    withPortal,
    dropdownPosition,
  });

  const menuContent = (
    <>
      <div
        className={`ia-select-container-v3-styled-menu ${dropDownPortalClassName}`}
        style={{
          ...menuStyle,
          // Ensure position is set correctly based on mode
          position: withPortal ? "absolute" : undefined,
          marginTop: withPortal ? isKeyboardNav ? "0" : "-4px" : isKeyboardNav ? "4px" : "0",
        }}
        ref={menuRef}
        data-placement={computedPlacement}
      >
        {children}
      </div>
      <div className="ia-select-container-v3-blanket" onClick={onClose} />
    </>
  );

  return (
    <div className="ia-select-container-v3">
      {target}
      {!disabled && isOpen ? (
        <>
          {withPortal ? (
            <Portal container={portalContainer}>{menuContent}</Portal>
          ) : (
            menuContent
          )}
        </>
      ) : null}
    </div>
  );
}
