import { useState, useRef, useEffect } from 'react'
import type { ChatMessage, Metrics, MemorySamples } from '../types'
import { SourceBadge } from './SourceBadge'

interface ApiProps {
  connected: boolean
  metrics: Metrics | null
  loading: boolean
  sendMessage: (message: string, temperature?: number, maxTokens?: number) => Promise<any>
  teachModel: (question: string, answer: string) => Promise<any>
  learnText: (text: string) => Promise<any>
  dream: (cycles: number) => Promise<any>
  reason: (question: string) => Promise<any>
}

type SidebarTab = 'chat' | 'teach' | 'learn' | 'dream' | 'stats'

const SUGGESTIONS = [
  { icon: '👋', title: 'Say hello', q: 'hello' },
  { icon: '🧠', title: 'Who are you?', q: 'who are you' },
  { icon: '🐍', title: 'What is Python?', q: 'what is python' },
  { icon: '✨', title: 'Write a poem', q: 'write a poem about the sea' },
  { icon: '💻', title: 'Write code', q: 'write a python function to check if a number is prime' },
  { icon: '📖', title: 'Explain something', q: 'explain how the internet works' },
  { icon: '🌑', title: 'Science facts', q: 'what is dark matter' },
  { icon: '💡', title: 'Get advice', q: 'how to stay focused' },
]

