import { useState, useRef, useEffect } from 'react'
import './App.css'
import MessageList from './components/MessageList'
import ChatInput from './components/ChatInput'
import CitationsPanel from './components/CitationsPanel'
import { useChatStream, Citation } from './hooks/useChatStream'

export interface Message {
  role: 'user' | 'assistant'
  content: string
}

function App() {
  const [messages, setMessages] = useState<Message[]>([])
  const [input, setInput] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [citations, setCitations] = useState<Citation[]>([])
  const [showCitations, setShowCitations] = useState(false)
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const { sendMessage } = useChatStream()

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [messages])

  const handleSend = async () => {
    if (!input.trim() || isLoading) return

    const userMessage = input.trim()
    setInput('')
    setMessages(prev => [...prev, { role: 'user', content: userMessage }])
    setIsLoading(true)
    setCitations([])
    setShowCitations(false)

    let assistantContent = ''
    
    await sendMessage(userMessage, {
      onChunk: (chunk) => {
        assistantContent += chunk
        setMessages(prev => {
          const newMessages = [...prev]
          const lastMsg = newMessages[newMessages.length - 1]
          if (lastMsg?.role === 'assistant') {
            lastMsg.content = assistantContent
          } else {
            newMessages.push({ role: 'assistant', content: assistantContent })
          }
          return newMessages
        })
      },
      onCitations: (newCitations) => {
        setCitations(newCitations)
        setShowCitations(newCitations.length > 0)
      },
      onDone: () => {
        setIsLoading(false)
      },
      onError: (error) => {
        console.error('Stream error:', error)
        setIsLoading(false)
      }
    })
  }

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

  return (
    <div className="app">
      <header className="header">
        <h1>Companion</h1>
      </header>
      <main className="chat-container">
        <MessageList messages={messages} isLoading={isLoading} />
        <div ref={messagesEndRef} />
      </main>
      <footer className="input-container">
        <ChatInput
          value={input}
          onChange={setInput}
          onSend={handleSend}
          onKeyDown={handleKeyDown}
          disabled={isLoading}
        />
      </footer>
      <CitationsPanel
        citations={citations}
        isOpen={showCitations}
        onClose={() => setShowCitations(false)}
      />
    </div>
  )
}

export default App
