'use client';

import { useState, useRef, useEffect, useCallback } from 'react';
import {
  X,
  Send,
  Loader2,
  ThumbsUp,
  ThumbsDown,
  AlertCircle,
  History,
  Plus,
  Bot,
  User,
  Copy,
  Check,
  ChevronDown,
  Minimize2,
  Maximize2,
} from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';
import { aiAssistantApi, sendMessageStream, type Message, type Conversation } from '@/lib/api/ai-assistant';
import { EscalateDialog } from './EscalateDialog';
import { HistoryPanel } from './HistoryPanel';

/**
 * 简单的 Markdown 渲染组件
 * 支持基本的格式：粗体、斜体、代码、链接、列表
 */
function MarkdownContent({ content }: { content: string }) {
  // 简单解析 markdown
  const parseMarkdown = (text: string): React.ReactNode[] => {
    const lines = text.split('\n');
    const result: React.ReactNode[] = [];

    lines.forEach((line, index) => {
      // 处理标题
      if (line.startsWith('### ')) {
        result.push(<h4 key={index} className="font-semibold text-base mt-3 mb-1">{line.slice(4)}</h4>);
        return;
      }
      if (line.startsWith('## ')) {
        result.push(<h3 key={index} className="font-semibold text-lg mt-3 mb-1">{line.slice(3)}</h3>);
        return;
      }
      if (line.startsWith('# ')) {
        result.push(<h2 key={index} className="font-bold text-xl mt-3 mb-1">{line.slice(2)}</h2>);
        return;
      }

      // 处理列表
      if (line.startsWith('- ') || line.startsWith('* ')) {
        result.push(
          <div key={index} className="flex items-start gap-2 ml-2">
            <span className="text-gray-400">•</span>
            <span>{parseInline(line.slice(2))}</span>
          </div>
        );
        return;
      }

      // 处理有序列表
      const orderedMatch = line.match(/^(\d+)\.\s+(.*)$/);
      if (orderedMatch) {
        result.push(
          <div key={index} className="flex items-start gap-2 ml-2">
            <span className="text-gray-500 min-w-[1.5em]">{orderedMatch[1]}.</span>
            <span>{parseInline(orderedMatch[2])}</span>
          </div>
        );
        return;
      }

      // 处理代码块
      if (line.startsWith('```')) {
        result.push(<div key={index} className="bg-gray-100 rounded p-2 font-mono text-xs my-2" />);
        return;
      }

      // 普通段落
      if (line.trim()) {
        result.push(<p key={index} className="mb-1">{parseInline(line)}</p>);
      } else {
        result.push(<div key={index} className="h-2" />);
      }
    });

    return result;
  };

  // 处理内联样式
  const parseInline = (text: string): React.ReactNode => {
    // 简单处理：粗体 **text**
    let processed = text;
    const parts: React.ReactNode[] = [];
    let lastIndex = 0;

    // 处理行内代码 `code`
    const codeRegex = /`([^`]+)`/g;
    let match;
    while ((match = codeRegex.exec(text)) !== null) {
      if (match.index > lastIndex) {
        parts.push(text.slice(lastIndex, match.index));
      }
      parts.push(
        <code key={match.index} className="bg-gray-100 px-1 rounded text-sm font-mono">
          {match[1]}
        </code>
      );
      lastIndex = match.index + match[0].length;
    }

    if (parts.length > 0) {
      if (lastIndex < text.length) {
        parts.push(text.slice(lastIndex));
      }
      return <>{parts}</>;
    }

    // 处理粗体 **text**
    processed = processed.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
    
    // 如果有 HTML 标签，使用 dangerouslySetInnerHTML
    if (processed !== text) {
      return <span dangerouslySetInnerHTML={{ __html: processed }} />;
    }

    return text;
  };

  return <div className="text-sm">{parseMarkdown(content)}</div>;
}

interface AIAssistantDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

/**
 * AI 助手对话框组件
 */
export function AIAssistantDialog({ open, onOpenChange }: AIAssistantDialogProps) {
  const { t } = useTranslation();
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [conversationId, setConversationId] = useState<string | null>(null);
  const [streamingContent, setStreamingContent] = useState('');
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const [showHistory, setShowHistory] = useState(false);
  const [showEscalate, setShowEscalate] = useState(false);
  const [isMaximized, setIsMaximized] = useState(false);
  const [feedbackSubmitted, setFeedbackSubmitted] = useState<Record<string, boolean>>({});
  
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);

  // 自动滚动到底部
  const scrollToBottom = useCallback(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, []);

  useEffect(() => {
    scrollToBottom();
  }, [messages, streamingContent, scrollToBottom]);

  // 打开对话框时聚焦输入框
  useEffect(() => {
    if (open) {
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  }, [open]);

  // 创建新对话
  const createNewConversation = useCallback(async () => {
    try {
      const response: any = await aiAssistantApi.createConversation();
      setConversationId(response.data.id);
      setMessages([]);
      setError(null);
      return response.data.id;
    } catch (err) {
      console.error('Failed to create conversation:', err);
      setError('Failed to create conversation');
      return null;
    }
  }, [t]);

  // 发送消息
  const handleSendMessage = async () => {
    if (!inputValue.trim() || isLoading) return;

    const content = inputValue.trim();
    setInputValue('');
    setIsLoading(true);
    setError(null);
    setStreamingContent('');

    try {
      // 如果没有对话，先创建
      let currentConversationId = conversationId;
      if (!currentConversationId) {
        currentConversationId = await createNewConversation();
        if (!currentConversationId) {
          setIsLoading(false);
          return;
        }
      }

      // 添加临时用户消息到列表（显示中）
      const tempUserMessageId = `temp-${Date.now()}`;
      const tempUserMessage: Message = {
        id: tempUserMessageId,
        conversationId: currentConversationId,
        role: 'USER',
        source: 'USER',
        content,
        createdAt: new Date().toISOString(),
      };
      setMessages(prev => [...prev, tempUserMessage]);

      // 使用流式响应
      let fullContent = '';
      await sendMessageStream(currentConversationId, content, {
        onToken: (token) => {
          fullContent += token;
          setStreamingContent(fullContent);
        },
        onComplete: (finalContent, messageIds) => {
          // 更新用户消息 ID 为后端返回的真实 ID
          if (messageIds) {
            setMessages(prev => prev.map(msg => 
              msg.id === tempUserMessageId 
                ? { ...msg, id: messageIds.userMessageId }
                : msg
            ));
          }
          
          // 添加 AI 回复到消息列表（使用后端返回的真实 ID）
          const aiMessage: Message = {
            id: messageIds?.aiMessageId || `ai-${Date.now()}`,
            conversationId: currentConversationId!,
            role: 'ASSISTANT',
            source: 'AI',
            content: finalContent,
            createdAt: new Date().toISOString(),
          };
          setMessages(prev => [...prev, aiMessage]);
          setStreamingContent('');
          setIsLoading(false);
        },
        onError: (err) => {
          setError(err.message || 'An error occurred');
          setStreamingContent('');
          setIsLoading(false);
        },
      });
    } catch (err: any) {
      setError(err.message || 'An error occurred');
      setIsLoading(false);
    }
  };

  // 处理键盘事件
  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 复制消息内容
  const handleCopy = async (messageId: string, content: string) => {
    try {
      await navigator.clipboard.writeText(content);
      setCopiedId(messageId);
      setTimeout(() => setCopiedId(null), 2000);
    } catch (err) {
      console.error('Failed to copy:', err);
    }
  };

  // 提交反馈
  const handleFeedback = async (messageId: string, type: 'LIKE' | 'DISLIKE') => {
    if (feedbackSubmitted[messageId]) return;
    
    try {
      await aiAssistantApi.submitFeedback(messageId, { type });
      setFeedbackSubmitted(prev => ({ ...prev, [messageId]: true }));
    } catch (err) {
      console.error('Failed to submit feedback:', err);
    }
  };

  // 新建对话
  const handleNewChat = () => {
    setConversationId(null);
    setMessages([]);
    setError(null);
    setStreamingContent('');
    setShowHistory(false);
  };

  // 加载历史对话
  const handleLoadConversation = async (conversation: Conversation) => {
    setConversationId(conversation.id);
    setShowHistory(false);
    setIsLoading(true);
    
    try {
      const response: any = await aiAssistantApi.getMessages(conversation.id);
      setMessages(response.data.items || []);
    } catch (err) {
      console.error('Failed to load messages:', err);
      setError('Failed to load messages');
    } finally {
      setIsLoading(false);
    }
  };

  if (!open) return null;

  const dialogClass = isMaximized
    ? 'fixed inset-4 z-50'
    : 'fixed bottom-28 right-6 z-50 w-[420px] h-[600px]';

  return (
    <>
      {/* 遮罩层 */}
      <div 
        className="fixed inset-0 bg-black/20 z-40"
        onClick={() => onOpenChange(false)}
      />

      {/* 对话框 */}
      <div 
        className={`${dialogClass} bg-white rounded-2xl shadow-2xl flex flex-col overflow-hidden`}
        onClick={(e) => e.stopPropagation()}
      >
        {/* 头部 */}
        <div className="flex items-center justify-between px-4 py-3 bg-gradient-to-r from-purple-600 to-blue-600 text-white">
          <div className="flex items-center gap-2">
            <Bot className="w-5 h-5" />
            <h2 className="font-semibold">{'AI Assistant'}</h2>
          </div>
          <div className="flex items-center gap-1">
            <button
              onClick={() => setShowHistory(!showHistory)}
              className="p-1.5 hover:bg-white/20 rounded-lg transition-colors"
              title={'History'}
            >
              <History className="w-4 h-4" />
            </button>
            <button
              onClick={handleNewChat}
              className="p-1.5 hover:bg-white/20 rounded-lg transition-colors"
              title={'New Chat'}
            >
              <Plus className="w-4 h-4" />
            </button>
            <button
              onClick={() => setIsMaximized(!isMaximized)}
              className="p-1.5 hover:bg-white/20 rounded-lg transition-colors"
            >
              {isMaximized ? <Minimize2 className="w-4 h-4" /> : <Maximize2 className="w-4 h-4" />}
            </button>
            <button
              onClick={() => onOpenChange(false)}
              className="p-1.5 hover:bg-white/20 rounded-lg transition-colors"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>

        {/* 历史面板 */}
        {showHistory && (
          <HistoryPanel
            onSelect={handleLoadConversation}
            onClose={() => setShowHistory(false)}
            currentConversationId={conversationId}
          />
        )}

        {/* 消息列表 */}
        <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50">
          {messages.length === 0 && !streamingContent && (
            <div className="flex flex-col items-center justify-center h-full text-center text-gray-500">
              <Bot className="w-12 h-12 mb-4 text-gray-300" />
              <p className="text-sm">{'Hello! How can I help you today?'}</p>
            </div>
          )}

          {messages.map((message) => (
            <div
              key={message.id}
              className={`flex gap-3 ${message.role === 'USER' ? 'flex-row-reverse' : ''}`}
            >
              {/* 头像 */}
              <div
                className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                  message.role === 'USER'
                    ? 'bg-blue-500 text-white'
                    : 'bg-gradient-to-r from-purple-500 to-blue-500 text-white'
                }`}
              >
                {message.role === 'USER' ? <User className="w-4 h-4" /> : <Bot className="w-4 h-4" />}
              </div>

              {/* 消息内容 */}
              <div
                className={`max-w-[80%] ${
                  message.role === 'USER'
                    ? 'bg-blue-500 text-white rounded-2xl rounded-tr-md px-4 py-2'
                    : 'bg-white rounded-2xl rounded-tl-md px-4 py-3 shadow-sm'
                }`}
              >
                {message.role === 'USER' ? (
                  <p className="text-sm whitespace-pre-wrap">{message.content}</p>
                ) : (
                  <div className="prose prose-sm max-w-none">
                    <MarkdownContent content={message.content} />
                  </div>
                )}

                {/* AI 消息的操作按钮 */}
                {message.role === 'ASSISTANT' && (
                  <div className="flex items-center gap-2 mt-2 pt-2 border-t border-gray-100">
                    <button
                      onClick={() => handleCopy(message.id, message.content)}
                      className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
                      title={'Copy'}
                    >
                      {copiedId === message.id ? (
                        <Check className="w-3.5 h-3.5 text-green-500" />
                      ) : (
                        <Copy className="w-3.5 h-3.5" />
                      )}
                    </button>
                    <button
                      onClick={() => handleFeedback(message.id, 'LIKE')}
                      disabled={feedbackSubmitted[message.id]}
                      className={`p-1 transition-colors ${
                        feedbackSubmitted[message.id]
                          ? 'text-green-500'
                          : 'text-gray-400 hover:text-green-500'
                      }`}
                      title={'Helpful'}
                    >
                      <ThumbsUp className="w-3.5 h-3.5" />
                    </button>
                    <button
                      onClick={() => handleFeedback(message.id, 'DISLIKE')}
                      disabled={feedbackSubmitted[message.id]}
                      className={`p-1 transition-colors ${
                        feedbackSubmitted[message.id]
                          ? 'text-red-500'
                          : 'text-gray-400 hover:text-red-500'
                      }`}
                      title={'Not Helpful'}
                    >
                      <ThumbsDown className="w-3.5 h-3.5" />
                    </button>
                  </div>
                )}
              </div>
            </div>
          ))}

          {/* 流式输出 */}
          {streamingContent && (
            <div className="flex gap-3">
              <div className="w-8 h-8 rounded-full bg-gradient-to-r from-purple-500 to-blue-500 text-white flex items-center justify-center flex-shrink-0">
                <Bot className="w-4 h-4" />
              </div>
              <div className="max-w-[80%] bg-white rounded-2xl rounded-tl-md px-4 py-3 shadow-sm">
                <div className="prose prose-sm max-w-none">
                  <MarkdownContent content={streamingContent} />
                </div>
              </div>
            </div>
          )}

          {/* 加载中 */}
          {isLoading && !streamingContent && (
            <div className="flex gap-3">
              <div className="w-8 h-8 rounded-full bg-gradient-to-r from-purple-500 to-blue-500 text-white flex items-center justify-center flex-shrink-0">
                <Bot className="w-4 h-4" />
              </div>
              <div className="bg-white rounded-2xl rounded-tl-md px-4 py-3 shadow-sm">
                <div className="flex items-center gap-2 text-gray-500">
                  <Loader2 className="w-4 h-4 animate-spin" />
                  <span className="text-sm">{'AI is thinking...'}</span>
                </div>
              </div>
            </div>
          )}

          {/* 错误提示 */}
          {error && (
            <div className="flex items-center gap-2 px-4 py-3 bg-red-50 text-red-600 rounded-lg">
              <AlertCircle className="w-4 h-4" />
              <span className="text-sm">{error}</span>
            </div>
          )}

          <div ref={messagesEndRef} />
        </div>

        {/* 底部操作区 */}
        <div className="p-4 bg-white border-t">
          {/* 转人工按钮 */}
          {messages.length > 0 && (
            <div className="flex justify-center mb-3">
              <button
                onClick={() => setShowEscalate(true)}
                className="text-sm text-blue-600 hover:text-blue-700 hover:underline"
              >
                {'Get Human Help'}
              </button>
            </div>
          )}

          {/* 输入区域 */}
          <div className="flex items-end gap-2">
            <textarea
              ref={inputRef}
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder={'Type your question...'}
              className="flex-1 resize-none border rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 min-h-[44px] max-h-[120px]"
              rows={1}
              disabled={isLoading}
            />
            <button
              onClick={handleSendMessage}
              disabled={!inputValue.trim() || isLoading}
              className="flex items-center justify-center w-11 h-11 bg-gradient-to-r from-purple-600 to-blue-600 text-white rounded-xl hover:from-purple-700 hover:to-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
            >
              {isLoading ? (
                <Loader2 className="w-5 h-5 animate-spin" />
              ) : (
                <Send className="w-5 h-5" />
              )}
            </button>
          </div>

          {/* 免责声明 */}
          <p className="text-xs text-gray-400 text-center mt-2">
            {'* AI provides guidance only'}
          </p>
        </div>
      </div>

      {/* 升级对话框 */}
      <EscalateDialog
        open={showEscalate}
        onOpenChange={setShowEscalate}
        conversationId={conversationId}
      />
    </>
  );
}

export default AIAssistantDialog;
