import { useState, useEffect } from "react";
import { Button } from "../ui/Button";

interface ChatInputProps {
  onSend: (message: string, model: string, useRag: boolean) => void;
  isLoading?: boolean;
}

export function ChatInput({ onSend, isLoading }: ChatInputProps) {
  const [message, setMessage] = useState("");
  const [models, setModels] = useState<string[]>([]);
  const [selectedModel, setSelectedModel] = useState("llama3:8b");
  const [useRag, setUseRag] = useState(true);

  useEffect(() => {
    fetch("/api/models")
      .then((res) => res.json())
      .then((data) => {
        if (Array.isArray(data)) {
          setModels(data);
          if (data.length > 0 && !data.includes(selectedModel)) {
            setSelectedModel(data[0]);
          }
        }
      })
      .catch((err) => console.error("Failed to fetch models", err));
  }, []);

  const handleSubmit = () => {
    if (message.trim() && !isLoading) {
      onSend(message, selectedModel, useRag);
      setMessage("");
    }
  };

  return (
    <footer className="p-6 bg-gradient-to-t from-black via-black to-transparent">
      <div className="max-w-3xl mx-auto relative group">
        <div className="absolute -inset-0.5 bg-gradient-to-r from-primary/30 to-blue-500/30 rounded-xl blur opacity-0 group-focus-within:opacity-100 transition-opacity duration-300"></div>
        <div className="relative bg-zinc-900 border border-zinc-800 rounded-xl p-2 flex flex-col gap-2 shadow-2xl">
          <textarea
            className="w-full bg-transparent border-none focus:ring-0 text-white placeholder-zinc-500 py-2 px-3 resize-none text-[15px]"
            placeholder="Ask anything or search your brain..."
            rows={1}
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter" && !e.shiftKey) {
                e.preventDefault();
                handleSubmit();
              }
            }}
          />
          <div className="flex items-center justify-between px-2 pb-1">
            <div className="flex items-center gap-3">
              {/* Model Selector */}
              <div className="relative group/models">
                <button className="flex items-center gap-1.5 px-2 py-1 bg-zinc-800 rounded text-[10px] font-bold text-zinc-400 hover:text-white hover:bg-zinc-700 transition-colors">
                  <span className="material-symbols-outlined !text-[14px]">smart_toy</span>
                  {selectedModel}
                </button>
                <div className="absolute bottom-full mb-2 left-0 w-48 bg-zinc-900 border border-zinc-700 rounded-lg shadow-xl overflow-hidden hidden group-hover/models:block z-10">
                  {models.map(m => (
                    <button
                      key={m}
                      onClick={() => setSelectedModel(m)}
                      className={`w-full text-left px-3 py-2 text-xs hover:bg-zinc-800 ${selectedModel === m ? 'text-blue-400 font-bold' : 'text-zinc-400'}`}
                    >
                      {m}
                    </button>
                  ))}
                </div>
              </div>

              {/* RAG Toggle */}
              <button
                onClick={() => setUseRag(!useRag)}
                className={`flex items-center gap-1.5 px-2 py-1 rounded text-[10px] font-bold transition-all ${useRag
                    ? 'bg-blue-900/40 text-blue-400 border border-blue-500/30'
                    : 'bg-zinc-800 text-zinc-500 border border-transparent'
                  }`}
              >
                <span className="material-symbols-outlined !text-[14px]">{useRag ? 'database' : 'chat_bubble'}</span>
                {useRag ? 'Brain Search' : 'Chat Only'}
              </button>
            </div>

            <div className="flex items-center gap-3">
              <Button size="icon" className="h-8 w-8" disabled={!message.trim() || isLoading} onClick={handleSubmit}>
                <span className="material-symbols-outlined !text-[18px]">arrow_upward</span>
              </Button>
            </div>
          </div>
        </div>
      </div>
      <p className="text-center text-[11px] text-zinc-600 mt-4">
        Second Brain uses AI to synthesize your notes. Please verify important technical claims.
      </p>
    </footer>
  );
}
