import { useState, useEffect, useRef } from 'react'
import { ChatList } from './ChatList'
import { ChatBottombar } from './ChatBottombar'
import { ChatMobileSidebar } from './ChatMobileSidebar'
import { ChatDesktopSidebar } from './ChatDesktopSidebar'
import { ChatHeader } from './ChatHeader'
import { ChatInfoPanel } from './ChatInfoPanel'
import { useChatStore } from '@/store/useChatStore'
import { useConnectionStore } from '@/store/useConnectionStore'
import { useConversations } from '@/hooks/useConversations'
import { useIsMobile } from '@/hooks/useIsMobile'

export function ChatLayout() {
  const messages = useChatStore((state) => state.messages)
  const initStomp = useChatStore((state) => state.initStomp)
  const connectionStatus = useConnectionStore((state) => state.status)
  const isMobile = useIsMobile()

  const {
    conversations,
    activeId,
    isLoading,
    selectConversation,
    createNewConversation,
    deleteConversation,
    updateTitle,
    fetchConversations,
  } = useConversations()

  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false)
  const [isMobileSidebarOpen, setIsMobileSidebarOpen] = useState(false)
  const [showRightPanel, setShowRightPanel] = useState(false)
  
  const fetchedRef = useRef<string | null>(null)

  useEffect(() => {
    initStomp()
  }, [initStomp])

  useEffect(() => {
    if (!activeId) return
    const currentConv = conversations.find(c => c.id === activeId)
    // Auto-update title when agent starts replying to a new conversation
    if (currentConv && currentConv.title === 'Cuộc trò chuyện mới' && fetchedRef.current !== activeId) {
      const firstAgentMsg = messages.find(m => m.role === 'agent')
      const hasAgentStartedReplying = firstAgentMsg && (firstAgentMsg.content.length > 0 || firstAgentMsg.toolStatus || !firstAgentMsg.isStreaming)
      
      if (hasAgentStartedReplying) {
        fetchedRef.current = activeId
        fetchConversations()
      }
    }
  }, [messages, activeId, conversations, fetchConversations])

  return (
    <div className="flex h-screen w-full bg-background text-foreground overflow-hidden">
      {/* Mobile Drawer & Sidebar */}
      <ChatMobileSidebar
        isOpen={isMobileSidebarOpen}
        onClose={() => setIsMobileSidebarOpen(false)}
        conversations={conversations}
        activeId={activeId}
        isLoading={isLoading}
        onSelectConversation={selectConversation}
        onCreateNewConversation={createNewConversation}
        onUpdateTitle={updateTitle}
        onDeleteConversation={deleteConversation}
      />

      {/* Desktop Left Sidebar */}
      {!isMobile && (
        <ChatDesktopSidebar
          isCollapsed={isSidebarCollapsed}
          onToggleCollapse={() => setIsSidebarCollapsed(!isSidebarCollapsed)}
          conversations={conversations}
          activeId={activeId}
          isLoading={isLoading}
          onSelectConversation={selectConversation}
          onCreateNewConversation={createNewConversation}
          onUpdateTitle={updateTitle}
          onDeleteConversation={deleteConversation}
        />
      )}

      {/* Main Container */}
      <main className="flex-1 flex flex-col bg-background relative overflow-hidden">
        {/* Header */}
        <ChatHeader
          isMobile={isMobile}
          isSidebarCollapsed={isSidebarCollapsed}
          onOpenMobileSidebar={() => setIsMobileSidebarOpen(true)}
          onExpandDesktopSidebar={() => setIsSidebarCollapsed(false)}
          connectionStatus={connectionStatus}
          onToggleRightPanel={() => setShowRightPanel(!showRightPanel)}
        />

        {/* Center Content & Floating Input */}
        <div className="flex-1 flex overflow-hidden">
          <div className="flex-1 flex flex-col overflow-hidden relative">
            <ChatList messages={messages} />
            <ChatBottombar />
          </div>

          {/* Right Info Panel */}
          <ChatInfoPanel
            isOpen={showRightPanel}
            onClose={() => setShowRightPanel(false)}
          />
        </div>
      </main>
    </div>
  )
}
