import React, { useState, useCallback, useRef, useEffect } from 'react';
import { LLMChatProps, SearchRequest } from '../../types/outfitSearch';
import { OutfitCard } from './OutfitCard';
import OutfitSearchService from '../../services/outfitSearchService';
import { MessageCircle, Send, Trash2, Bot, User, AlertCircle, Sparkles, Search } from 'lucide-react';

/**
 * LLM聊天组件
 * 遵循 Tauri 开发规范的组件设计原则
 */
export const LLMChat: React.FC<LLMChatProps> = ({
  onAskLLM,
  onSearch,
  response,
  isLoading,
  error,
}) => {
  const [input, setInput] = useState('');
  const [chatHistory, setChatHistory] = useState<Array<{
    type: 'user' | 'assistant';
    content: string;
    timestamp: Date;
    relatedResults?: any[];
    searchSuggestions?: string[];
  }>>([]);
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const chatContainerRef = useRef<HTMLDivElement>(null);

  // 提取搜索关键词
  const extractSearchKeywords = useCallback((text: string): string[] => {
    const keywords: string[] = [];
    const lowerText = text.toLowerCase();

    // 常见的搜索关键词模式
    const patterns = [
      /(?:想要|寻找|搜索|找|推荐).*?([\u4e00-\u9fa5]+(?:装|衣|裤|鞋|包|帽))/g,
      /(?:休闲|正式|运动|街头|优雅|可爱|性感|简约|复古|时尚)/g,
      /(?:春|夏|秋|冬)(?:季|天)/g,
      /(?:上班|约会|聚会|旅行|运动|居家)/g,
    ];

    patterns.forEach(pattern => {
      let match;
      while ((match = pattern.exec(lowerText)) !== null) {
        if (match[1]) {
          keywords.push(match[1]);
        } else {
          keywords.push(match[0]);
        }
      }
    });

    return [...new Set(keywords)].slice(0, 3); // 最多3个关键词
  }, []);

  // 处理发送消息
  const handleSendMessage = useCallback(() => {
    if (input.trim().length === 0 || isLoading) return;

    const userMessage = input.trim();
    const searchSuggestions = extractSearchKeywords(userMessage);
    setInput('');

    // 添加用户消息到历史
    setChatHistory(prev => [...prev, {
      type: 'user',
      content: userMessage,
      timestamp: new Date(),
      searchSuggestions: searchSuggestions.length > 0 ? searchSuggestions : undefined,
    }]);

    // 发送到LLM
    onAskLLM({
      user_input: userMessage,
    });
  }, [input, isLoading, onAskLLM, extractSearchKeywords]);

  // 处理快速搜索
  const handleQuickSearch = useCallback(async (keyword: string) => {
    if (!onSearch) return;

    try {
      const defaultConfig = await OutfitSearchService.getDefaultSearchConfig();
      const searchRequest: SearchRequest = {
        query: keyword,
        config: defaultConfig,
        page_size: 9,
        page_offset: 0,
      };

      onSearch(searchRequest);
    } catch (error) {
      console.error('Quick search failed:', error);
    }
  }, [onSearch]);

  // 处理回车键发送
  const handleKeyPress = useCallback((e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  }, [handleSendMessage]);

  // 当收到LLM响应时更新聊天历史
  useEffect(() => {
    if (response && !isLoading) {
      setChatHistory(prev => [...prev, {
        type: 'assistant',
        content: response.answer,
        timestamp: new Date(),
        relatedResults: response.related_results,
      }]);
    }
  }, [response, isLoading]);

  // 自动滚动到底部
  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [chatHistory, isLoading]);

  // 清除聊天历史
  const handleClearChat = useCallback(() => {
    setChatHistory([]);
  }, []);

  // 预设问题
  const presetQuestions = [
    '如何搭配牛仔裤？',
    '正式场合应该穿什么？',
    '夏季有什么清爽的搭配？',
    '约会穿什么比较好？',
    '运动风格怎么搭配？',
  ];

  // 处理预设问题点击
  const handlePresetClick = useCallback((question: string) => {
    setInput(question);
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  return (
    <div className="card p-4 sm:p-6 h-[500px] sm:h-[600px] flex flex-col animate-fade-in">
      <div className="flex items-start justify-between mb-4 sm:mb-6 gap-4">
        <div className="flex items-center gap-3 min-w-0 flex-1">
          <div className="icon-container primary w-8 h-8 sm:w-10 sm:h-10 flex-shrink-0">
            <Bot className="w-4 h-4 sm:w-5 sm:h-5" />
          </div>
          <div className="min-w-0 flex-1">
            <h3 className="text-lg sm:text-xl font-bold text-high-emphasis truncate">AI搭配顾问</h3>
            <p className="text-xs sm:text-sm text-medium-emphasis hidden sm:block">
              向AI顾问咨询搭配建议，获得专业的时尚指导
            </p>
          </div>
        </div>
        {chatHistory.length > 0 && (
          <button
            onClick={handleClearChat}
            className="btn btn-secondary btn-sm hover-lift flex-shrink-0"
            title="清除对话历史"
          >
            <Trash2 className="w-3 h-3 sm:w-4 sm:h-4" />
            <span className="hidden sm:inline ml-2">清除对话</span>
          </button>
        )}
      </div>

      {/* 聊天历史 - 现代化设计 */}
      <div ref={chatContainerRef} className="flex-1 overflow-y-auto space-y-4 mb-6 pr-2 scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100">
        {chatHistory.length === 0 && (
          <div className="h-full flex items-center justify-center">
            <div className="text-center space-y-4 max-w-md">
              <div className="flex justify-center">
                <div className="icon-container purple w-16 h-16">
                  <MessageCircle className="w-8 h-8" />
                </div>
              </div>
              <div className="space-y-2">
                <h4 className="text-heading-4 text-high-emphasis">欢迎咨询AI搭配顾问</h4>
                <p className="text-body text-medium-emphasis">
                  您可以询问任何关于服装搭配的问题，我会为您提供专业建议
                </p>
              </div>
            </div>
          </div>
        )}

        {chatHistory.map((message, index) => (
          <div key={index} className={`flex gap-2 sm:gap-3 animate-slide-in-up ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}>
            {message.type === 'assistant' && (
              <div className="icon-container primary w-6 h-6 sm:w-8 sm:h-8 flex-shrink-0">
                <Bot className="w-3 h-3 sm:w-4 sm:h-4" />
              </div>
            )}

            <div className={`max-w-[85%] sm:max-w-[80%] ${message.type === 'user' ? 'order-1' : ''}`}>
              <div className={`p-3 sm:p-4 rounded-2xl ${
                message.type === 'user'
                  ? 'bg-gradient-primary text-white ml-auto'
                  : 'bg-gray-100 text-gray-900'
              }`}>
                <div className="text-sm leading-relaxed whitespace-pre-wrap break-words">
                  {message.content}
                </div>
              </div>
              <div className={`text-xs text-gray-500 mt-1 px-1 ${message.type === 'user' ? 'text-right' : 'text-left'}`}>
                {message.timestamp.toLocaleTimeString()}
              </div>

              {/* 相关搜索结果 - 响应式 */}
              {message.relatedResults && message.relatedResults.length > 0 && (
                <div className="mt-3 sm:mt-4 p-3 sm:p-4 bg-blue-50 rounded-xl border border-blue-100">
                  <h5 className="text-sm font-semibold text-blue-900 mb-3 flex items-center gap-2">
                    <Sparkles className="w-4 h-4" />
                    相关搭配推荐
                  </h5>
                  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                    {message.relatedResults.slice(0, 3).map((result, resultIndex) => (
                      <div key={resultIndex} className="transform hover:scale-105 transition-transform duration-200">
                        <OutfitCard
                          result={result}
                          showScore={false}
                        />
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 搜索建议按钮 */}
              {message.type === 'user' && message.searchSuggestions && message.searchSuggestions.length > 0 && onSearch && (
                <div className="mt-3 sm:mt-4 p-3 sm:p-4 bg-green-50 rounded-xl border border-green-100">
                  <h5 className="text-sm font-semibold text-green-900 mb-3 flex items-center gap-2">
                    <Search className="w-4 h-4" />
                    基于您的问题，推荐搜索
                  </h5>
                  <div className="flex flex-wrap gap-2">
                    {message.searchSuggestions.map((keyword, keywordIndex) => (
                      <button
                        key={keywordIndex}
                        onClick={() => handleQuickSearch(keyword)}
                        className="px-3 py-1.5 bg-green-100 hover:bg-green-200 text-green-800 text-sm rounded-full border border-green-200 transition-colors duration-200 flex items-center gap-1"
                      >
                        <Search className="w-3 h-3" />
                        {keyword}
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {message.type === 'user' && (
              <div className="icon-container secondary w-6 h-6 sm:w-8 sm:h-8 flex-shrink-0 order-2">
                <User className="w-3 h-3 sm:w-4 sm:h-4" />
              </div>
            )}
          </div>
        ))}

        {/* 加载状态 - 打字动画 */}
        {isLoading && (
          <div className="flex gap-3 justify-start animate-slide-in-up">
            <div className="icon-container primary w-8 h-8 flex-shrink-0">
              <Bot className="w-4 h-4" />
            </div>
            <div className="max-w-[80%]">
              <div className="p-4 rounded-2xl bg-gray-100">
                <div className="flex items-center gap-2">
                  <div className="flex space-x-1">
                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0ms' }} />
                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
                  </div>
                  <span className="text-sm text-gray-600">AI正在思考中...</span>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 错误消息 */}
        {error && (
          <div className="flex items-center gap-3 p-4 bg-red-50 border border-red-200 rounded-xl text-red-800 animate-shake">
            <AlertCircle className="w-5 h-5 text-red-500 flex-shrink-0" />
            <span className="text-sm font-medium">{error}</span>
          </div>
        )}
      </div>

      {/* 预设问题 - 美化设计 */}
      {chatHistory.length === 0 && (
        <div className="mb-4 animate-fade-in">
          <div className="text-sm font-medium text-gray-700 mb-3">常见问题</div>
          <div className="flex flex-wrap gap-2">
            {presetQuestions.map((question, index) => (
              <button
                key={index}
                onClick={() => handlePresetClick(question)}
                className="px-3 py-2 text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-full transition-colors duration-200 hover-lift disabled:opacity-50 disabled:cursor-not-allowed"
                disabled={isLoading}
              >
                {question}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* 输入区域 - 现代化设计 */}
      <div className="border-t border-gray-200 pt-4">
        <div className="flex gap-3 items-end">
          <div className="flex-1 relative">
            <textarea
              ref={inputRef}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={handleKeyPress}
              placeholder="输入您的搭配问题..."
              className="form-input resize-none min-h-[44px] max-h-32 pr-12"
              disabled={isLoading}
              rows={1}
            />
            <div className="absolute right-3 bottom-3 text-gray-400">
              <MessageCircle className="w-5 h-5" />
            </div>
          </div>
          <button
            onClick={handleSendMessage}
            disabled={isLoading || input.trim().length === 0}
            className="btn btn-primary px-4 py-3 hover-lift disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isLoading ? (
              <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
            ) : (
              <Send className="w-5 h-5" />
            )}
          </button>
        </div>
        <div className="text-xs text-gray-500 mt-2 text-center">
          按 Enter 发送，Shift + Enter 换行
        </div>
      </div>
    </div>
  );
};

export default LLMChat;
