import { PopoverCommonProps } from '@wix/design-system';
import { useFilterRenderingContext } from '../components/FilterRenderingContext';
import { useRef, useState } from 'react';
import { addResizeObserver } from '@wix/bex-core';

export function useWindowFlipPopoverProps({
  popoverProps,
}: {
  popoverProps?: PopoverCommonProps;
}) {
  const { location } = useFilterRenderingContext();
  const inputRef = useRef<HTMLInputElement | null>();

  const [dropdownWidth, setDropdownWidth] = useState<number>();

  addResizeObserver(inputRef.current, () => {
    if (inputRef.current) {
      setDropdownWidth(inputRef.current.width);
    }
  });

  return {
    inputRef,
    windowFlipPopoverProps: {
      appendTo: 'window' as const,
      flip: true,
      fixed: false,
      maxWidth: dropdownWidth,
      ...(location === 'modal' && { zIndex: 5001 }),
      ...popoverProps,
    },
  };
}
