import {useEffect, useState} from 'react'
import {useNavigate, useSearchParams} from 'react-router-dom'
import {PanelLeftOpen, PanelRightOpen} from 'lucide-react'
import Sidebar from '../components/Sidebar'
import ChatArea from '../components/ChatArea'
import CharacterPanel from '../components/CharacterPanel'
import SettingsPanel from '../components/SettingsPanel'
import {type Conversation, conversationApi} from '../api/conversation'
import {type Character, characterApi} from '../api/character'
import {useAppStore} from '../store'

export default function ChatPage() {
  const [searchParams] = useSearchParams()
  const navigate = useNavigate()
  const [activePanel, setActivePanel] = useState<'chat' | 'settings'>('chat')
  const [backgroundImage, setBackgroundImage] = useState<string>()
  const [showCharacterPanel, setShowCharacterPanel] = useState(true)

  // 使用 MVU store
  const {
    currentConversation: storeConversation,
    loading,
    sidebarOpen: showSidebar,
    setCurrentConversation,
    setCurrentCharacter,
    setLoading,
    setSidebarOpen: setShowSidebar,
    setVariable,
  } = useAppStore()

  // 使用本地状态来存储完整的 Conversation 和 Character 对象
  const [currentConversation, setLocalConversation] = useState<Conversation | null>(null)
  const [currentCharacter, setLocalCharacter] = useState<Character | null>(null)

  // 同步 store 和本地状态
  useEffect(() => {
    if (storeConversation && currentConversation?.id !== storeConversation.id) {
      // 当 store 中的对话改变时，重新加载完整数据
      initializeChat()
    }
  }, [storeConversation?.id])

  // 从URL参数获取角色ID或对话ID
  const characterId = searchParams.get('character')
  const conversationId = searchParams.get('conversation')

  useEffect(() => {
    initializeChat()
  }, [characterId, conversationId])

  // 监听 iframe 消息（状态栏按钮点击事件）
  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      if (event.data.type === 'playerAction') {
        // 用户点击了状态栏中的按钮，自动发送消息
        const action = event.data.data.action
        console.log('[ChatPage] 收到状态栏操作:', action)
        // 这里需要触发消息发送，但需要访问 ChatArea 的 sendMessage 方法
        // 暂时通过自定义事件来实现
        window.dispatchEvent(new CustomEvent('sendMessageFromStatusBar', { detail: action }))
      }
    }

    window.addEventListener('message', handleMessage)
    return () => window.removeEventListener('message', handleMessage)
  }, [])

  useEffect(() => {
    if (currentConversation?.settings) {
      try {
        const settings = typeof currentConversation.settings === 'string'
          ? JSON.parse(currentConversation.settings)
          : currentConversation.settings

        // 设置背景图（如果有）
        if (settings.backgroundImage) {
          setBackgroundImage(settings.backgroundImage)
        } else {
          // 如果当前对话没有背景图，清除背景图
          setBackgroundImage(undefined)
        }

        // 设置主题色
        if (settings.themeColor) {
          document.documentElement.style.setProperty('--color-primary', settings.themeColor)
        }
      } catch (e) {
        console.error('解析设置失败:', e)
      }
    } else {
      // 如果没有设置，清除背景图
      setBackgroundImage(undefined)
    }
  }, [currentConversation?.settings, currentConversation?.id])

  const initializeChat = async () => {
    try {
      setLoading(true)

      // 如果有对话ID，加载现有对话
      if (conversationId) {
        const convResp = await conversationApi.getConversationById(Number(conversationId))
        setLocalConversation(convResp.data)
        setCurrentConversation(convResp.data)

        // 加载对话关联的角色
        const charResp = await characterApi.getCharacterById(convResp.data.characterId)
        setLocalCharacter(charResp.data)
        setCurrentCharacter(charResp.data)

        // 更新变量系统
        setVariable('char', charResp.data.name)
      }
      // 如果有角色ID，创建新对话
      else if (characterId) {
        const charResp = await characterApi.getCharacterById(Number(characterId))
        setLocalCharacter(charResp.data)
        setCurrentCharacter(charResp.data)

        // 更新变量系统
        setVariable('char', charResp.data.name)

        // 创建新对话
        const convResp = await conversationApi.createConversation({
          characterId: Number(characterId),
          title: `与 ${charResp.data.name} 的对话`,
        })
        setLocalConversation(convResp.data)
        setCurrentConversation(convResp.data)

        // 更新URL为对话ID
        navigate(`/chat?conversation=${convResp.data.id}`, { replace: true })
      }
    } catch (err) {
      console.error('初始化对话失败:', err)
      alert('加载对话失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  const handleConversationChange = (conversation: Conversation) => {
    setLocalConversation(conversation)
    setCurrentConversation(conversation)
    navigate(`/chat?conversation=${conversation.id}`)
  }

  const handleConversationUpdate = (conversation: Conversation) => {
    setLocalConversation(conversation)
    setCurrentConversation(conversation)
  }

  const handleSettingsUpdate = (settings: any) => {
    if (settings.backgroundImage !== undefined) {
      setBackgroundImage(settings.backgroundImage)
    }
    if (settings.themeColor) {
      document.documentElement.style.setProperty('--color-primary', settings.themeColor)
    }
  }

  if (loading) {
    return (
      <div className="h-screen w-screen flex items-center justify-center bg-gradient-to-br from-[#0A0A0F] via-[#1A0B2E] to-[#0A0A0F]">
        <div className="text-white">加载中...</div>
      </div>
    )
  }

  // 如果没有对话和角色,显示带侧边栏的空状态
  if (!currentConversation || !currentCharacter) {
    return (
      <div className="h-screen w-screen overflow-hidden flex bg-gradient-to-br from-[#0A0A0F] via-[#1A0B2E] to-[#0A0A0F]">
        <Sidebar
          currentConversationId={undefined}
          onConversationChange={handleConversationChange}
        />
        <div className="flex-1 flex items-center justify-center">
          <div className="text-center">
            <p className="text-white/60 mb-4">请选择或创建对话</p>
            <button
              onClick={() => navigate('/characters')}
              className="px-6 py-3 bg-gradient-to-r from-primary to-secondary rounded-xl font-medium hover:opacity-90 transition-opacity cursor-pointer"
            >
              选择角色开始对话
            </button>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="h-screen w-screen overflow-hidden flex bg-gradient-to-br from-[#0A0A0F] via-[#1A0B2E] to-[#0A0A0F] relative">
      {backgroundImage && (
        <div
          className="absolute inset-0 bg-cover bg-center bg-no-repeat opacity-20"
          style={{ backgroundImage: `url(${backgroundImage})` }}
        />
      )}

      <div className="relative z-10 flex w-full min-w-0 overflow-hidden">
        {/* 左侧边栏 */}
        {showSidebar && (
          <Sidebar
            currentConversationId={currentConversation.id}
            onConversationChange={handleConversationChange}
            onClose={() => setShowSidebar(false)}
          />
        )}

        {/* 左侧边栏切换按钮 */}
        {!showSidebar && (
          <button
            onClick={() => setShowSidebar(true)}
            className="fixed left-2 top-4 z-50 p-2 glass-hover rounded-lg cursor-pointer shadow-lg"
            title="显示对话列表"
          >
            <PanelLeftOpen className="w-5 h-5" />
          </button>
        )}

        <div className="flex-1 flex min-w-0 overflow-hidden">
          {activePanel === 'chat' ? (
            <>
              <ChatArea
                conversation={currentConversation}
                character={currentCharacter}
                onConversationUpdate={handleConversationUpdate}
              />
              {showCharacterPanel && (
                <CharacterPanel
                  character={currentCharacter}
                  conversation={currentConversation}
                  onOpenSettings={() => setActivePanel('settings')}
                  onClose={() => setShowCharacterPanel(false)}
                />
              )}

              {/* 右侧角色面板切换按钮 */}
              {!showCharacterPanel && (
                <button
                  onClick={() => setShowCharacterPanel(true)}
                  className="fixed right-2 top-4 z-50 p-2 glass-hover rounded-lg cursor-pointer shadow-lg"
                  title="显示角色信息"
                >
                  <PanelRightOpen className="w-5 h-5" />
                </button>
              )}
            </>
          ) : (
            <SettingsPanel
              conversation={currentConversation}
              onClose={() => setActivePanel('chat')}
              onUpdate={handleSettingsUpdate}
            />
          )}
        </div>
      </div>
    </div>
  )
}
