'use client';

import React, { RefObject, useEffect } from 'react';
import { cn } from '@/lib/utils';
import { MentionOption, PopoverPosition } from './types';

interface MentionPopoverProps {
  popoverRef: RefObject<HTMLDivElement | null>;
  filteredOptions: MentionOption[];
  selectedIndex: number;
  setSelectedIndex: (index: number) => void;
  popoverPosition: PopoverPosition;
  insertMention: (option: MentionOption) => void;
  popoverClassName?: string;
  popoverItemClassName?: string;
  popoverItemRender?: (option: MentionOption, isSelected: boolean) => React.ReactNode;
}

/**
 * 提及弹出框组件
 */
export const MentionPopover: React.FC<MentionPopoverProps> = ({
  popoverRef,
  filteredOptions,
  selectedIndex,
  setSelectedIndex,
  popoverPosition,
  insertMention,
  popoverClassName,
  popoverItemClassName,
  popoverItemRender,
}) => {
  // 滚动选中项到可见区域
  useEffect(() => {
    if (popoverRef.current) {
      const selectedElement = popoverRef.current.querySelector(`[data-index="${selectedIndex}"]`);
      if (selectedElement) {
        selectedElement.scrollIntoView({
          block: 'nearest',
          behavior: 'smooth',
        });
      }
    }
  }, [selectedIndex, popoverRef]);

  if (filteredOptions.length === 0) {
    return null;
  }

  return (
    <div
      ref={popoverRef}
      className={cn(
        'absolute z-50 max-h-60 overflow-auto rounded-md border border-gray-200 bg-white shadow-lg',
        popoverClassName
      )}
      style={{
        [popoverPosition.placement === 'bottom' ? 'top' : 'bottom']:
          popoverPosition.placement === 'bottom'
            ? popoverPosition.top
            : `calc(100% - ${popoverPosition.top}px)`,
        left: popoverPosition.left,
        minWidth: '200px',
      }}
    >
      {filteredOptions.map((option, index) => {
        const isSelected = index === selectedIndex;

        // 使用自定义渲染器或默认渲染
        const content = popoverItemRender ? popoverItemRender(option, isSelected) : `@${option.label}`;

        return (
          <div
            key={option.value}
            data-index={index}
            className={cn(
              'cursor-pointer px-4 py-2 text-sm hover:bg-gray-100',
              isSelected && 'bg-blue-50 text-blue-600',
              popoverItemClassName
            )}
            onClick={() => insertMention(option)}
            onMouseEnter={() => setSelectedIndex(index)}
          >
            {content}
          </div>
        );
      })}
    </div>
  );
};