export function ChatGPTLayout({ api }: { api: ApiProps }) {
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [input, setInput] = useState('')
  const [sidebarOpen, setSidebarOpen] = useState(true)
  const [tab, setTab] = useState<SidebarTab>('chat')
  const scrollRef = useRef<HTMLDivElement>(null)

  // Teach state
  const [teachQ, setTeachQ] = useState('')
  const [teachA, setTeachA] = useState('')
  const [teachHistory, setTeachHistory] = useState<{q: string, a: string, tokens: number}[]>([])

  // Learn state
  const [learnText, setLearnText] = useState('')
  const [learnResult, setLearnResult] = useState<any>(null)

  // Dream state
  const [dreamResult, setDreamResult] = useState<any>(null)

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight
  }, [messages, api.loading])

  const handleSend = async () => {
    const msg = input.trim()
    if (!msg || api.loading) return
    setInput('')
    const userMsg: ChatMessage = { id: `u-${Date.now()}`, role: 'user', text: msg, timestamp: Date.now() }
    setMessages(prev => [...prev, userMsg])
    try {
      const resp = await api.sendMessage(msg)
      setMessages(prev => [...prev, {
        id: `b-${Date.now()}`, role: 'palimpseste', text: resp.response,
        confidence: resp.confidence, source: resp.source,
        explanation: resp.explanation, chain: resp.chain,
        elapsed_ms: resp.elapsed_ms, timestamp: Date.now(),
      }])
    } catch {
      setMessages(prev => [...prev, {
        id: `e-${Date.now()}`, role: 'palimpseste',
        text: '⚠️ Cannot connect to server. Is the API running on :3332?',
        source: 'fallback', confidence: 0, timestamp: Date.now(),
      }])
    }
  }

  const handleTeach = async () => {
    if (!teachQ.trim() || !teachA.trim() || api.loading) return
    try {
      const resp = await api.teachModel(teachQ, teachA)
      setTeachHistory(prev => [{ q: teachQ, a: teachA, tokens: resp.tokens_written }, ...prev])
      setTeachQ(''); setTeachA('')
    } catch {}
  }

  const handleLearn = async () => {
    if (!learnText.trim() || api.loading) return
    try {
      const r = await api.learnText(learnText)
      setLearnResult(r)
    } catch {}
  }

  const handleDream = async () => {
    try {
      const r = await api.dream(3)
      setDreamResult(r)
    } catch {}
  }

  const newChat = () => { setMessages([]); setTab('chat') }

  return (
    <div className="h-screen w-screen flex bg-pal-bg relative overflow-hidden">
      {/* Background orbs */}
      <div className="bg-orbs">
        <div className="bg-orb" style={{ width: '500px', height: '500px', background: '#7c3aed', top: '-100px', left: '-100px' }} />
        <div className="bg-orb" style={{ width: '400px', height: '400px', background: '#06b6d4', bottom: '-50px', right: '-50px', animationDelay: '2s' }} />
      </div>

      {/* Sidebar */}
      {sidebarOpen && (
        <aside className="relative z-10 w-72 glass border-r border-pal-border flex flex-col">
          {/* New chat button */}
          <div className="p-3">
            <button onClick={newChat} className="w-full flex items-center gap-2 px-3 py-2.5 rounded-xl glass-card hover:border-pal-accent/30 transition-all text-sm text-pal-text font-medium">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg>
              New Chat
            </button>
          </div>

          {/* Nav */}
          <nav className="px-2 space-y-0.5">
            {([
              ['chat', '💬', 'Chat'],
              ['teach', '📚', 'Teach'],
              ['learn', '📖', 'Learn Text'],
              ['dream', '🌙', 'Dream'],
              ['stats', '📊', 'Statistics'],
            ] as [SidebarTab, string, string][]).map(([t, icon, label]) => (
              <button key={t} onClick={() => setTab(t)}
                className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-all ${
                  tab === t ? 'glass-card text-pal-text font-medium' : 'text-pal-muted hover:text-pal-text'
                }`}>
                <span>{icon}</span> {label}
              </button>
            ))}
          </nav>

          {/* Connection status */}
          <div className="mt-auto p-3 border-t border-pal-border">
            <div className="flex items-center gap-2 mb-2">
              <div className={`w-2 h-2 rounded-full ${api.connected ? 'bg-pal-green' : 'bg-pal-red'}`}>
                {api.connected && <div className="w-2 h-2 rounded-full bg-pal-green animate-ping" />}
              </div>
              <span className="text-xs text-pal-muted">{api.connected ? 'Connected' : 'Offline'}</span>
            </div>
            <p className="text-[10px] text-pal-muted">PALIMPSESTE · No GPU · 0 weights</p>
            <p className="text-[10px] text-pal-muted">Philippe-Antoine Robert · 2026</p>
          </div>
        </aside>
      )}

      {/* Main content */}
      <main className="relative z-10 flex-1 flex flex-col">
        {/* Top bar */}
        <header className="flex items-center justify-between px-4 py-2.5 border-b border-pal-border glass">
          <div className="flex items-center gap-3">
            <button onClick={() => setSidebarOpen(!sidebarOpen)}
              className="p-1.5 rounded-lg hover:bg-pal-card text-pal-muted hover:text-pal-text transition-all">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 12h18M3 6h18M3 18h18"/></svg>
            </button>
            <span className="text-sm font-bold gradient-text">PALIMPSESTE</span>
            <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-pal-accent/15 text-pal-accent font-semibold">BPE</span>
          </div>
          {api.metrics && (
            <div className="hidden md:flex items-center gap-3 text-xs text-pal-muted">
              <span>D={api.metrics.model.D.toLocaleString()}</span>
              <span>·</span>
              <span>|M|={api.metrics.model.n_traces.toLocaleString()}</span>
            </div>
          )}
        </header>

        {/* Content area */}
        {tab === 'chat' && (
          <>
            {/* Messages */}
            <div ref={scrollRef} className="flex-1 overflow-y-auto">
              {messages.length === 0 ? (
                <div className="h-full flex flex-col items-center justify-center px-6">
                  <div className="text-5xl mb-4 animate-float">🧠</div>
                  <h1 className="text-2xl font-bold gradient-text mb-1">PALIMPSESTE</h1>
                  <p className="text-sm text-pal-muted mb-8">A self-referential hypervectorial cortex</p>
                  <div className="grid grid-cols-2 gap-2 max-w-lg w-full">
                    {SUGGESTIONS.map(s => (
                      <button key={s.q} onClick={() => setInput(s.q)}
                        className="flex items-center gap-2 p-3 rounded-xl glass-card hover:border-pal-accent/30 transition-all text-left">
                        <span className="text-lg">{s.icon}</span>
                        <div>
                          <div className="text-xs font-medium text-pal-text">{s.title}</div>
                          <div className="text-[10px] text-pal-muted truncate">{s.q}</div>
                        </div>
                      </button>
                    ))}
                  </div>
                </div>
              ) : (
                <div className="max-w-3xl mx-auto px-4 py-6 space-y-6">
                  {messages.map(msg => (
                    <div key={msg.id} className={`flex gap-3 ${msg.role === 'user' ? 'justify-end' : ''} animate-slide-up`}>
                      {msg.role === 'palimpseste' && (
                        <div className="w-8 h-8 rounded-full bg-gradient-to-br from-pal-accent to-pal-accent2 flex items-center justify-center text-sm flex-shrink-0">
                          🧠
                        </div>
                      )}
                      <div className={`max-w-[80%] ${msg.role === 'user' ? 'order-1' : ''}`}>
                        <div className={`rounded-2xl px-4 py-3 ${
                          msg.role === 'user'
                            ? 'bg-gradient-to-br from-pal-accent/30 to-pal-accent/10 border border-pal-accent/30'
                            : 'glass border border-pal-border'
                        }`}>
                          <p className="text-sm text-pal-text whitespace-pre-wrap break-words">{msg.text}</p>
                          {msg.role === 'palimpseste' && msg.source && (
                            <div className="mt-2 pt-2 border-t border-pal-border/50">
                              <div className="flex items-center justify-between gap-2">
                                <SourceBadge source={msg.source} confidence={msg.confidence ?? 0} />
                                {msg.elapsed_ms !== undefined && (
                                  <span className="text-[10px] text-pal-muted font-mono">{msg.elapsed_ms < 1 ? '<1' : msg.elapsed_ms.toFixed(0)}ms</span>
                                )}
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                      {msg.role === 'user' && (
                        <div className="w-8 h-8 rounded-full bg-pal-card flex items-center justify-center text-sm flex-shrink-0">
                          🧑
                        </div>
                      )}
                    </div>
                  ))}
                  {api.loading && (
                    <div className="flex gap-3">
                      <div className="w-8 h-8 rounded-full bg-gradient-to-br from-pal-accent to-pal-accent2 flex items-center justify-center text-sm">🧠</div>
                      <div className="glass border border-pal-border rounded-2xl px-4 py-3">
                        <div className="flex gap-1.5">
                          <span className="w-2 h-2 rounded-full bg-pal-accent animate-bounce" style={{ animationDelay: '0ms' }} />
                          <span className="w-2 h-2 rounded-full bg-pal-accent animate-bounce" style={{ animationDelay: '150ms' }} />
                          <span className="w-2 h-2 rounded-full bg-pal-accent animate-bounce" style={{ animationDelay: '300ms' }} />
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* Input bar */}
            <div className="border-t border-pal-border glass px-4 py-3">
              <div className="max-w-3xl mx-auto flex gap-2 items-end">
                <textarea
                  value={input}
                  onChange={e => setInput(e.target.value)}
                  onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend() } }}
                  placeholder="Message PALIMPSESTE..."
                  rows={1}
                  className="flex-1 bg-pal-surface border border-pal-border rounded-2xl px-4 py-3 text-sm text-pal-text placeholder:text-pal-muted focus:outline-none focus:border-pal-accent/40 transition-all resize-none max-h-32"
                  style={{ minHeight: '46px' }}
                />
                <button onClick={handleSend} disabled={!input.trim() || api.loading}
                  className="p-3 rounded-2xl bg-gradient-to-br from-pal-accent to-pal-accent2 text-white transition-all hover:scale-105 hover:glow-accent disabled:opacity-30 disabled:cursor-not-allowed">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>
                </button>
              </div>
              <p className="text-center text-[10px] text-pal-muted mt-1.5">
                PALIMPSESTE can make mistakes. No weights, no gradient, no GPU.
              </p>
            </div>
          </>
        )}

        {/* TEACH TAB */}
        {tab === 'teach' && (
          <div className="flex-1 overflow-y-auto p-6">
            <div className="max-w-lg mx-auto space-y-4">
              <h2 className="text-lg font-bold text-pal-text flex items-center gap-2">📚 Teach PALIMPSESTE</h2>
              <p className="text-sm text-pal-muted">Teach new facts instantly. O(1) memory write, immediately retrievable.</p>
              <input value={teachQ} onChange={e => setTeachQ(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleTeach()}
                placeholder="Question" className="w-full bg-pal-surface border border-pal-border rounded-xl px-4 py-2.5 text-sm text-pal-text placeholder:text-pal-muted focus:outline-none focus:border-pal-green/40" />
              <input value={teachA} onChange={e => setTeachA(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleTeach()}
                placeholder="Answer" className="w-full bg-pal-surface border border-pal-border rounded-xl px-4 py-2.5 text-sm text-pal-text placeholder:text-pal-muted focus:outline-none focus:border-pal-green/40" />
              <button onClick={handleTeach} disabled={!teachQ.trim() || !teachA.trim() || api.loading}
                className="w-full py-2.5 rounded-xl bg-gradient-to-r from-pal-green to-pal-accent2 text-white font-semibold text-sm transition-all hover:scale-[1.02] disabled:opacity-30">
                ⚡ Teach Instantly
              </button>
              {teachHistory.map((h, i) => (
                <div key={i} className="p-3 rounded-xl glass-card animate-slide-up">
                  <div className="text-sm text-pal-text">{h.q} → <span className="text-pal-green font-medium">{h.a}</span></div>
                  <div className="text-[10px] text-pal-muted mt-0.5">+{h.tokens} tokens</div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* LEARN TAB */}
        {tab === 'learn' && (
          <div className="flex-1 overflow-y-auto p-6">
            <div className="max-w-lg mx-auto space-y-4">
              <h2 className="text-lg font-bold text-pal-text flex items-center gap-2">📖 Instant Expertise</h2>
              <p className="text-sm text-pal-muted">Paste any text. PALIMPSESTE becomes an expert in milliseconds.</p>
              <textarea value={learnText} onChange={e => setLearnText(e.target.value)} placeholder="Paste a document, article, or any text..." rows={8}
                className="w-full bg-pal-surface border border-pal-border rounded-xl px-4 py-2.5 text-sm text-pal-text placeholder:text-pal-muted focus:outline-none focus:border-pal-accent2/40 resize-none" />
              <button onClick={handleLearn} disabled={!learnText.trim() || api.loading}
                className="w-full py-2.5 rounded-xl bg-gradient-to-r from-pal-accent2 to-pal-green text-white font-semibold text-sm transition-all hover:scale-[1.02] disabled:opacity-30">
                ⚡ Learn Instantly
              </button>
              {learnResult && !learnResult.error && (
                <div className="p-3 rounded-xl glass-card border-pal-accent2/20 animate-slide-up">
                  <div className="text-sm font-semibold text-pal-green mb-1">✓ Learned {learnResult.n_facts} facts in {learnResult.n_seconds}s</div>
                  {learnResult.facts?.map((f: any, i: number) => (
                    <div key={i} className="text-xs text-pal-text mt-1"><span className="text-pal-accent2">Q:</span> {f.q}<br/><span className="text-pal-green">A:</span> {f.a?.slice(0, 80)}</div>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}

        {/* DREAM TAB */}
        {tab === 'dream' && (
          <div className="flex-1 overflow-y-auto p-6">
            <div className="max-w-lg mx-auto space-y-4">
              <h2 className="text-lg font-bold text-pal-text flex items-center gap-2">🌙 Dream Consolidation</h2>
              <p className="text-sm text-pal-muted">When idle, PALIMPSESTE replays memory, discovers concepts, and gets smarter autonomously.</p>
              <button onClick={handleDream} disabled={api.loading}
                className="w-full py-2.5 rounded-xl bg-gradient-to-r from-pal-accent to-pal-accent2 text-white font-semibold text-sm transition-all hover:scale-[1.02] hover:glow-accent disabled:opacity-30">
                🌙 Trigger Dream
              </button>
              {dreamResult && !dreamResult.error && (
                <div className="p-3 rounded-xl glass-card border-pal-accent/20 animate-slide-up">
                  <div className="text-sm font-semibold text-pal-accent">✓ {dreamResult.n_concepts_extracted} concepts discovered</div>
                  <div className="text-xs text-pal-muted mt-1">in {dreamResult.n_seconds}s · {dreamResult.n_total_concepts} total</div>
                  {dreamResult.concept_labels?.length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-2">
                      {dreamResult.concept_labels.map((l: string, i: number) => (
                        <span key={i} className="text-[10px] px-2 py-0.5 rounded-full bg-pal-accent/10 text-pal-accent">{l}</span>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        )}

        {/* STATS TAB */}
        {tab === 'stats' && api.metrics && (
          <div className="flex-1 overflow-y-auto p-6">
            <div className="max-w-lg mx-auto space-y-3">
              <h2 className="text-lg font-bold text-pal-text">📊 Statistics</h2>
              <div className="grid grid-cols-2 gap-2">
                <StatCard label="Dimension (D)" value={api.metrics.model.D.toLocaleString()} />
                <StatCard label="Memory Traces" value={api.metrics.model.n_traces.toLocaleString()} />
                <StatCard label="Vocab" value={api.metrics.model.vocab_size.toLocaleString()} />
                <StatCard label="Context Window" value={api.metrics.model.context_window.toString()} />
                <StatCard label="Kernel Radius" value={api.metrics.config.kernel_radius.toString()} />
                <StatCard label="Temperature" value={api.metrics.config.temperature.toString()} />
                <StatCard label="Turns" value={api.metrics.conversation.turns.toString()} />
                <StatCard label="Mean Weight" value={api.metrics.memory.mean_weight.toFixed(3)} />
              </div>
              <div className="p-3 rounded-xl glass-card">
                <div className="text-[10px] text-pal-muted uppercase font-medium mb-1">Theoretical Capacity</div>
                <div className="text-lg font-bold gradient-text">2^{(api.metrics.model.theoretical_capacity_log2 / 3.32).toFixed(0)}</div>
                <div className="text-[10px] text-pal-muted">≈ 10^{api.metrics.model.theoretical_capacity_log2.toFixed(0)} associations</div>
              </div>
            </div>
          </div>
        )}
        {tab === 'stats' && !api.metrics && (
          <div className="flex-1 flex items-center justify-center text-pal-muted text-sm">Loading statistics...</div>
        )}
      </main>
    </div>
  )
}

function StatCard({ label, value }: { label: string; value: string }) {
  return (
    <div className="p-3 rounded-xl glass-card">
      <div className="text-[10px] text-pal-muted uppercase font-medium">{label}</div>
      <div className="text-lg font-bold text-pal-text">{value}</div>
    </div>
  )
}
