'use client';

import React, { useRef, useEffect } from 'react';
import { cn } from '@/lib/utils';
import { MentionInputProps } from './types';
import { parseValue } from './utils';
import { useCursorPosition } from './useCursorPosition';
import { useMentionInput } from './useMentionInput';
import { usePopoverPosition } from './usePopoverPosition';
import { MentionPopover } from './MentionPopover';

/**
 * MentionInput 组件
 * 支持 @ 提及功能的富文本输入框
 */
const MentionInput: React.FC<MentionInputProps> = ({
  value = '',
  onChange,
  onEnter,
  options,
  placeholder = '输入 @ 来提及...',
  className,
  mentionClassName,
  popoverClassName,
  popoverItemClassName,
  popoverPlacement = 'auto',
  popoverItemRender,
  disabled = false,
  maxHeight = '200px',
}) => {
  const inputRef = useRef<HTMLDivElement>(null);
  const popoverRef = useRef<HTMLDivElement>(null);
  const isComposingRef = useRef(false);

  // 光标位置管理
  const { getCursorTextPosition, setCursorTextPosition } = useCursorPosition(inputRef);

  // 提及输入核心逻辑
  const {
    showPopover,
    filteredOptions,
    selectedIndex,
    setSelectedIndex,
    popoverPosition,
    setPopoverPosition,
    handleInput,
    insertMention,
    handleKeyDown,
  } = useMentionInput({
    value,
    options,
    onChange,
    onEnter,
    popoverPlacement,
    inputRef,
    isComposingRef,
    getCursorTextPosition,
    setCursorTextPosition,
  });

  // 弹出框位置调整
  usePopoverPosition({
    showPopover,
    popoverRef,
    inputRef,
    popoverPosition,
    setPopoverPosition,
    filteredOptionsLength: filteredOptions.length,
  });

  // 更新显示内容
  useEffect(() => {
    if (!inputRef.current) return;

    // 获取当前光标位置（在清空之前）
    let currentPosition = 0;
    try {
      const selection = window.getSelection();
      if (
        selection &&
        selection.rangeCount > 0 &&
        inputRef.current.contains(selection.anchorNode)
      ) {
        currentPosition = getCursorTextPosition();
      }
    } catch (e) {
      console.warn('Failed to get cursor position:', e);
    }

    // 清空并重建内容
    inputRef.current.innerHTML = '';

    if (!value) {
      // 空值时不添加任何内容，让 CSS placeholder 处理
      return;
    }

    const segments = parseValue(value);
    segments.forEach((segment) => {
      if (segment.type === 'mention') {
        const span = document.createElement('span');
        span.className = cn(
          'inline-block px-1 rounded bg-blue-100 text-blue-600 font-medium',
          mentionClassName
        );
        span.setAttribute('data-mention', segment.value || '');
        span.contentEditable = 'false';
        span.textContent = `@${segment.label}`;
        inputRef.current?.appendChild(span);
      } else {
        const textNode = document.createTextNode(segment.content);
        inputRef.current?.appendChild(textNode);
      }
    });

    // 恢复光标位置
    if (currentPosition > 0) {
      try {
        // 使用 requestAnimationFrame 确保 DOM 更新完成
        requestAnimationFrame(() => {
          setCursorTextPosition(currentPosition);
        });
      } catch (e) {
        console.warn('Failed to set cursor position:', e);
      }
    }
  }, [value, mentionClassName, getCursorTextPosition, setCursorTextPosition]);

  return (
    <div className="relative">
      <div
        ref={inputRef}
        contentEditable={!disabled}
        onInput={handleInput}
        onKeyDown={handleKeyDown}
        onCompositionStart={() => {
          isComposingRef.current = true;
        }}
        onCompositionEnd={() => {
          isComposingRef.current = false;
          handleInput();
        }}
        data-placeholder={placeholder}
        className={cn(
          'w-full px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent overflow-y-auto bg-transparent',
          'empty:before:content-[attr(data-placeholder)] empty:before:text-gray-400 empty:before:pointer-events-none',
          disabled && 'cursor-not-allowed opacity-50',
          className
        )}
        style={{ maxHeight }}
        suppressContentEditableWarning
      />

      {showPopover && (
        <MentionPopover
          popoverRef={popoverRef}
          filteredOptions={filteredOptions}
          selectedIndex={selectedIndex}
          setSelectedIndex={setSelectedIndex}
          popoverPosition={popoverPosition}
          insertMention={insertMention}
          popoverClassName={popoverClassName}
          popoverItemClassName={popoverItemClassName}
          popoverItemRender={popoverItemRender}
        />
      )}
    </div>
  );
};

export default MentionInput;
export * from './types';
