import React, { useState, useCallback, useRef, useEffect } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { GroundingMetadata, GroundingSupport, GroundingSource } from '../types/ragGrounding';
import ImageCard from './ImageCard';
import ImagePreviewModal from './ImagePreviewModal';
import useImageDownload from '../hooks/useImageDownload';

/**
 * 文字片段信息
 */
interface TextSegment {
  /** 片段文本 */
  text: string;
  /** 开始位置 */
  startIndex: number;
  /** 结束位置 */
  endIndex: number;
  /** 关联的grounding支持 */
  groundingSupport?: GroundingSupport;
  /** 关联的来源 */
  sources?: GroundingSource[];
}

/**
 * Grounded文本属性接口
 */
interface GroundedTextProps {
  /** 原始文本内容 */
  text: string;
  /** Grounding元数据 */
  groundingMetadata?: GroundingMetadata;
  /** 自定义样式类名 */
  className?: string;
  /** 是否启用图片卡片 */
  enableImageCards?: boolean;
  /** 高亮样式 */
  highlightStyle?: 'underline' | 'background' | 'border';
  /** 是否启用 Markdown 渲染 */
  enableMarkdown?: boolean;
}

/**
 * Grounded文本组件
 * 支持文字片段高亮和相关图片卡片展示
 */
