import React, { useState, useRef, useEffect, useCallback } from 'react'
import { MessageCircle, Send, User, Bot, Sparkles, Loader, AlertCircle, CheckCircle } from 'lucide-react'
import { Project } from '../services/projectService'
import { Model } from '../services/modelService'
import { aguiService, AGUIEvent, AGUIState } from '../services/aguiService'

interface ChatMessage {
  id: string
  type: 'user' | 'assistant' | 'system'
  content: string
  timestamp: Date
  status?: 'sending' | 'sent' | 'error'
  events?: AGUIEvent[]
}

interface AGUIChatProps {
  project: Project
  models: Model[]
  onMaterialCreated?: () => void
}

const AGUIChat: React.FC<AGUIChatProps> = ({
  project,
  models,
  onMaterialCreated
}) => {
  const [messages, setMessages] = useState<ChatMessage[]>([
    {
      id: '1',
      type: 'system',
      content: `欢迎使用AI创作助手！我是您的智能创作伙伴，基于AG-UI协议为您提供专业的视频创作服务。\n\n🎯 **专业能力**\n• 智能视频内容生成\n• 模特选择与匹配\n• 创作流程优化\n• 实时质量监控\n\n💡 **项目信息**\n当前项目：${project.product_name}\n可用模特：${models.length}个\n\n请告诉我您的创作需求，我将为您提供专业的解决方案！`,
      timestamp: new Date()
    }
  ])
  const [inputText, setInputText] = useState('')
  const [aguiState, setAguiState] = useState<AGUIState>({
    connected: false,
    processing: false
  })
  const messagesEndRef = useRef<HTMLDivElement>(null)

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

  useEffect(() => {
    // 连接到AG-UI服务
    const connectToAgent = async () => {
      try {
        await aguiService.connect('video_creator')
      } catch (error) {
        console.error('Failed to connect to AG-UI agent:', error)
      }
    }

    // 订阅AG-UI状态变化
    const stateSubscription = aguiService.getStateStream().subscribe(setAguiState)

    // 订阅AG-UI事件流
    const eventSubscription = aguiService.getEventStream().subscribe(handleAGUIEvent)

    connectToAgent()

    return () => {
      stateSubscription.unsubscribe()
      eventSubscription.unsubscribe()
    }
  }, [])

  const handleAGUIEvent = useCallback((event: AGUIEvent) => {
    switch (event.type) {
      case 'message':
        if (event.data.role === 'assistant') {
          const assistantMessage: ChatMessage = {
            id: event.id,
            type: 'assistant',
            content: event.data.content,
            timestamp: event.timestamp,
            events: [event]
          }
          setMessages(prev => [...prev, assistantMessage])
        }
        break

      case 'thinking':
        // 显示思考状态
        setMessages(prev => {
          const lastMessage = prev[prev.length - 1]
          if (lastMessage && lastMessage.type === 'assistant' && lastMessage.events) {
            return prev.map((msg, index) =>
              index === prev.length - 1
                ? { ...msg, events: [...msg.events!, event] }
                : msg
            )
          }
          return prev
        })
        break

      case 'progress':
        // 更新进度
        setMessages(prev => {
          const lastMessage = prev[prev.length - 1]
          if (lastMessage && lastMessage.type === 'assistant' && lastMessage.events) {
            return prev.map((msg, index) =>
              index === prev.length - 1
                ? { ...msg, events: [...msg.events!.filter(e => e.type !== 'progress'), event] }
                : msg
            )
          }
          return prev
        })
        break

      case 'tool_call':
        // 显示工具调用
        setMessages(prev => {
          const lastMessage = prev[prev.length - 1]
          if (lastMessage && lastMessage.type === 'assistant' && lastMessage.events) {
            return prev.map((msg, index) =>
              index === prev.length - 1
                ? { ...msg, events: [...msg.events!, event] }
                : msg
            )
          }
          return prev
        })
        break

      case 'complete':
        // 处理完成事件
        if (event.data.success && onMaterialCreated) {
          onMaterialCreated()
        }
        break

      case 'error':
        // 处理错误
        const errorMessage: ChatMessage = {
          id: event.id,
          type: 'assistant',
          content: `抱歉，处理过程中出现了错误：${event.data.error}`,
          timestamp: event.timestamp,
          status: 'error'
        }
        setMessages(prev => [...prev, errorMessage])
        break
    }
  }, [onMaterialCreated])

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  const handleSendMessage = async () => {
    if (!inputText.trim() || aguiState.processing) return

    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      type: 'user',
      content: inputText.trim(),
      timestamp: new Date(),
      status: 'sending'
    }

    setMessages(prev => [...prev, userMessage])
    const messageContent = inputText.trim()
    setInputText('')

    try {
      // 更新消息状态为已发送
      setMessages(prev => prev.map(msg =>
        msg.id === userMessage.id ? { ...msg, status: 'sent' } : msg
      ))

      // 发送消息到AG-UI服务
      await aguiService.sendMessage(messageContent, {
        project: project,
        models: models,
        session_context: {
          message_count: messages.length,
          last_activity: new Date()
        }
      })
    } catch (error) {
      // 更新消息状态为错误
      setMessages(prev => prev.map(msg =>
        msg.id === userMessage.id ? { ...msg, status: 'error' } : msg
      ))
      console.error('Failed to send message:', error)
    }
  }



  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSendMessage()
    }
  }

  const getMessageStatusIcon = (status?: string) => {
    switch (status) {
      case 'sending':
        return <Loader size={12} className="animate-spin text-gray-400" />
      case 'sent':
        return <CheckCircle size={12} className="text-green-500" />
      case 'error':
        return <AlertCircle size={12} className="text-red-500" />
      default:
        return null
    }
  }

  const getLatestProgress = (events?: AGUIEvent[]) => {
    if (!events) return null
    const progressEvents = events.filter(e => e.type === 'progress')
    return progressEvents.length > 0 ? progressEvents[progressEvents.length - 1] : null
  }

  return (
    <div className="h-full flex flex-col bg-white border-r border-gray-200">
      {/* 头部 */}
      <div className="p-4 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-purple-50">
        <div className="flex items-center justify-between mb-2">
          <div className="flex items-center">
            <MessageCircle className="text-blue-600 mr-2" size={20} />
            <h3 className="font-semibold text-gray-900">AI创作助手</h3>
          </div>
          <div className="flex items-center">
            <div className={`w-2 h-2 rounded-full mr-2 ${aguiState.connected ? 'bg-green-500' : 'bg-red-500'}`} />
            <span className="text-xs text-gray-600">
              {aguiState.connected ? '已连接' : '未连接'}
            </span>
          </div>
        </div>
        <p className="text-xs text-gray-600">
          基于AG-UI协议的智能创作助手
        </p>
      </div>

      {/* 消息列表 */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {messages.map((message) => {
          const latestProgress = getLatestProgress(message.events)
          
          return (
            <div
              key={message.id}
              className={`flex ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}
            >
              <div className={`max-w-[85%] ${message.type === 'user' ? 'order-2' : 'order-1'}`}>
                {/* 消息头部 */}
                <div className={`flex items-center mb-1 ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}>
                  <div className={`flex items-center ${message.type === 'user' ? 'flex-row-reverse' : 'flex-row'}`}>
                    <div className={`w-6 h-6 rounded-full flex items-center justify-center ${
                      message.type === 'user' 
                        ? 'bg-blue-600 text-white ml-2' 
                        : message.type === 'system'
                        ? 'bg-purple-600 text-white mr-2'
                        : 'bg-gray-600 text-white mr-2'
                    }`}>
                      {message.type === 'user' ? (
                        <User size={14} />
                      ) : message.type === 'system' ? (
                        <Sparkles size={14} />
                      ) : (
                        <Bot size={14} />
                      )}
                    </div>
                    <span className="text-xs text-gray-500">
                      {message.timestamp.toLocaleTimeString()}
                    </span>
                    {message.status && (
                      <div className="ml-1">
                        {getMessageStatusIcon(message.status)}
                      </div>
                    )}
                  </div>
                </div>

                {/* 消息内容 */}
                <div className={`rounded-lg px-3 py-2 ${
                  message.type === 'user'
                    ? 'bg-blue-600 text-white'
                    : message.type === 'system'
                    ? 'bg-purple-100 text-purple-900 border border-purple-200'
                    : 'bg-gray-100 text-gray-900'
                }`}>
                  <div className="text-sm whitespace-pre-wrap">
                    {message.content}
                  </div>

                  {/* AG-UI事件展示 */}
                  {message.events && message.events.length > 0 && (
                    <div className="mt-2 space-y-1">
                      {/* 进度指示器 */}
                      {latestProgress && (
                        <div className="p-2 bg-white/20 rounded border">
                          <div className="flex items-center justify-between mb-1">
                            <span className="text-xs opacity-75">
                              {latestProgress.data.message}
                            </span>
                            <span className="text-xs opacity-75">
                              {latestProgress.data.progress}%
                            </span>
                          </div>
                          <div className="w-full bg-white/30 rounded-full h-1">
                            <div
                              className="bg-white h-1 rounded-full transition-all duration-300"
                              style={{ width: `${latestProgress.data.progress}%` }}
                            />
                          </div>
                        </div>
                      )}

                      {/* 工具调用展示 */}
                      {message.events.filter(e => e.type === 'tool_call').map(toolEvent => (
                        <div key={toolEvent.id} className="p-2 bg-blue-50/50 rounded border border-blue-200/50">
                          <div className="flex items-center text-xs">
                            <Sparkles size={12} className="mr-1 text-blue-600" />
                            <span className="font-medium">调用工具: {toolEvent.data.tool}</span>
                          </div>
                        </div>
                      ))}

                      {/* 思考状态展示 */}
                      {message.events.filter(e => e.type === 'thinking').map(thinkEvent => (
                        <div key={thinkEvent.id} className="p-2 bg-purple-50/50 rounded border border-purple-200/50">
                          <div className="flex items-center text-xs">
                            <Bot size={12} className="mr-1 text-purple-600 animate-pulse" />
                            <span className="italic">{thinkEvent.data.message}</span>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          )
        })}
        <div ref={messagesEndRef} />
      </div>

      {/* 输入区域 */}
      <div className="p-4 border-t border-gray-200 bg-gray-50">
        <div className="flex space-x-2">
          <textarea
            value={inputText}
            onChange={(e) => setInputText(e.target.value)}
            onKeyDown={handleKeyPress}
            placeholder={`告诉我您想要什么样的${project.product_name}视频...`}
            disabled={aguiState.processing}
            rows={2}
            className="flex-1 resize-none border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed text-sm"
          />
          <button
            onClick={handleSendMessage}
            disabled={!inputText.trim() || aguiState.processing}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors flex items-center"
          >
            {aguiState.processing ? (
              <Loader size={16} className="animate-spin" />
            ) : (
              <Send size={16} />
            )}
          </button>
        </div>
      </div>
    </div>
  )
}

export default AGUIChat
