import React, { useState, useCallback } from 'react';
import {
  Bot,
  User,
  Copy,
  CheckCircle,
  Clock,
  Sparkles,
  Image as ImageIcon,
  ExternalLink
} from 'lucide-react';
import GroundedText from './GroundedText';
import { GroundingMetadata } from '../types/ragGrounding';

/**
 * 聊天消息接口
 */
interface ChatMessage {
  id: string;
  type: 'user' | 'assistant';
  content: string;
  timestamp: Date;
  status?: 'sending' | 'sent' | 'error';
  metadata?: {
    responseTime?: number;
    modelUsed?: string;
    sources?: Array<{
      title: string;
      uri?: string;
      content?: any;
    }>;
    grounding_metadata?: GroundingMetadata;
  };
}

/**
 * 增强聊天消息属性接口
 */
interface EnhancedChatMessageProps {
  /** 消息数据 */
  message: ChatMessage;
  /** 是否显示来源信息 */
  showSources?: boolean;
  /** 是否启用图片卡片 */
  enableImageCards?: boolean;
  /** 自定义样式类名 */
  className?: string;
}

/**
 * 增强聊天消息组件
 * 支持grounding文本高亮和图片卡片展示
 */
export const EnhancedChatMessage: React.FC<EnhancedChatMessageProps> = ({
  message,
  showSources = true,
  enableImageCards = true,
  className = ''
}) => {
  const [copied, setCopied] = useState(false);
  const [expandedSources, setExpandedSources] = useState(false);

  const isUser = message.type === 'user';
  const isAssistant = message.type === 'assistant';
  const groundingMetadata = message.metadata?.grounding_metadata;
  const sources = message.metadata?.sources || [];

  // 调试信息
  console.log('💬 EnhancedChatMessage - message:', message);
  console.log('💬 EnhancedChatMessage - groundingMetadata:', groundingMetadata);
  console.log('💬 EnhancedChatMessage - grounding_supports:', groundingMetadata?.grounding_supports);

  // 处理复制消息
  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(message.content);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (error) {
      console.error('复制失败:', error);
    }
  }, [message.content]);

  // 切换来源展开状态
  const toggleSources = useCallback(() => {
    setExpandedSources(prev => !prev);
  }, []);

  // 格式化时间
  const formatTime = useCallback((date: Date) => {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    });
  }, []);

  return (
    <div className={`flex ${isUser ? 'justify-end' : 'justify-start'} mb-4 ${className}`}>
      <div className={`flex max-w-[85%] ${isUser ? 'flex-row-reverse' : 'flex-row'}`}>
        {/* 头像 */}
        <div className={`flex-shrink-0 ${isUser ? 'ml-3' : 'mr-3'}`}>
          <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
            isUser 
              ? 'bg-gradient-to-br from-blue-500 to-blue-600 text-white' 
              : 'bg-gradient-to-br from-pink-500 to-purple-600 text-white'
          }`}>
            {isUser ? <User className="w-4 h-4" /> : <Bot className="w-4 h-4" />}
          </div>
        </div>

        {/* 消息内容 */}
        <div className={`flex flex-col ${isUser ? 'items-end' : 'items-start'}`}>
          {/* 消息气泡 */}
          <div className={`relative rounded-2xl px-4 py-3 shadow-sm ${
            isUser
              ? 'bg-gradient-to-br from-blue-500 to-blue-600 text-white'
              : 'bg-white border border-gray-200 text-gray-900'
          }`}>
            {/* 消息内容 */}
            <div className="space-y-2">
              {isAssistant && groundingMetadata ? (
                <GroundedText
                  text={message.content}
                  groundingMetadata={groundingMetadata}
                  enableImageCards={enableImageCards}
                  enableMarkdown={true}
                  highlightStyle="underline"
                  className=""
                />
              ) : (
                <div className="whitespace-pre-wrap">{message.content}</div>
              )}

              {/* 状态指示器 */}
              {message.status === 'sending' && (
                <div className="flex items-center space-x-2 text-sm opacity-70">
                  <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-current"></div>
                  <span>发送中...</span>
                </div>
              )}

              {message.status === 'error' && (
                <div className="text-red-500 text-sm">
                  发送失败，请重试
                </div>
              )}
            </div>

            {/* 操作按钮 */}
            <div className={`flex items-center justify-between mt-2 pt-2 border-t ${
              isUser ? 'border-blue-400' : 'border-gray-100'
            }`}>
              <div className="flex items-center space-x-2 text-xs opacity-70">
                <Clock className="w-3 h-3" />
                <span>{formatTime(message.timestamp)}</span>
                {message.metadata?.responseTime && (
                  <>
                    <span>•</span>
                    <span>{message.metadata.responseTime}ms</span>
                  </>
                )}
              </div>

              <div className="flex items-center space-x-1">
                {/* 复制按钮 */}
                <button
                  onClick={handleCopy}
                  className={`p-1 rounded transition-colors ${
                    isUser
                      ? 'hover:bg-blue-400 text-blue-100'
                      : 'hover:bg-gray-100 text-gray-500'
                  }`}
                  title="复制消息"
                >
                  {copied ? (
                    <CheckCircle className="w-3 h-3" />
                  ) : (
                    <Copy className="w-3 h-3" />
                  )}
                </button>

                {/* 来源按钮 */}
                {isAssistant && sources.length > 0 && showSources && (
                  <button
                    onClick={toggleSources}
                    className="p-1 rounded transition-colors hover:bg-gray-100 text-gray-500"
                    title={`查看来源 (${sources.length})`}
                  >
                    <ImageIcon className="w-3 h-3" />
                  </button>
                )}
              </div>
            </div>
          </div>

          {/* 来源信息 */}
          {isAssistant && sources.length > 0 && showSources && expandedSources && (
            <div className="mt-2 w-full">
              <div className="bg-gray-50 rounded-lg border border-gray-200 p-3">
                <div className="flex items-center justify-between mb-2">
                  <h4 className="text-sm font-medium text-gray-700 flex items-center">
                    <Sparkles className="w-4 h-4 mr-1 text-pink-500" />
                    参考来源 ({sources.length})
                  </h4>
                  <button
                    onClick={toggleSources}
                    className="text-xs text-gray-500 hover:text-gray-700"
                  >
                    收起
                  </button>
                </div>

                {/* 图片卡片网格布局 */}
                <div className="grid grid-cols-4 sm:grid-cols-6 gap-3">
                  {sources.map((source, index) => (
                    <div
                      key={index}
                      className="dynamic-card group cursor-pointer aspect-square overflow-hidden"
                    >
                      {/* 图片展示 */}
                      <div className="relative w-full h-full bg-gray-100">
                        {source.uri ? (
                          <div className="relative w-full h-full">
                            <img
                              src={source.uri}
                              alt={source.title || `图片 ${index + 1}`}
                              className="w-full h-full object-cover transition-all duration-500 group-hover:scale-105"
                              loading="lazy"
                              onError={(e) => {
                                const target = e.target as HTMLImageElement;
                                target.style.display = 'none';
                                target.parentElement?.querySelector('.error-placeholder')?.classList.remove('hidden');
                              }}
                            />

                            {/* 悬停时显示的操作按钮 */}
                            <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all duration-300 flex items-center justify-center">
                              <a
                                href={source.uri}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="opacity-0 group-hover:opacity-100 p-2 bg-white bg-opacity-90 hover:bg-opacity-100 text-gray-800 rounded-full transition-all duration-200"
                                title="查看原图"
                                onClick={(e) => e.stopPropagation()}
                              >
                                <ExternalLink className="w-4 h-4" />
                              </a>
                            </div>

                            {/* 错误占位符 */}
                            <div className="error-placeholder hidden absolute inset-0 bg-gray-100 flex items-center justify-center">
                              <div className="text-center">
                                <div className="w-8 h-8 bg-gray-300 rounded-full flex items-center justify-center mx-auto mb-1">
                                  <span className="text-gray-500 text-xs">!</span>
                                </div>
                                <span className="text-gray-400 text-xs">加载失败</span>
                              </div>
                            </div>
                          </div>
                        ) : (
                          <div className="w-full h-full flex items-center justify-center bg-gray-100">
                            <div className="text-center">
                              <div className="w-8 h-8 bg-gray-300 rounded-full flex items-center justify-center mx-auto mb-1">
                                <ImageIcon className="w-4 h-4 text-gray-500" />
                              </div>
                              <span className="text-gray-400 text-xs">暂无图片</span>
                            </div>
                          </div>
                        )}

                        {/* 图片标题覆盖层 */}
                        <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/60 to-transparent p-2">
                          <p className="text-white text-xs font-medium truncate">
                            {source.title || `图片 ${index + 1}`}
                          </p>
                          {source.content?.description && (
                            <p className="text-white/80 text-xs truncate">
                              {source.content.description}
                            </p>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* 模型信息 */}
          {isAssistant && message.metadata?.modelUsed && (
            <div className="mt-1 text-xs text-gray-400">
              由 {message.metadata.modelUsed} 生成
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default EnhancedChatMessage;
