import { RefObject, useEffect } from 'react';
import { PopoverPosition } from './types';

interface UsePopoverPositionProps {
  showPopover: boolean;
  popoverRef: RefObject<HTMLDivElement | null>;
  inputRef: RefObject<HTMLDivElement | null>;
  popoverPosition: PopoverPosition;
  setPopoverPosition: React.Dispatch<React.SetStateAction<PopoverPosition>>;
  filteredOptionsLength: number;
}

/**
 * 弹出框位置调整 Hook
 * 确保弹出框始终在视口内显示
 */
export function usePopoverPosition({
  showPopover,
  popoverRef,
  inputRef,
  popoverPosition,
  setPopoverPosition,
  filteredOptionsLength,
}: UsePopoverPositionProps) {
  useEffect(() => {
    if (showPopover && popoverRef.current && inputRef.current) {
      // 使用 requestAnimationFrame 确保 DOM 已经渲染
      requestAnimationFrame(() => {
        if (!popoverRef.current || !inputRef.current) return;

        const popover = popoverRef.current;
        const input = inputRef.current;

        // 获取弹出框的实际尺寸
        const popoverRect = popover.getBoundingClientRect();
        const inputRect = input.getBoundingClientRect();

        // 当前弹出框的绝对位置
        const absoluteLeft = popoverRect.left;
        const absoluteRight = popoverRect.right;

        const viewportWidth = window.innerWidth;
        const padding = 8; // 安全边距

        let adjustmentNeeded = false;
        let newLeft = popoverPosition.left;

        // 检查右边界
        if (absoluteRight > viewportWidth - padding) {
          newLeft = viewportWidth - inputRect.left - popoverRect.width - padding;
          adjustmentNeeded = true;
        }

        // 检查左边界
        if (absoluteLeft < padding) {
          newLeft = padding - inputRect.left;
          adjustmentNeeded = true;
        }

        // 如果位置需要调整，更新状态
        if (adjustmentNeeded && Math.abs(newLeft - popoverPosition.left) > 1) {
          setPopoverPosition((prev) => ({
            ...prev,
            left: Math.max(0, newLeft),
          }));
        }
      });
    }
  }, [showPopover, filteredOptionsLength]);
}

/**
 * 计算弹出框初始位置
 */
export function calculatePopoverPosition(
  cursorRect: DOMRect,
  inputRect: DOMRect,
  placement: 'auto' | 'top' | 'bottom'
): PopoverPosition {
  let finalPlacement: 'top' | 'bottom' = 'bottom';

  if (placement === 'top') {
    finalPlacement = 'top';
  } else if (placement === 'bottom') {
    finalPlacement = 'bottom';
  } else {
    // auto: 自动检测，优先向上弹出（适合输入框在底部的场景）
    const viewportHeight = window.innerHeight;
    const spaceBelow = viewportHeight - cursorRect.bottom;
    const spaceAbove = cursorRect.top;
    const popoverEstimatedHeight = 240; // max-h-60 约等于 240px

    // 如果下方空间不足且上方空间充足，则向上弹出
    if (spaceBelow < popoverEstimatedHeight && spaceAbove > popoverEstimatedHeight) {
      finalPlacement = 'top';
    } else {
      finalPlacement = 'bottom';
    }
  }

  // 计算左右位置，确保不超出视口
  const viewportWidth = window.innerWidth;
  const popoverMinWidth = 200;
  let leftPosition = cursorRect.left - inputRect.left;

  // 检查右边界
  const absoluteLeft = cursorRect.left;
  if (absoluteLeft + popoverMinWidth > viewportWidth) {
    // 超出右边界，调整到左边
    leftPosition = viewportWidth - inputRect.left - popoverMinWidth - 8; // 8px 安全边距
  }

  // 检查左边界
  if (absoluteLeft < 8) {
    // 超出左边界，调整到 8px
    leftPosition = 8 - inputRect.left;
  }

  return {
    top:
      finalPlacement === 'bottom'
        ? cursorRect.bottom - inputRect.top + 4
        : cursorRect.top - inputRect.top - 4,
    left: leftPosition,
    placement: finalPlacement,
  };
}