export const GroundedText: React.FC<GroundedTextProps> = ({
  text,
  groundingMetadata,
  className = '',
  enableImageCards = true,
  highlightStyle = 'underline',
  enableMarkdown = true
}) => {
  const [hoveredSegment, setHoveredSegment] = useState<TextSegment | null>(null);
  const [clickedSegment, setClickedSegment] = useState<TextSegment | null>(null);
  const [cardPosition, setCardPosition] = useState<{ top: number; left: number } | null>(null);
  const [previewSource, setPreviewSource] = useState<GroundingSource | null>(null);
  const [isCardHovered, setIsCardHovered] = useState(false);
  const [isPersistent, setIsPersistent] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const hideTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const { downloadImage, isDownloadable } = useImageDownload();

  // 清理定时器
  useEffect(() => {
    return () => {
      if (hideTimeoutRef.current) {
        clearTimeout(hideTimeoutRef.current);
      }
    };
  }, []);

  // 解析文本片段
  const textSegments = React.useMemo(() => {
    console.log('🔍 GroundedText - groundingMetadata:', groundingMetadata);
    console.log('🔍 GroundedText - grounding_supports:', groundingMetadata?.grounding_supports);

    if (!groundingMetadata?.grounding_supports) {
      console.log('❌ 没有 grounding_supports 数据');
      return [{ text, startIndex: 0, endIndex: text.length }];
    }

    const segments: TextSegment[] = [];
    const supports = groundingMetadata.grounding_supports;
    const sources = groundingMetadata.sources;

    // 按开始位置排序
    const sortedSupports = [...supports].sort((a, b) => a.segment.endIndex - b.segment.startIndex);

    let currentIndex = 0;

    for (const support of sortedSupports) {
      const { startIndex: start_index, endIndex: end_index, text: segmentText } = support.segment;

      // 添加前面的普通文本
      if (currentIndex < start_index) {
        segments.push({
          text: text.slice(currentIndex, start_index),
          startIndex: currentIndex,
          endIndex: start_index
        });
      }

      // 获取关联的来源
      const relatedSources = (support.groundingChunkIndices || [])
        .map((index: number) => sources[index])
        .filter(Boolean);

      console.log('📝 处理片段:', {
        text: segmentText,
        groundingChunkIndices: support.groundingChunkIndices,
        relatedSources: relatedSources.length,
        sources: relatedSources
      });

      // 添加高亮片段
      segments.push({
        text: segmentText,
        startIndex: start_index,
        endIndex: end_index,
        groundingSupport: support,
        sources: relatedSources
      });

      currentIndex = end_index;
    }

    // 添加剩余的普通文本
    if (currentIndex < text.length) {
      segments.push({
        text: text.slice(currentIndex),
        startIndex: currentIndex,
        endIndex: text.length
      });
    }

    return segments;
  }, [text, groundingMetadata]);

  // 清除隐藏定时器
  const clearHideTimeout = useCallback(() => {
    if (hideTimeoutRef.current) {
      clearTimeout(hideTimeoutRef.current);
      hideTimeoutRef.current = null;
    }
  }, []);

  // 隐藏卡片
  const hideCard = useCallback(() => {
    if (!isPersistent) {
      setHoveredSegment(null);
      setCardPosition(null);
      setIsCardHovered(false);
    }
  }, [isPersistent]);

  // 延迟隐藏卡片
  const scheduleHideCard = useCallback(() => {
    if (isPersistent) return; // 如果是持久显示，不隐藏

    clearHideTimeout();
    hideTimeoutRef.current = setTimeout(() => {
      if (!isCardHovered) {
        hideCard();
      }
    }, 150); // 150ms 延迟，给用户时间移动到卡片上
  }, [clearHideTimeout, hideCard, isCardHovered, isPersistent]);

  // 显示卡片
  const showCard = useCallback((segment: TextSegment, event: React.MouseEvent, persistent = false) => {
    console.log('🎯 showCard 调用:', {
      hasGrounding: !!segment.groundingSupport,
      sourcesLength: segment.sources?.length,
      enableImageCards,
      persistent
    });

    if (!segment.groundingSupport || !segment.sources?.length || !enableImageCards) {
      console.log('❌ showCard 条件不满足');
      return;
    }

    clearHideTimeout();

    const rect = event.currentTarget.getBoundingClientRect();
    const containerRect = containerRef.current?.getBoundingClientRect();

    if (containerRect) {
      setCardPosition({
        top: rect.bottom - containerRect.top + 8,
        left: rect.left - containerRect.left
      });
    }

    if (persistent) {
      setClickedSegment(segment);
      setIsPersistent(true);
    } else {
      setHoveredSegment(segment);
    }
  }, [enableImageCards, clearHideTimeout]);

  // 处理鼠标悬停文字
  const handleMouseEnter = useCallback((segment: TextSegment, event: React.MouseEvent) => {
    console.log('🖱️ 鼠标悬停:', {
      text: segment.text,
      hasGrounding: !!segment.groundingSupport,
      sourcesCount: segment.sources?.length || 0,
      isPersistent
    });

    if (isPersistent) return; // 如果已经是持久显示，悬停不生效
    showCard(segment, event, false);
  }, [isPersistent, showCard]);

  // 处理鼠标离开文字
  const handleMouseLeave = useCallback(() => {
    scheduleHideCard();
  }, [scheduleHideCard]);

  // 处理点击文字
  const handleClick = useCallback((segment: TextSegment, event: React.MouseEvent) => {
    event.preventDefault();
    event.stopPropagation();

    // 如果点击的是同一个片段，切换显示状态
    if (clickedSegment === segment && isPersistent) {
      setIsPersistent(false);
      setClickedSegment(null);
      hideCard();
    } else {
      // 显示新的片段
      showCard(segment, event, true);
    }
  }, [clickedSegment, isPersistent, showCard, hideCard]);

  // 处理鼠标进入卡片
  const handleCardMouseEnter = useCallback(() => {
    clearHideTimeout();
    setIsCardHovered(true);
  }, [clearHideTimeout]);

  // 处理鼠标离开卡片
  const handleCardMouseLeave = useCallback(() => {
    setIsCardHovered(false);
    scheduleHideCard();
  }, [scheduleHideCard]);

  // 处理图片下载
  const handleDownload = useCallback(async (source: GroundingSource) => {
    try {
      const result = await downloadImage(source, {
        showSaveDialog: true
      });

      if (result.success) {
        console.log('图片下载成功:', result.filePath);
      } else {
        console.error('图片下载失败:', result.error);
      }
    } catch (error) {
      console.error('下载过程中出错:', error);
    }
  }, [downloadImage]);

  // 处理查看大图
  const handleViewLarge = useCallback((source: GroundingSource) => {
    setPreviewSource(source);
  }, []);

  // 关闭预览
  const handleClosePreview = useCallback(() => {
    setPreviewSource(null);
  }, []);

  // 关闭卡片
  const handleCloseCard = useCallback(() => {
    setIsPersistent(false);
    setClickedSegment(null);
    setHoveredSegment(null);
    setCardPosition(null);
    setIsCardHovered(false);
  }, []);

  // 获取高亮样式
  const getHighlightClass = useCallback((hasGrounding: boolean) => {
    if (!hasGrounding) return '';

    switch (highlightStyle) {
      case 'underline':
        return 'border-b-2 border-pink-300 hover:border-pink-500 cursor-pointer';
      case 'background':
        return 'bg-pink-50 hover:bg-pink-100 cursor-pointer rounded px-1';
      case 'border':
        return 'border border-pink-200 hover:border-pink-400 cursor-pointer rounded px-1';
      default:
        return 'border-b-2 border-pink-300 hover:border-pink-500 cursor-pointer';
    }
  }, [highlightStyle]);

  // 渲染内容（支持 Markdown 或纯文本）
  const renderContent = useCallback(() => {
    if (!enableMarkdown) {
      // 纯文本模式
      return (
        <div className="leading-relaxed">
          {textSegments.map((segment, index) => {
            const hasGrounding = !!(segment.groundingSupport && segment.sources?.length);
            const isActive = clickedSegment === segment && isPersistent;

            return (
              <span
                key={index}
                className={`transition-all duration-200 ${getHighlightClass(hasGrounding)} ${
                  isActive ? 'bg-pink-100 border-pink-400' : ''
                }`}
                onMouseEnter={hasGrounding ? (e) => handleMouseEnter(segment, e) : undefined}
                onMouseLeave={hasGrounding ? handleMouseLeave : undefined}
                onClick={hasGrounding ? (e) => handleClick(segment, e) : undefined}
                title={hasGrounding ? `点击查看相关图片 (${segment.sources?.length} 张)` : undefined}
              >
                {segment.text}
              </span>
            );
          })}
        </div>
      );
    }

    // Markdown 模式 - 暂时使用纯文本渲染以保持 grounding 功能
    // TODO: 未来需要实现更复杂的 Markdown + Grounding 集成
    return (
      <div className="prose prose-sm max-w-none">
        <div className="leading-relaxed whitespace-pre-wrap">
          {textSegments.map((segment, index) => {
            const hasGrounding = !!(segment.groundingSupport && segment.sources?.length);
            const isActive = clickedSegment === segment && isPersistent;

            return (
              <span
                key={index}
                className={`transition-all duration-200 ${getHighlightClass(hasGrounding)} ${
                  isActive ? 'bg-pink-100 border-pink-400' : ''
                }`}
                onMouseEnter={hasGrounding ? (e) => handleMouseEnter(segment, e) : undefined}
                onMouseLeave={hasGrounding ? handleMouseLeave : undefined}
                onClick={hasGrounding ? (e) => handleClick(segment, e) : undefined}
                title={hasGrounding ? `点击查看相关图片 (${segment.sources?.length} 张)` : undefined}
              >
                <>
                  {enableMarkdown ? (
                    <ReactMarkdown
                      remarkPlugins={[remarkGfm]}
                      components={{
                        p: ({ children }) => <>{children}</>,
                        h1: ({ children }) => <strong className="text-lg font-bold">{children}</strong>,
                        h2: ({ children }) => <strong className="text-base font-semibold">{children}</strong>,
                        h3: ({ children }) => <strong className="font-medium">{children}</strong>,
                        ul: ({ children }) => <span className="inline">{children}</span>,
                        ol: ({ children }) => <span className="inline">{children}</span>,
                        li: ({ children }) => <span className="inline">• {children} </span>,
                        strong: ({ children }) => <strong>{children}</strong>,
                        em: ({ children }) => <em>{children}</em>,
                        code: ({ children }) => <code className="bg-gray-100 px-1 py-0.5 rounded text-sm">{children}</code>,
                        blockquote: ({ children }) => <span className="italic text-gray-600">{children}</span>,
                      }}
                    >
                      {segment.text}
                    </ReactMarkdown>
                  ) : (
                    segment.text
                  )}

                  {/* 素材引用数量标注 - 使用CSS伪元素样式 */}
                  {hasGrounding && segment.sources && segment.sources.length > 0 && (
                    <span
                      className="text-xs text-gray-400 font-normal align-super leading-none"
                      style={{
                        fontSize: '0.6em',
                        verticalAlign: 'super',
                        lineHeight: 0,
                        marginLeft: '1px'
                      }}
                    >
                      {segment.sources.length}
                    </span>
                  )}
                </>
              </span>
            );
          })}
        </div>
      </div>
    );
  }, [enableMarkdown, textSegments, clickedSegment, isPersistent, getHighlightClass, handleMouseEnter, handleMouseLeave, handleClick, text]);

  return (
    <div ref={containerRef} className={`relative ${className}`}>
      {/* 渲染内容 */}
      {renderContent()}

      {/* 图片卡片 */}
      {(() => {
        const displaySegment = isPersistent ? clickedSegment : hoveredSegment;
        return displaySegment && displaySegment.sources && cardPosition && (
          <div
            className="absolute z-50"
            style={{
              top: cardPosition.top,
              left: cardPosition.left
            }}
            onMouseEnter={handleCardMouseEnter}
            onMouseLeave={handleCardMouseLeave}
          >
            {/* 显示第一张相关图片 */}
            {displaySegment.sources[0] && (
              <ImageCard
                source={displaySegment.sources[0]}
                showDetails={true}
                onClose={isPersistent ? handleCloseCard : hideCard}
                onDownload={isDownloadable(displaySegment.sources[0]) ? handleDownload : undefined}
                onViewLarge={handleViewLarge}
                className={`shadow-xl border-2 ${
                  isPersistent ? 'border-pink-400' : 'border-pink-200'
                }`}
              />
            )}

            {/* 如果有多张图片，显示指示器 */}
            {displaySegment.sources.length > 1 && (
              <div className="absolute -bottom-2 left-1/2 transform -translate-x-1/2">
                <div className={`text-white text-xs px-2 py-1 rounded-full ${
                  isPersistent ? 'bg-pink-600' : 'bg-pink-500'
                }`}>
                  +{displaySegment.sources.length - 1} 张图片
                </div>
              </div>
            )}

            {/* 持久显示时的固定指示器 */}
            {isPersistent && (
              <div className="absolute -top-2 -right-2">
                <div className="w-3 h-3 bg-pink-500 rounded-full border-2 border-white shadow-sm"></div>
              </div>
            )}
          </div>
        );
      })()}

      {/* 图片预览模态框 */}
      <ImagePreviewModal
        isOpen={!!previewSource}
        source={previewSource}
        onClose={handleClosePreview}
        onDownload={previewSource && isDownloadable(previewSource) ? handleDownload : undefined}
      />
    </div>
  );
};

export default GroundedText;
