import { useState, useEffect } from 'react'
import './App.css'
import ChatBox from './components/ChatBox'
import PluginLoader from './components/PluginLoader'
import { sendMessage, getStats } from './utils/api'

function App() {
  const [messages, setMessages] = useState([])
  const [loading, setLoading] = useState(false)
  const [systemPrompt, setSystemPrompt] = useState('Du bist ein hilfsbereiter KI-Assistent.')
  const [temperature, setTemperature] = useState(0.7)
  const [topP, setTopP] = useState(0.9)
  const [stats, setStats] = useState(null)
  const [plugins, setPlugins] = useState([])

  useEffect(() => {
    // Auf Plugin-Änderungen hören
    window.addEventListener('pluginsLoaded', (e) => {
      setPlugins(e.detail)
      console.log('Plugins loaded:', e.detail)
    })

    return () => {
      window.removeEventListener('pluginsLoaded', () => {})
    }
  }, [])

  const handleSendMessage = async (message) => {
    // Nachricht zum Chat hinzufügen
    const userMessage = {
      id: Date.now(),
      role: 'user',
      content: message,
      timestamp: new Date(),
    }
    
    setMessages(prev => [...prev, userMessage])
    setLoading(true)

    try {
      // Plugins benachrichtigen
      window.dispatchEvent(new CustomEvent('messageSent', {
        detail: { message, systemPrompt }
      }))

      const response = await sendMessage(message, systemPrompt, temperature, topP)
      
      const assistantMessage = {
        id: Date.now() + 1,
        role: 'assistant',
        content: response.response,
        timestamp: new Date(),
        stats: {
          tokens: response.tokens,
          time: response.time_seconds,
        }
      }
      
      setMessages(prev => [...prev, assistantMessage])
      setStats(response)

      // Plugins über Antwort benachrichtigen
      window.dispatchEvent(new CustomEvent('responseReceived', {
        detail: assistantMessage
      }))

    } catch (error) {
      console.error('Error:', error)
      const errorMessage = {
        id: Date.now() + 1,
        role: 'assistant',
        content: `❌ Fehler: ${error.message}`,
        timestamp: new Date(),
        isError: true,
      }
      setMessages(prev => [...prev, errorMessage])
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="app-container">
      <PluginLoader onPluginsLoad={setPlugins} />
      
      <header className="app-header">
        <h1>🤖 Zephyr-7B Chatbot</h1>
        <p className="tagline">Powered by Hugging Face</p>
      </header>

      <div className="app-content">
        <aside className="sidebar">
          <div className="sidebar-section">
            <h3>⚙️ Einstellungen</h3>
            
            <label>System Prompt</label>
            <textarea
              value={systemPrompt}
              onChange={(e) => setSystemPrompt(e.target.value)}
              placeholder="Definiere die Rolle des Assistenten..."
              disabled={loading}
            />
            
            <label>
              Temperatur: {temperature.toFixed(2)}
              <input
                type="range"
                min="0"
                max="2"
                step="0.1"
                value={temperature}
                onChange={(e) => setTemperature(parseFloat(e.target.value))}
                disabled={loading}
              />
            </label>

            <label>
              Top P: {topP.toFixed(2)}
              <input
                type="range"
                min="0"
                max="1"
                step="0.05"
                value={topP}
                onChange={(e) => setTopP(parseFloat(e.target.value))}
                disabled={loading}
              />
            </label>

            {stats && (
              <div className="stats-box">
                <h4>📊 Letzte Antwort</h4>
                <div className="stat-item">
                  <span>Tokens:</span>
                  <strong>{stats.tokens}</strong>
                </div>
                <div className="stat-item">
                  <span>Zeit:</span>
                  <strong>{stats.time_seconds}s</strong>
                </div>
              </div>
            )}

            {plugins.length > 0 && (
              <div className="plugins-box">
                <h4>🔌 Plugins ({plugins.length})</h4>
                <ul>
                  {plugins.map(plugin => (
                    <li key={plugin}>{plugin}</li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        </aside>

        <main className="chat-container">
          <ChatBox
            messages={messages}
            onSendMessage={handleSendMessage}
            loading={loading}
          />
        </main>
      </div>
    </div>
  )
}

export default App
