"use client"; import { useState } from "react"; import { useLiveQuery } from "dexie-react-hooks"; import { db } from "@/lib/db"; import { v4 as uuidv4 } from "uuid"; import { Send, Bot, User, Trash2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; export default function ChatPage() { const [input, setInput] = useState(""); const [isLoading, setIsLoading] = useState(false); // Mesajları eski tarihten yeniye göre sıralayarak al (Sohbet akışı) const messages = useLiveQuery( () => db.chat_messages.orderBy("created_at").toArray(), [], ); // Ollama'ya veya harici API'ye mesaj gönder const handleSend = async (e: React.FormEvent) => { e.preventDefault(); if (!input.trim()) return; const userMessageContent = input.trim(); setInput(""); setIsLoading(true); const userMessage = { id: uuidv4(), role: "user" as const, content: userMessageContent, created_at: new Date().toISOString(), }; try { await db.chat_messages.add(userMessage); // LocalStorage'dan veya Environment ayarlarını okuyup backend API'ye gönderiyoruz const provider = localStorage.getItem("mindspace_ai_provider") || "groq"; const apiKey = localStorage.getItem("mindspace_api_key") || process.env.NEXT_PUBLIC_GROQ_API_KEY || ""; const res = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider, apiKey, userMessageContent, }), }); if (!res.ok) { const errData = await res.json(); throw new Error(errData.error || "Sunucu hatası oluştu."); } const data = await res.json(); const assistantMessage = { id: uuidv4(), role: "assistant" as const, content: data.reply || "Şu an cevap veremiyorum, lütfen ayarlarınızı kontrol edin.", created_at: new Date().toISOString(), }; await db.chat_messages.add(assistantMessage); } catch (error) { console.error(error); await db.chat_messages.add({ id: uuidv4(), role: "assistant" as const, content: "API Bağlantısı kurulamadı. Lütfen internetini veya Ayarlar sayfasından API anahtarını kontrol et.", created_at: new Date().toISOString(), }); } finally { setIsLoading(false); } }; const handleClearChat = async () => { await db.chat_messages.clear(); }; return (

AI Terapist (Sohbet)

Ollama veya bulut destekli akıllı asistanınızla konuşun.

{(!messages || messages.length === 0) && (

Sohbet henüz başlamadı. İlk mesajınızı yollayın!

)} {messages?.map((m) => (
{m.role === "user" ? ( ) : ( )}
{m.content}
))} {isLoading && (
)}
setInput(e.target.value)} placeholder="Bugün nasıl hissediyorsun? Ya da eski günlüklere dayanarak bir şeyler sor..." className="flex-1" />
); }