import { useState } from 'react'
import { MessageList } from './MessageList'
import { MessageInput } from './MessageInput'
import { ExpertSelector } from './ExpertSelector'
import type { ChatMessage, Attachment } from '../../types/protocol'

interface ChatContainerProps {
  messages: ChatMessage[]
  isLoading: boolean
  isReadOnly?: boolean
  channelName?: string
  onSendMessage: (content: string, attachments: Attachment[]) => void
  onNavigateToSubAgent?: (taskId: string, description: string, subagentType?: string) => void
  onStop?: () => void
  showThinking?: boolean
  /** 视图标识，用于保存/恢复滚动位置 */
  viewKey?: string
  /** 高亮的消息 ID */
  highlightedMessageId?: string | null
  /** 当前 session ID，用于专家选择 */
  sessionId?: string | null
  /** 打开设置页（用于专家管理入口） */
  onOpenSettings?: () => void
  /** 设置弹窗关闭信号（每次关闭递增，用于触发 ExpertSelector 刷新） */
  settingsClosedTick?: number
}

export function ChatContainer({
  messages,
  isLoading,
  isReadOnly = false,
  channelName,
  onSendMessage,
  onNavigateToSubAgent,
  onStop,
  showThinking = true,
  viewKey,
  highlightedMessageId,
  sessionId,
  onOpenSettings,
  settingsClosedTick,
}: ChatContainerProps) {
  const [selectedExpert, setSelectedExpert] = useState<{ name: string; description: string } | null>(null)

  return (
    <div className="flex h-full flex-col relative">
      <div className="flex-1 overflow-hidden relative">
        <MessageList messages={messages} onNavigateToSubAgent={onNavigateToSubAgent} showThinking={showThinking} viewKey={viewKey} highlightedMessageId={highlightedMessageId} />
      </div>
      <ExpertSelector
        sessionId={sessionId ?? null}
        onManageExperts={onOpenSettings}
        onSelectionChange={setSelectedExpert}
        settingsClosedTick={settingsClosedTick}
      />
      <MessageInput
        onSend={onSendMessage}
        onStop={onStop}
        disabled={isLoading}
        isLoading={isLoading}
        isReadOnly={isReadOnly}
        channelName={channelName}
        selectedExpert={selectedExpert}
      />
    </div>
  )
}
