"use client"; import { useState, useRef, useEffect } from "react"; import { Send, MessageSquare, Sparkles, Loader2, User, Bot } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { ScrollArea } from "@/components/ui/scroll-area"; import { Avatar, AvatarFallback } from "@/components/ui/avatar"; // Assuming Avatar is in ui folder import { sendChatMessage } from "@/api/chat"; // Import the API function import ReactMarkdown from "react-markdown"; import remarkGfm from "remark-gfm"; // Interface for chat messages interface ChatMessage { id: string; role: "user" | "assistant"; // Changed sender to role content: string; timestamp: Date; } // Recommended prompts (keep or adjust as needed) const recommendedPrompts = [ { id: "prompt1", text: "What are common signs of nutrient deficiency in plants?", category: "Plant Health", }, { id: "prompt2", text: "How can I improve soil drainage?", category: "Soil Management", }, { id: "prompt3", text: "Explain integrated pest management (IPM).", category: "Pest Control", }, { id: "prompt4", text: "What are the benefits of crop rotation?", category: "Planning", }, { id: "prompt5", text: "Tell me about sustainable farming practices.", category: "Sustainability", }, { id: "prompt6", text: "How does weather affect crop yield?", category: "Weather", }, ]; export default function GeneralChatbotPage() { const [messages, setMessages] = useState([]); const [inputValue, setInputValue] = useState(""); const [isLoading, setIsLoading] = useState(false); // Loading state for API call const messagesEndRef = useRef(null); // Initialize with a welcome message useEffect(() => { setMessages([ { id: `assistant-${Date.now()}`, role: "assistant", content: "👋 Hello! I'm ForFarm Assistant, your general farming AI companion. Ask me anything about agriculture, crops, soil, weather, or best practices!", timestamp: new Date(), }, ]); }, []); // Scroll to bottom of messages useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }, [messages]); // Handle sending a message const handleSendMessage = async (content: string = inputValue) => { if (!content.trim() || isLoading) return; const userMessage: ChatMessage = { id: `user-${Date.now()}`, role: "user", content, timestamp: new Date(), }; setMessages((prev) => [...prev, userMessage]); setInputValue(""); setIsLoading(true); // Prepare history for the API call const apiHistory = messages .filter((msg) => msg.role === "user" || msg.role === "assistant") .map((msg) => ({ role: msg.role, text: msg.content })); try { // Call the API function *without* farmId and cropId const response = await sendChatMessage(userMessage.content, apiHistory); const assistantMessage: ChatMessage = { id: `assistant-${Date.now()}`, role: "assistant", content: response.response, timestamp: new Date(), }; setMessages((prev) => [...prev, assistantMessage]); } catch (error) { console.error("Error sending general chat message:", error); const errorMessage: ChatMessage = { id: `error-${Date.now()}`, role: "assistant", content: `Sorry, I encountered an issue. ${(error as Error).message || "Please try again later."}`, timestamp: new Date(), }; setMessages((prev) => [...prev, errorMessage]); } finally { setIsLoading(false); } }; // Handle clicking a recommended prompt const handlePromptClick = (promptText: string) => { setInputValue(promptText); // Directly send message after setting input // The handleSendMessage function will pick up the new inputValue // No need to call handleSendMessage here if the button triggers submit or calls it // Let's assume the button just sets the input and the user clicks send // OR: uncomment the line below if the button should send immediately // handleSendMessage(promptText); }; return (
{/* Header (Optional - can be simplified as it's part of the main layout) */}

General Farming Assistant

{/* Chat Area */}
{messages.map((message, i) => (
{message.role === "assistant" && ( )}
{message.content}

{message.timestamp.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}

{message.role === "user" && ( )}
))} {isLoading && (
Assistant is thinking...
)}
{/* Recommended prompts */}

Try asking...

{recommendedPrompts.slice(0, 5).map( ( prompt // Limit displayed prompts ) => ( ) )}
{/* Input area */}
{ e.preventDefault(); handleSendMessage(); }} className="flex gap-2 max-w-4xl mx-auto"> setInputValue(e.target.value)} placeholder="Ask the farming assistant..." className="flex-1 h-11" disabled={isLoading} onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSendMessage(); } }} />
); }