feat: implement AI chat interface with Supabase persistence and edge API route integration

This commit is contained in:
Poyraz Avsever
2026-05-08 14:32:07 +03:00
parent b1615d72ba
commit e38a809ff9
3 changed files with 582 additions and 361 deletions
+314 -112
View File
@@ -1,176 +1,378 @@
"use client";
import { useState } from "react";
import { useLiveQuery } from "dexie-react-hooks";
import { db } from "@/lib/db";
import { useEffect, useState, useRef } from "react";
import { Brain, Send, Paperclip, MoreHorizontal, Search, MessageSquare, Plus, FileText, CheckCircle2, Trash2 } from "lucide-react";
import { createClient } from "@/lib/supabase/client";
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() {
interface ChatSession {
id: string;
title: string;
created_at: string;
}
interface ChatMessage {
id: string;
session_id: string;
role: "user" | "assistant" | "system";
content: string;
created_at: string;
}
export default function AIChatPage() {
const [supabase] = useState(() => createClient());
const [sessions, setSessions] = useState<ChatSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState("");
const [isLoading, setIsLoading] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
// Mesajları eski tarihten yeniye göre sıralayarak al (Sohbet akışı)
const messages = useLiveQuery(
() => db.chat_messages.orderBy("created_at").toArray(),
[],
);
// Auto-scroll to bottom
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
// Ollama'ya veya harici API'ye mesaj gönder
const handleSend = async (e: React.FormEvent) => {
e.preventDefault();
if (!input.trim()) return;
useEffect(() => {
scrollToBottom();
}, [messages]);
// 1. Fetch Sessions on mount
useEffect(() => {
const fetchSessions = async () => {
const { data: { user } } = await supabase.auth.getUser();
if (!user) return;
const { data } = await supabase
.from("chat_sessions")
.select("*")
.eq("user_id", user.id)
.order("updated_at", { ascending: false });
if (data) {
setSessions(data);
if (data.length > 0) {
setActiveSessionId(data[0].id);
}
}
};
fetchSessions();
}, [supabase]);
// 2. Fetch Messages when session changes
useEffect(() => {
if (!activeSessionId) return;
const fetchMessages = async () => {
const { data } = await supabase
.from("chat_messages")
.select("*")
.eq("session_id", activeSessionId)
.order("created_at", { ascending: true });
if (data) {
setMessages(data as ChatMessage[]);
}
};
fetchMessages();
// Subscribe to real-time changes
const channel = supabase
.channel(`chat:${activeSessionId}`)
.on('postgres_changes', {
event: 'INSERT',
schema: 'public',
table: 'chat_messages',
filter: `session_id=eq.${activeSessionId}`
}, (payload) => {
setMessages(prev => {
if (prev.find(m => m.id === payload.new.id)) return prev;
return [...prev, payload.new as ChatMessage];
});
})
.subscribe();
return () => {
supabase.removeChannel(channel);
};
}, [activeSessionId, supabase]);
const handleNewChat = async () => {
const { data: { user } } = await supabase.auth.getUser();
if (!user) return;
const newSession = {
user_id: user.id,
title: "Yeni Sohbet",
updated_at: new Date().toISOString()
};
const { data, error } = await supabase
.from("chat_sessions")
.insert(newSession)
.select()
.single();
if (data) {
setSessions([data, ...sessions]);
setActiveSessionId(data.id);
setMessages([]);
}
};
const handleSend = async (e?: React.FormEvent) => {
if (e) e.preventDefault();
if (!input.trim() || isLoading) return;
const userMessageContent = input.trim();
setInput("");
// Ensure we have a session
let sessionId = activeSessionId;
const { data: { user } } = await supabase.auth.getUser();
if (!user) return;
if (!sessionId) {
const { data: newSess } = await supabase
.from("chat_sessions")
.insert({ user_id: user.id, title: userMessageContent.slice(0, 30) + "..." })
.select()
.single();
if (newSess) {
sessionId = newSess.id;
setActiveSessionId(sessionId);
setSessions([newSess, ...sessions]);
} else return;
}
setIsLoading(true);
const userMessage = {
// 1. Optimistic Update: Add User Message locally
const optimisticUserMsg: ChatMessage = {
id: uuidv4(),
role: "user" as const,
session_id: sessionId,
role: "user",
content: userMessageContent,
created_at: new Date().toISOString(),
created_at: new Date().toISOString()
};
setMessages(prev => [...prev, optimisticUserMsg]);
// 2. Save User Message to Supabase
await supabase.from("chat_messages").insert({
id: optimisticUserMsg.id,
session_id: sessionId,
role: "user",
content: userMessageContent
});
try {
await db.chat_messages.add(userMessage);
// 3. Fetch AI preferences for API call
const { data: settings } = await supabase
.from("user_settings")
.select("*")
.eq("user_id", user.id)
.single();
// 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 provider = settings?.ai_model || localStorage.getItem("mindspace_ai_provider") || "gemini";
const apiKey = settings?.api_key || localStorage.getItem("mindspace_api_key") || "";
// 4. Call AI API
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
provider,
apiKey,
userMessageContent,
}),
body: JSON.stringify({ provider, apiKey, userMessageContent }),
});
if (!res.ok) {
const errData = await res.json();
throw new Error(errData.error || "Sunucu hatası oluştu.");
}
if (!res.ok) throw new Error("AI API Error");
const data = await res.json();
const assistantMessage = {
// 5. Optimistic Update: Add Assistant Message locally
const assistantMsg: ChatMessage = {
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(),
session_id: sessionId,
role: "assistant",
content: data.reply || "Cevap üretilemedi.",
created_at: new Date().toISOString()
};
setMessages(prev => [...prev, assistantMsg]);
// 6. Save Assistant Message to Supabase
await supabase.from("chat_messages").insert({
id: assistantMsg.id,
session_id: sessionId,
role: "assistant",
content: assistantMsg.content
});
// 7. Update session title if it was default
const currentSession = sessions.find(s => s.id === sessionId);
if (currentSession?.title === "Yeni Sohbet") {
const newTitle = userMessageContent.slice(0, 40);
await supabase.from("chat_sessions").update({ title: newTitle }).eq("id", sessionId);
setSessions(prev => prev.map(s => s.id === sessionId ? { ...s, title: newTitle } : s));
}
await db.chat_messages.add(assistantMessage);
} catch (error) {
console.error(error);
await db.chat_messages.add({
const errorMsg: ChatMessage = {
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(),
session_id: sessionId,
role: "assistant",
content: "Hata oluştu. Lütfen Ayarlar sayfasından API anahtarınızı kontrol edin.",
created_at: new Date().toISOString()
};
setMessages(prev => [...prev, errorMsg]);
await supabase.from("chat_messages").insert({
id: errorMsg.id,
session_id: sessionId,
role: "assistant",
content: errorMsg.content
});
} finally {
setIsLoading(false);
}
};
const handleClearChat = async () => {
await db.chat_messages.clear();
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend();
}
};
const deleteSession = async (id: string, e: React.MouseEvent) => {
e.stopPropagation();
await supabase.from("chat_sessions").delete().eq("id", id);
setSessions(prev => prev.filter(s => s.id !== id));
if (activeSessionId === id) {
setActiveSessionId(null);
setMessages([]);
}
};
return (
<div className="flex flex-col h-[calc(100vh-4rem)] p-4 max-w-4xl mx-auto w-full">
<div className="flex items-center justify-between mb-4">
<div>
<h1 className="text-2xl font-bold text-foreground">
AI Terapist (Sohbet)
<div className="mx-auto max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500 h-[calc(100vh-80px)] flex flex-col text-foreground font-sans">
{/* Top Header */}
<div className="flex items-center justify-between pb-4 border-b border-white/5 mt-4 shrink-0">
<h1 className="text-lg font-medium text-muted-foreground flex items-center gap-2">
<Brain className="h-5 w-5 text-primary" />
<span className="text-foreground">MindSpace</span> / AI Assistant
</h1>
<p className="text-sm text-muted-foreground">
Ollama veya bulut destekli akıllı asistanınızla konuşun.
</p>
<div className="flex items-center gap-3">
<button onClick={handleNewChat} className="bg-primary hover:bg-primary/90 text-primary-foreground border border-primary/20 px-4 py-1.5 rounded-sm text-xs font-semibold flex items-center gap-2 transition-colors shadow-lg shadow-primary/20">
<Plus className="h-4 w-4" />
NEW CHAT
</button>
</div>
<Button
variant="outline"
size="icon"
onClick={handleClearChat}
title="Sohbeti Temizle"
>
<Trash2 className="w-4 h-4 text-destructive" />
</Button>
</div>
<div className="flex-1 overflow-y-auto p-4 space-y-4 rounded-xl border border-border bg-card shadow-sm mb-4">
{(!messages || messages.length === 0) && (
<div className="flex flex-col items-center justify-center h-full text-muted-foreground">
<Bot className="w-12 h-12 mb-2 opacity-50" />
<p>Sohbet henüz başlamadı. İlk mesajınızı yollayın!</p>
{/* Main Chat Interface */}
<div className="flex-1 flex gap-6 mt-6 min-h-0">
{/* Left Sidebar: Chat Sessions */}
<div className="hidden lg:flex w-72 flex-col gap-4 shrink-0 border border-white/5 bg-[#0A0710] rounded-sm overflow-hidden">
<div className="p-4 border-b border-white/5 bg-[#0F0B15]/50">
<div className="bg-[#150F1D] border border-white/5 rounded-sm px-3 py-2 flex items-center gap-2">
<Search className="h-4 w-4 text-muted-foreground" />
<input
type="text"
placeholder="Search history..."
className="bg-transparent border-none outline-none text-xs w-full placeholder:text-muted-foreground/50 text-foreground"
/>
</div>
</div>
<div className="flex-1 overflow-y-auto tiny-scrollbar p-3 space-y-1">
<div className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground px-2 py-1 mb-1">Recent Conversations</div>
{sessions.map((session) => (
<div
key={session.id}
onClick={() => setActiveSessionId(session.id)}
className={`group flex items-center gap-3 p-3 rounded-sm cursor-pointer transition-colors ${activeSessionId === session.id ? 'bg-[#1F172B] border border-primary/30 text-primary' : 'hover:bg-white/5 text-muted-foreground hover:text-foreground border border-transparent'}`}
>
<MessageSquare className="h-4 w-4 shrink-0" />
<div className="flex-1 min-w-0">
<div className="text-sm font-medium truncate">{session.title}</div>
<div className="text-[10px] mt-0.5 opacity-60">{new Date(session.created_at).toLocaleDateString()}</div>
</div>
<button onClick={(e) => deleteSession(session.id, e)} className="opacity-0 group-hover:opacity-100 p-1 hover:bg-white/10 rounded-sm transition-opacity">
<Trash2 className="h-3.5 w-3.5 text-red-400" />
</button>
</div>
))}
</div>
</div>
{/* Right Side: Active Chat Area */}
<div className="flex-1 flex flex-col rounded-sm border border-white/5 bg-[#0A0710] overflow-hidden relative">
{/* Chat Messages Area */}
<div className="flex-1 overflow-y-auto tiny-scrollbar p-6 space-y-8">
{messages.length === 0 && !isLoading && (
<div className="flex flex-col items-center justify-center h-full text-muted-foreground opacity-60">
<Brain className="w-16 h-16 mb-4 text-primary opacity-50" />
<p className="text-sm font-medium">Hello! I am your MindSpace AI Assistant.</p>
<p className="text-xs mt-1">Start a conversation or select a session from history.</p>
</div>
)}
{messages?.map((m) => (
<div
key={m.id}
className={`flex w-full ${m.role === "user" ? "justify-end" : "justify-start"}`}
>
<div
className={`flex gap-2 max-w-[80%] ${m.role === "user" ? "flex-row-reverse" : "flex-row"}`}
>
<div
className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${m.role === "user" ? "bg-primary text-primary-foreground" : "bg-secondary text-secondary-foreground"}`}
>
{m.role === "user" ? (
<User className="w-4 h-4" />
) : (
<Bot className="w-4 h-4" />
{messages.map((m) => (
<div key={m.id} className={`flex items-start gap-4 max-w-4xl ${m.role === "user" ? "ml-auto" : "mr-auto"}`}>
{m.role === "assistant" && (
<div className="h-8 w-8 rounded-sm bg-primary/20 border border-primary/30 flex items-center justify-center shrink-0">
<Brain className="h-5 w-5 text-primary" />
</div>
)}
<div className={`flex-1 p-5 ${m.role === "user" ? "bg-[#150F1D] border border-white/10 rounded-sm rounded-tr-none" : "bg-[linear-gradient(135deg,rgba(108,91,176,0.05)_0%,rgba(10,7,16,0)_100%)] border border-primary/10 rounded-sm rounded-tl-none"}`}>
<p className="text-sm leading-relaxed whitespace-pre-wrap">{m.content}</p>
</div>
<div
className={`p-3 rounded-xl ${m.role === "user" ? "bg-primary text-primary-foreground rounded-tr-none" : "bg-muted text-foreground rounded-tl-none border border-border"}`}
>
{m.content}
</div>
</div>
{m.role === "user" && (
<div className="h-8 w-8 rounded-sm bg-[#1F172B] border border-white/10 flex items-center justify-center font-bold text-foreground shrink-0 text-[10px]">ME</div>
)}
</div>
))}
{isLoading && (
<div className="flex w-full justify-start">
<div className="flex gap-2 max-w-[80%]">
<div className="w-8 h-8 rounded-full bg-secondary text-secondary-foreground flex items-center justify-center shrink-0">
<Bot className="w-4 h-4" />
</div>
<div className="p-3 rounded-xl bg-muted text-foreground rounded-tl-none border border-border flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-primary/50 animate-bounce" />
<div className="w-2 h-2 rounded-full bg-primary/50 animate-bounce delay-75" />
<div className="w-2 h-2 rounded-full bg-primary/50 animate-bounce delay-150" />
</div>
</div>
<div className="flex items-center gap-2 text-primary text-xs ml-12">
<span className="relative flex h-2 w-2">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"></span>
<span className="relative inline-flex rounded-full h-2 w-2 bg-primary"></span>
</span>
MindSpace AI is thinking...
</div>
)}
<div ref={messagesEndRef} />
</div>
<form onSubmit={handleSend} className="flex gap-2 items-center">
<Input
disabled={isLoading}
{/* Chat Input Box */}
<div className="p-4 border-t border-white/5 bg-[#0F0B15]/80 backdrop-blur-sm">
<div className="max-w-4xl mx-auto flex flex-col bg-[#150F1D] border border-white/10 rounded-sm focus-within:border-primary/50 transition-colors p-2 shadow-2xl">
<textarea
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Bugün nasıl hissediyorsun? Ya da eski günlüklere dayanarak bir şeyler sor..."
className="flex-1"
onKeyDown={handleKeyDown}
disabled={isLoading}
placeholder="Message your MindSpace AI... (Press Enter to send)"
className="w-full bg-transparent border-none outline-none text-sm text-foreground resize-none p-2 min-h-[60px] tiny-scrollbar disabled:opacity-50"
/>
<Button type="submit" size="icon" disabled={isLoading || !input.trim()}>
<Send className="w-4 h-4" />
</Button>
</form>
<div className="flex items-center justify-between mt-2 pt-2 border-t border-white/5">
<div className="flex gap-2">
<button className="p-1.5 hover:bg-white/10 rounded-sm text-muted-foreground transition-colors" title="Attach Context"><Paperclip className="h-4 w-4" /></button>
<button className="p-1.5 hover:bg-white/10 rounded-sm text-muted-foreground transition-colors" title="Settings"><MoreHorizontal className="h-4 w-4" /></button>
</div>
<button
onClick={handleSend}
disabled={isLoading || !input.trim()}
className="bg-primary hover:bg-primary/90 text-primary-foreground p-2 rounded-sm transition-colors shadow-lg shadow-primary/20 disabled:opacity-50"
>
<Send className="h-4 w-4" />
</button>
</div>
</div>
<p className="text-center text-[10px] text-muted-foreground mt-3">AI can make mistakes. Verify important decisions.</p>
</div>
</div>
</div>
</div>
);
}
+202 -211
View File
@@ -1,305 +1,296 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { Bot, KeyRound, Save, User } from "lucide-react";
import { User, Bell, Shield, Blocks, Brain, CreditCard, Save, Key, AlertTriangle } from "lucide-react";
import { updatePassword, updateProfile } from "./actions";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
type AiProvider = "groq" | "ollama" | "openai";
function getInitialAiProvider(): AiProvider {
if (typeof window === "undefined") {
return "groq";
}
const savedProvider = localStorage.getItem("mindspace_ai_provider");
return savedProvider === "ollama" || savedProvider === "openai"
? savedProvider
: "groq";
}
function getInitialApiKey() {
if (typeof window === "undefined") {
return "";
}
return localStorage.getItem("mindspace_api_key") ?? "";
}
type AiProvider = "groq" | "ollama" | "openai" | "gemini";
export default function SettingsPage() {
const [aiProvider, setAiProvider] = useState<AiProvider>(getInitialAiProvider);
const [apiKey, setApiKey] = useState(getInitialApiKey);
const [saveStatus, setSaveStatus] = useState("");
const [activeTab, setActiveTab] = useState("AI Preferences");
// Profile States
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [avatarUrl, setAvatarUrl] = useState("");
const [profileSaveStatus, setProfileSaveStatus] = useState("");
const [passwordSaveStatus, setPasswordSaveStatus] = useState("");
const [supabase] = useState(() => createClient());
// Security States
const [passwordSaveStatus, setPasswordSaveStatus] = useState("");
const formRef = useRef<HTMLFormElement>(null);
// AI States
const [aiProvider, setAiProvider] = useState<AiProvider>("gemini");
const [apiKey, setApiKey] = useState("");
const [aiSaveStatus, setAiSaveStatus] = useState("");
// Supabase
const [supabase] = useState(() => createClient());
const tabs = [
{ name: "Profile & Account", icon: User },
{ name: "AI Preferences", icon: Brain },
{ name: "Security", icon: Shield },
{ name: "Integrations", icon: Blocks },
{ name: "Notifications", icon: Bell },
{ name: "Billing & Plans", icon: CreditCard },
];
useEffect(() => {
let isActive = true;
const fetchProfile = async () => {
const {
data: { user },
} = await supabase.auth.getUser();
const fetchData = async () => {
const { data: { user } } = await supabase.auth.getUser();
if (!user || !isActive) return;
if (!user || !isActive) {
return;
}
const { data } = await supabase
// 1. Fetch Profile
const { data: profile } = await supabase
.from("profiles")
.select("*")
.eq("id", user.id)
.single();
if (!data || !isActive) {
return;
if (profile && isActive) {
setFirstName(profile.first_name || "");
setLastName(profile.last_name || "");
setAvatarUrl(profile.avatar_url || "");
}
setFirstName(data.first_name || "");
setLastName(data.last_name || "");
setAvatarUrl(data.avatar_url || "");
// 2. Fetch User Settings from Supabase
const { data: settings } = await supabase
.from("user_settings")
.select("*")
.eq("user_id", user.id)
.single();
if (settings && isActive) {
setAiProvider((settings.ai_model as AiProvider) || "gemini");
setApiKey(settings.api_key || "");
// Also sync to local storage for existing API route calls if they use it
localStorage.setItem("mindspace_ai_provider", settings.ai_model);
localStorage.setItem("mindspace_api_key", settings.api_key || "");
}
};
void fetchProfile();
return () => {
isActive = false;
};
void fetchData();
return () => { isActive = false; };
}, [supabase]);
const handleSaveAI = () => {
localStorage.setItem("mindspace_ai_provider", aiProvider);
localStorage.setItem("mindspace_api_key", apiKey);
setSaveStatus("Ayarlar başarıyla kaydedildi!");
window.setTimeout(() => setSaveStatus(""), 3000);
};
const handleProfileAction = async (formData: FormData) => {
const response = await updateProfile(formData);
if (response?.error) {
setProfileSaveStatus(`Hata: ${response.error}`);
} else {
setProfileSaveStatus("Profil başarıyla güncellendi!");
setProfileSaveStatus("Profil güncellendi!");
const avatar = formData.get("avatar");
if (avatar instanceof File && avatar.size > 0) {
window.location.reload();
if (avatar instanceof File && avatar.size > 0) window.location.reload();
}
}
window.setTimeout(() => setProfileSaveStatus(""), 3000);
setTimeout(() => setProfileSaveStatus(""), 3000);
};
const handlePasswordAction = async (formData: FormData) => {
const response = await updatePassword(formData);
if (response?.error) {
setPasswordSaveStatus(`Hata: ${response.error}`);
} else {
setPasswordSaveStatus("Şifre başarıyla güncellendi!");
setPasswordSaveStatus("Şifre güncellendi!");
formRef.current?.reset();
}
setTimeout(() => setPasswordSaveStatus(""), 3000);
};
window.setTimeout(() => setPasswordSaveStatus(""), 3000);
const handleSaveAI = async () => {
try {
const { data: { user } } = await supabase.auth.getUser();
if (!user) throw new Error("Giriş yapılmamış");
// Save to Supabase user_settings table
const { error } = await supabase
.from("user_settings")
.upsert({
user_id: user.id,
ai_model: aiProvider,
api_key: apiKey,
updated_at: new Date().toISOString()
}, { onConflict: 'user_id' });
if (error) throw error;
// Sync to localStorage as a redundant fallback
localStorage.setItem("mindspace_ai_provider", aiProvider);
localStorage.setItem("mindspace_api_key", apiKey);
setAiSaveStatus("Yapay Zeka ayarları kaydedildi!");
} catch (e: any) {
console.error(e);
setAiSaveStatus("Hata oluştu, veritabanına kaydedilemedi.");
}
setTimeout(() => setAiSaveStatus(""), 3000);
};
return (
<div className="mx-auto flex w-full max-w-2xl flex-col gap-6 p-4">
<div>
<h1 className="text-3xl font-bold text-foreground">Ayarlar</h1>
<p className="mt-1 text-muted-foreground">
Kullanıcı profili ve yapay zeka asistanı yapılandırmanızı yönetin.
</p>
<div className="mx-auto max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500 h-[calc(100vh-80px)] flex flex-col text-foreground font-sans space-y-6">
<div className="flex items-center justify-between pb-4 border-b border-white/5 mt-4 shrink-0">
<h1 className="text-lg font-medium text-muted-foreground">
<span className="text-foreground">Settings</span> / {activeTab}
</h1>
</div>
<div className="flex flex-col space-y-6 rounded-xl border border-border bg-card p-6 shadow-sm">
<div className="flex items-center gap-3 border-b border-border/50 pb-4">
<User className="h-6 w-6 text-primary" />
<h2 className="text-xl font-semibold">Kullanıcı Profili</h2>
<div className="flex flex-col md:flex-row gap-8 flex-1 min-h-0">
{/* Settings Sidebar */}
<div className="w-full md:w-64 flex flex-col gap-1 shrink-0">
{tabs.map((tab) => {
const Icon = tab.icon;
return (
<button
key={tab.name}
onClick={() => setActiveTab(tab.name)}
className={`flex items-center gap-3 px-4 py-3 rounded-sm text-sm font-medium transition-colors text-left ${
activeTab === tab.name
? "bg-[#1F172B] text-primary border border-primary/20 shadow-inner"
: "text-muted-foreground hover:bg-white/5 hover:text-foreground border border-transparent"
}`}
>
<Icon className={`h-4 w-4 ${activeTab === tab.name ? "text-primary" : "text-muted-foreground"}`} />
{tab.name}
</button>
)
})}
</div>
<form action={handleProfileAction} className="space-y-4">
<div className="mb-6 flex items-center gap-4">
{/* Settings Content Area */}
<div className="flex-1 rounded-sm border border-white/5 bg-[#0A0710] p-8 overflow-y-auto tiny-scrollbar">
{activeTab === "Profile & Account" && (
<div className="max-w-2xl animate-in fade-in duration-300">
<h2 className="text-xl font-bold mb-6">User Profile</h2>
<form action={handleProfileAction} className="space-y-6">
<div className="flex items-center gap-4 mb-6">
{avatarUrl ? (
<>
{/* Avatar URL dış kaynaklı olduğu için bu önizlemede native img kullanıyoruz. */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={avatarUrl}
alt="Avatar"
className="h-16 w-16 rounded-full border border-border object-cover"
/>
</>
<img src={avatarUrl} alt="Avatar" className="h-16 w-16 rounded-full border border-white/10 object-cover" />
) : (
<div className="flex h-16 w-16 items-center justify-center rounded-full border border-border bg-muted">
<div className="flex h-16 w-16 items-center justify-center rounded-full border border-white/10 bg-[#150F1D]">
<User className="h-8 w-8 text-muted-foreground" />
</div>
)}
<div className="flex-1 space-y-1">
<Label htmlFor="avatar">Profil Fotoğrafı Yükle</Label>
<Input id="avatar" name="avatar" type="file" accept="image/*" />
<label className="text-sm font-medium">Profil Fotoğrafı</label>
<input id="avatar" name="avatar" type="file" accept="image/*" className="block w-full text-xs text-muted-foreground file:mr-4 file:py-1.5 file:px-3 file:rounded-sm file:border-0 file:text-xs file:font-semibold file:bg-primary/20 file:text-primary hover:file:bg-primary/30 transition-colors" />
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="firstName">Ad</Label>
<Input
id="firstName"
name="firstName"
value={firstName}
onChange={(event) => setFirstName(event.target.value)}
/>
<label className="text-sm font-medium">Ad</label>
<input name="firstName" value={firstName} onChange={(e) => setFirstName(e.target.value)} className="w-full bg-[#150F1D] border border-white/10 rounded-sm px-3 py-2 text-sm outline-none focus:border-primary/50 transition-colors" />
</div>
<div className="space-y-2">
<Label htmlFor="lastName">Soyad</Label>
<Input
id="lastName"
name="lastName"
value={lastName}
onChange={(event) => setLastName(event.target.value)}
/>
<label className="text-sm font-medium">Soyad</label>
<input name="lastName" value={lastName} onChange={(e) => setLastName(e.target.value)} className="w-full bg-[#150F1D] border border-white/10 rounded-sm px-3 py-2 text-sm outline-none focus:border-primary/50 transition-colors" />
</div>
</div>
<div className="mt-4 flex items-center gap-4">
<Button type="submit" className="w-max">
<Save className="mr-2 h-4 w-4" />
Profili Kaydet
</Button>
{profileSaveStatus && (
<span
className={`text-sm ${
profileSaveStatus.startsWith("Hata")
? "text-red-500"
: "text-green-600 dark:text-green-400"
}`}
>
{profileSaveStatus}
</span>
)}
<div className="flex items-center gap-4 mt-6">
<button type="submit" className="bg-primary hover:bg-primary/90 text-primary-foreground px-4 py-2 rounded-sm text-xs font-semibold flex items-center gap-2 transition-colors">
<Save className="h-4 w-4" /> Profili Kaydet
</button>
{profileSaveStatus && <span className="text-sm text-emerald-400">{profileSaveStatus}</span>}
</div>
</form>
</div>
<div className="flex flex-col space-y-6 rounded-xl border border-border bg-card p-6 shadow-sm">
<div className="flex items-center gap-3 border-b border-border/50 pb-4">
<KeyRound className="h-6 w-6 text-primary" />
<h2 className="text-xl font-semibold">Şifre Değiştir</h2>
</div>
<form ref={formRef} action={handlePasswordAction} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="password">Yeni Şifre</Label>
<Input
id="password"
name="password"
type="password"
minLength={6}
placeholder="En az 6 karakter"
required
/>
</div>
<div className="mt-4 flex items-center gap-4">
<Button type="submit" className="w-max">
<Save className="mr-2 h-4 w-4" />
Şifreyi Güncelle
</Button>
{passwordSaveStatus && (
<span
className={`text-sm ${
passwordSaveStatus.startsWith("Hata")
? "text-red-500"
: "text-green-600 dark:text-green-400"
}`}
>
{passwordSaveStatus}
</span>
)}
{activeTab === "Security" && (
<div className="max-w-2xl animate-in fade-in duration-300">
<h2 className="text-xl font-bold mb-6">Şifre İşlemleri</h2>
<form ref={formRef} action={handlePasswordAction} className="space-y-6">
<div className="space-y-2">
<label className="text-sm font-medium">Yeni Şifre</label>
<input name="password" type="password" minLength={6} placeholder="En az 6 karakter" required className="w-full bg-[#150F1D] border border-white/10 rounded-sm px-3 py-2 text-sm outline-none focus:border-primary/50 transition-colors" />
</div>
<div className="flex items-center gap-4">
<button type="submit" className="bg-primary hover:bg-primary/90 text-primary-foreground px-4 py-2 rounded-sm text-xs font-semibold flex items-center gap-2 transition-colors">
<Save className="h-4 w-4" /> Şifreyi Güncelle
</button>
{passwordSaveStatus && <span className="text-sm text-emerald-400">{passwordSaveStatus}</span>}
</div>
</form>
</div>
)}
<div className="flex flex-col space-y-6 rounded-xl border border-border bg-card p-6 shadow-sm">
<div className="flex items-center gap-3 border-b border-border/50 pb-4">
<Bot className="h-6 w-6 text-primary" />
<h2 className="text-xl font-semibold">Terapist (AI) Ayarları</h2>
{activeTab === "AI Preferences" && (
<div className="max-w-2xl animate-in fade-in duration-300">
<h2 className="text-xl font-bold mb-6">AI Assistant Configuration</h2>
<div className="space-y-8">
<div>
<h3 className="text-sm font-semibold mb-3 border-b border-white/5 pb-2">Model ve Sağlayıcı Seçimi</h3>
<div className="grid grid-cols-2 gap-4">
<label onClick={() => setAiProvider("gemini")} className={`flex flex-col p-4 rounded-sm cursor-pointer relative overflow-hidden transition-colors ${aiProvider === "gemini" ? "border border-primary bg-primary/10" : "border border-white/10 bg-[#150F1D] opacity-60 hover:opacity-100"}`}>
{aiProvider === "gemini" && <div className="absolute top-0 right-0 p-2"><div className="w-2 h-2 rounded-full bg-primary"></div></div>}
<span className="font-bold text-sm mb-1">Google Gemini</span>
<span className="text-[11px] text-muted-foreground leading-tight">Gelişmiş akıl yürütme. (Varsayılan)</span>
</label>
<label onClick={() => setAiProvider("openai")} className={`flex flex-col p-4 rounded-sm cursor-pointer relative overflow-hidden transition-colors ${aiProvider === "openai" ? "border border-primary bg-primary/10" : "border border-white/10 bg-[#150F1D] opacity-60 hover:opacity-100"}`}>
{aiProvider === "openai" && <div className="absolute top-0 right-0 p-2"><div className="w-2 h-2 rounded-full bg-primary"></div></div>}
<span className="font-bold text-sm mb-1">OpenAI (GPT)</span>
<span className="text-[11px] text-muted-foreground leading-tight">GPT-4o veya GPT-4.</span>
</label>
<label onClick={() => setAiProvider("groq")} className={`flex flex-col p-4 rounded-sm cursor-pointer relative overflow-hidden transition-colors ${aiProvider === "groq" ? "border border-primary bg-primary/10" : "border border-white/10 bg-[#150F1D] opacity-60 hover:opacity-100"}`}>
{aiProvider === "groq" && <div className="absolute top-0 right-0 p-2"><div className="w-2 h-2 rounded-full bg-primary"></div></div>}
<span className="font-bold text-sm mb-1">Groq (Llama 3)</span>
<span className="text-[11px] text-muted-foreground leading-tight">Yüksek hızlı bulut çıkarımı.</span>
</label>
<label onClick={() => setAiProvider("ollama")} className={`flex flex-col p-4 rounded-sm cursor-pointer relative overflow-hidden transition-colors ${aiProvider === "ollama" ? "border border-primary bg-primary/10" : "border border-white/10 bg-[#150F1D] opacity-60 hover:opacity-100"}`}>
{aiProvider === "ollama" && <div className="absolute top-0 right-0 p-2"><div className="w-2 h-2 rounded-full bg-primary"></div></div>}
<span className="font-bold text-sm mb-1">Ollama (Yerel)</span>
<span className="text-[11px] text-muted-foreground leading-tight">Gizlilik odaklı yerel modeller.</span>
</label>
</div>
<div className="space-y-4">
<div className="space-y-2">
<Label>AI Sağlayıcısı</Label>
<Select
value={aiProvider}
onValueChange={(value) => setAiProvider(value as AiProvider)}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="Sağlayıcı seçin" />
</SelectTrigger>
<SelectContent>
<SelectItem value="ollama">
Ollama (Yerel ve Gizlilik Odaklı)
</SelectItem>
<SelectItem value="openai">OpenAI (GPT-4o vb.)</SelectItem>
<SelectItem value="groq">Groq (Llama 3 Bulut)</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Gizliliğiniz için yerel Ollama önerilir. Sunucunuzda çalışmayan
durumlarda OpenAI veya Groq gibi bulut çözümlerine
geçebilirsiniz.
</p>
</div>
{aiProvider !== "ollama" && (
<div className="space-y-2">
<Label>API Anahtarı ({aiProvider.toUpperCase()})</Label>
<Input
<div>
<h3 className="text-sm font-semibold mb-3 border-b border-white/5 pb-2">API Keys</h3>
<div className="bg-[#150F1D] border border-white/5 rounded-sm p-4 flex flex-col gap-3">
<div className="flex items-center gap-2">
<Key className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium">{aiProvider.toUpperCase()} API Key</span>
</div>
<input
type="password"
value={apiKey}
onChange={(event) => setApiKey(event.target.value)}
onChange={(e) => setApiKey(e.target.value)}
placeholder="sk-..."
className="bg-[#0A0710] border border-white/10 rounded-sm px-3 py-2 text-sm text-foreground w-full outline-none focus:border-primary/50"
/>
<p className="text-xs text-muted-foreground">
Anahtarınız sadece tarayıcınızın kendi local hafızasında saklanır;
herhangi bir sunucuya kaydedilmez.
</p>
</div>
</div>
)}
<div className="mt-4 flex items-center gap-4">
<Button type="button" onClick={handleSaveAI} className="w-max">
<Save className="mr-2 h-4 w-4" />
Kaydet
</Button>
{saveStatus && (
<span className="text-sm text-green-600 dark:text-green-400">
{saveStatus}
</span>
)}
<div className="flex items-center gap-4">
<button onClick={handleSaveAI} className="bg-primary hover:bg-primary/90 text-primary-foreground px-4 py-2 rounded-sm text-xs font-semibold flex items-center gap-2 transition-colors">
<Save className="h-4 w-4" /> Ayarları Kaydet
</button>
{aiSaveStatus && <span className="text-sm text-emerald-400">{aiSaveStatus}</span>}
</div>
</div>
</div>
)}
{["Integrations", "Notifications", "Billing & Plans"].includes(activeTab) && (
<div className="max-w-2xl animate-in fade-in duration-300 flex flex-col items-center justify-center h-full opacity-50 py-20">
<Blocks className="h-12 w-12 text-muted-foreground mb-4" />
<h2 className="text-lg font-bold mb-2">{activeTab}</h2>
<p className="text-sm text-center text-muted-foreground">Bu bölüm şu an geliştirme aşamasındadır.</p>
</div>
)}
</div>
</div>
</div>
+30 -2
View File
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
type ChatProvider = "groq" | "openai" | "ollama";
type ChatProvider = "groq" | "openai" | "ollama" | "gemini";
type ChatRequestBody = {
provider?: ChatProvider;
@@ -46,7 +46,35 @@ export async function POST(request: Request) {
let assistantReply = "";
if (provider === "groq") {
if (provider === "gemini") {
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent?key=${apiKey}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
system_instruction: {
parts: [{ text: "Sen MindSpace adlı kullanıcının kişisel yapay zeka terapistisin ve sırdaşısın. Şefkatli, yargılamayan ve destekleyici cevaplar ver. Kullanıcının iş süreçlerini asiste edebilirsin." }]
},
contents: [
{
parts: [{ text: userMessageContent }]
}
]
}),
}
);
if (!response.ok) {
throw new Error("Gemini API hatası");
}
const data = await response.json();
assistantReply = data.candidates?.[0]?.content?.parts?.[0]?.text ?? "";
} else if (provider === "groq") {
const response = await fetch(
"https://api.groq.com/openai/v1/chat/completions",
{