import { useCallback, useRef, useState } from "react";
import { View } from "react-native";

type DropdownPosition = {
  top: number;
  left: number;
  width: number;
};

/**
 * Hook for managing dropdown position measurement and visibility.
 * @param widthMultiplier - Multiply the measured width (default: 1)
 */
export const useDropdownPosition = (widthMultiplier = 1) => {
  const [visible, setVisible] = useState(false);
  const [position, setPosition] = useState<DropdownPosition>({
    top: 0,
    left: 0,
    width: 0,
  });
  const ref = useRef<View>(null);

  const open = useCallback(() => {
    ref.current?.measureInWindow((x, y, width, height) => {
      setPosition({
        top: y + height,
        left: x,
        width: width * widthMultiplier,
      });
      setVisible(true);
    });
  }, [widthMultiplier]);

  const close = useCallback(() => setVisible(false), []);

  return { ref, visible, position, open, close };
};
