import { useState, useEffect, useRef } from "react";

export function ChatPage() {
  const [messages, setMessages] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [input, setInput] = useState("");
  const [models, setModels] = useState<string[]>([]);
  const [selectedModel, setSelectedModel] = useState("llama3:8b");
  const [useRag, setUseRag] = useState(true);

  const bottomRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    fetch("/api/models")
      .then(res => res.json())
      .then(data => { if (Array.isArray(data)) setModels(data); });

    // Initial greeting
    setMessages([{
      role: "assistant",
      content: "Welcome. I've indexed your workspace. What would you like to synthesize today?",
      sources: []
    }]);
  }, []);

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  const handleSend = async () => {
    if (!input.trim() || isLoading) return;
    const userMsg = { role: "user", content: input };
    setMessages(prev => [...prev, userMsg]);
    setInput("");
    setIsLoading(true);

    try {
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: userMsg.content, model: selectedModel, useRag }),
      });
      const data = await res.json();
      setMessages(prev => [...prev, { role: "assistant", content: data.answer, sources: data.sources }]);
    } catch (err) {
      console.error(err);
      setMessages(prev => [...prev, { role: "assistant", content: "Error connecting to brain." }]);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="flex flex-col h-full relative">
      {/* Chat Message List */}
      <div className="flex-1 overflow-y-auto pt-8 pb-32 custom-scrollbar">
        <div className="max-w-3xl mx-auto px-4 space-y-10">
          {messages.map((msg, idx) => (
            <div key={idx} className={`flex flex-col ${msg.role === 'user' ? 'items-end' : 'items-start'} gap-2 group`}>
              <div className="flex items-center gap-2 mb-1">
                {msg.role === 'assistant' && (
                  <div className="w-6 h-6 rounded bg-zinc-800 flex items-center justify-center">
                    <span className="material-symbols-outlined text-zinc-400 text-sm">smart_toy</span>
                  </div>
                )}
                <span className={`text-[11px] font-medium text-zinc-500 uppercase tracking-widest ${msg.role === 'user' ? 'text-right' : ''}`}>
                  {msg.role === 'user' ? 'You' : 'Assistant'}
                </span>
              </div>

              <div className={`max-w-[85%] text-[15px] leading-relaxed ${msg.role === 'user'
                ? 'bg-primary/10 border border-primary/20 text-zinc-900 dark:text-zinc-200 px-5 py-3 rounded-2xl rounded-tr-none'
                : 'text-zinc-800 dark:text-zinc-300 space-y-4'
                }`}>
                {msg.content.split('\n').map((line: string, i: number) => (
                  <p key={i} className="min-h-[1em]">{line}</p>
                ))}

                {msg.sources && msg.sources.length > 0 && (
                  <div className="mt-4 pt-4 border-t border-zinc-200 dark:border-zinc-800">
                    <p className="text-xs font-bold text-zinc-500 mb-2">SOURCES</p>
                    <div className="flex flex-wrap gap-2">
                      {msg.sources.map((s: string, i: number) => (
                        <span key={i} className="flex items-center gap-1.5 bg-zinc-100 dark:bg-zinc-800 px-2 py-1 rounded text-[10px] text-zinc-600 dark:text-zinc-400 border border-zinc-200 dark:border-zinc-700">
                          <span className="material-symbols-outlined !text-[12px]">description</span>
                          {s}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>
          ))}
          {isLoading && (
            <div className="flex flex-col items-start gap-2">
              <div className="flex items-center gap-2 mb-1">
                <div className="w-6 h-6 rounded bg-zinc-800 flex items-center justify-center">
                  <span className="material-symbols-outlined text-zinc-400 text-sm animate-spin">sync</span>
                </div>
                <span className="text-[11px] font-medium text-zinc-500 uppercase tracking-widest">Thinking...</span>
              </div>
            </div>
          )}
          <div ref={bottomRef} />
        </div>
      </div>

      {/* Sticky Bottom Input */}
      <div className="absolute bottom-0 left-0 right-0 p-4 md:p-6 pointer-events-none bg-gradient-to-t from-white dark:from-zinc-950 to-transparent">
        <div className="max-w-3xl mx-auto w-full pointer-events-auto">
          <div className="backdrop-blur-xl bg-white/50 dark:bg-zinc-900/50 border border-zinc-200/50 dark:border-white/10 rounded-2xl shadow-2xl p-2 flex flex-col gap-2">
            <textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }}
              className="w-full bg-transparent border-none focus:ring-0 text-zinc-900 dark:text-zinc-100 placeholder-zinc-500 py-3 px-3 resize-none text-[15px] max-h-48"
              placeholder="Ask your brain anything..."
              rows={1}
            />

            <div className="flex items-center justify-between px-1">
              <div className="flex items-center gap-2">
                {/* Model Selector */}
                <select
                  value={selectedModel}
                  onChange={(e) => setSelectedModel(e.target.value)}
                  className="bg-transparent text-[10px] font-bold text-zinc-500 uppercase tracking-wider border-none focus:ring-0 cursor-pointer hover:text-primary transition-colors"
                >
                  {models.map(m => <option key={m} value={m}>{m}</option>)}
                </select>

                {/* RAG Toggle */}
                <button
                  onClick={() => setUseRag(!useRag)}
                  className={`flex items-center gap-1.5 px-2 py-1 rounded-md text-[10px] font-bold transition-all ${useRag
                    ? 'bg-primary/10 text-primary border border-primary/20'
                    : 'bg-zinc-100 dark:bg-zinc-800 text-zinc-500 border border-zinc-200 dark:border-zinc-700'
                    }`}
                >
                  <span className="material-symbols-outlined !text-[12px]">{useRag ? 'database' : 'chat_bubble'}</span>
                  {useRag ? 'BRAIN ON' : 'CHAT ONLY'}
                </button>
              </div>

              <div className="flex items-center gap-1">
                <button className="bg-primary hover:bg-primary/90 text-white p-2.5 rounded-xl flex items-center justify-center transition-all shadow-lg shadow-primary/20" onClick={handleSend} disabled={isLoading}>
                  <span className="material-symbols-outlined text-[20px]">arrow_upward</span>
                </button>
              </div>
            </div>
          </div>
          <p className="text-[10px] text-center text-zinc-400 mt-4 uppercase tracking-[0.2em] font-medium">
            Second Brain v2.4.0 — AI Synchronized
          </p>
        </div>
      </div>
    </div>
  );
}
