/**
 * useFileMention Hook
 *
 * 管理文件提及的状态和逻辑
 */

import { useState, useCallback, useEffect, useRef } from 'react';
import { searchFiles } from '../api/client.js';
import type { FileSearchResult } from '../api/types.js';

interface UseFileMentionOptions {
  /** 是否启用 */
  enabled?: boolean;
  /** 搜索结果限制 */
  limit?: number;
  /** 防抖延迟 (ms) */
  debounceMs?: number;
}

interface UseFileMentionReturn {
  /** 是否显示文件菜单 */
  isOpen: boolean;
  /** 搜索结果 */
  files: FileSearchResult[];
  /** 是否正在加载 */
  isLoading: boolean;
  /** 当前选中索引 */
  selectedIndex: number;
  /** 设置选中索引 */
  setSelectedIndex: (index: number) => void;
  /** 检查并处理 @ 触发 */
  checkTrigger: (value: string, cursorPos: number) => void;
  /** 选择文件后获取替换文本 */
  getReplacementText: (file: FileSearchResult) => string;
  /** 关闭菜单 */
  close: () => void;
  /** @ 符号在输入中的位置 */
  mentionStart: number | null;
}

export function useFileMention(options: UseFileMentionOptions = {}): UseFileMentionReturn {
  const { enabled = true, limit = 10, debounceMs = 150 } = options;

  const [isOpen, setIsOpen] = useState(false);
  const [files, setFiles] = useState<FileSearchResult[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [mentionStart, setMentionStart] = useState<number | null>(null);

  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  // 搜索文件
  const search = useCallback(
    async (query: string) => {
      setIsLoading(true);
      try {
        const result = await searchFiles(query, limit, 'all');
        if (result.success) {
          setFiles(result.data.files);
          setSelectedIndex(0);
        }
      } catch (error) {
        console.error('File search error:', error);
        setFiles([]);
      } finally {
        setIsLoading(false);
      }
    },
    [limit]
  );

  // 检查 @ 触发
  const checkTrigger = useCallback(
    (value: string, cursorPos: number) => {
      if (!enabled) return;

      // 找到光标前最近的 @ 符号
      const beforeCursor = value.slice(0, cursorPos);
      const lastAtIndex = beforeCursor.lastIndexOf('@');

      if (lastAtIndex === -1) {
        setIsOpen(false);
        setMentionStart(null);
        return;
      }

      // 检查 @ 前面是否为空白或行首
      const charBefore = lastAtIndex > 0 ? beforeCursor[lastAtIndex - 1] : '';
      if (charBefore && !/\s/.test(charBefore)) {
        setIsOpen(false);
        setMentionStart(null);
        return;
      }

      // 检查 @ 后面到光标之间是否有空格（如果有，说明已经完成输入）
      const afterAt = beforeCursor.slice(lastAtIndex + 1);
      if (afterAt.includes(' ')) {
        setIsOpen(false);
        setMentionStart(null);
        return;
      }

      // 触发文件搜索
      setIsOpen(true);
      setMentionStart(lastAtIndex);

      // 防抖搜索
      if (debounceRef.current) {
        clearTimeout(debounceRef.current);
      }
      debounceRef.current = setTimeout(() => {
        search(afterAt);
      }, debounceMs);
    },
    [enabled, search, debounceMs]
  );

  // 获取替换文本
  const getReplacementText = useCallback((file: FileSearchResult): string => {
    // 返回 @filepath 格式（用户友好的显示格式）
    return `@${file.path} `;
  }, []);

  // 关闭菜单
  const close = useCallback(() => {
    setIsOpen(false);
    setMentionStart(null);
  }, []);

  // 清理
  useEffect(() => {
    return () => {
      if (debounceRef.current) {
        clearTimeout(debounceRef.current);
      }
    };
  }, []);

  return {
    isOpen,
    files,
    isLoading,
    selectedIndex,
    setSelectedIndex,
    checkTrigger,
    getReplacementText,
    close,
    mentionStart,
  };
}
