added server component, provider, api for login request to backend and receive jjwt token, socket context , and auth connection

This commit is contained in:
sumona-banerjeee committed 2026-04-16 17:03:38 +05:30
1 parent a049c054e8
commit 6fa6415bfa
14 files changed
+6355 -190

No files matched your search

+460
View File
@@ -0,0 +1,460 @@
"use client";
import { useState, useEffect, useRef, useMemo } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/context/AuthContext";
import { useSocket, type ChatMessage, type RoomNotice } from "@/context/SocketContext";
import { fetchConversations, createConversation } from "@/lib/api";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
Send,
Phone,
Video,
Plus,
LogOut,
Loader2,
Hash,
Wifi,
WifiOff,
Users,
} from "lucide-react";
import {
Avatar,
AvatarFallback,
AvatarImage,
} from "@/components/ui/avatar";
import { useDebounce } from "@/hooks/useDebounce";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface Room {
id: string;
name: string;
isGroup: boolean;
}
/* ------------------------------------------------------------------ */
/* Backend rooms loaded dynamically */
/* ------------------------------------------------------------------ */
/* ------------------------------------------------------------------ */
/* ChatPage */
/* ------------------------------------------------------------------ */
export default function ChatPage() {
const router = useRouter();
const { user, isLoading: authLoading, logout } = useAuth();
const {
isConnected,
mySocketId,
joinRoom,
leaveRoom,
sendMessage,
messages,
notices,
currentRoom,
setCurrentRoom,
clearMessages,
} = useSocket();
const [text, setText] = useState("");
const [search, setSearch] = useState("");
const [activeTab, setActiveTab] = useState<"rooms" | "create">("rooms");
const [newRoomName, setNewRoomName] = useState("");
const [rooms, setRooms] = useState<Room[]>([]);
const debouncedSearch = useDebounce(search, 300);
const messagesEndRef = useRef<HTMLDivElement>(null);
// ── Auth guard ────────────────────────────────────────────────────
useEffect(() => {
if (!authLoading && !user) {
router.push("/login");
}
}, [authLoading, user, router]);
// ── Fetch rooms & Auto-join ─────────────────────────────────────
useEffect(() => {
if (!isConnected) return;
// Fetch conversations from API
fetchConversations()
.then((data) => {
// Map backend returned data to Room format
const loadedRooms = Array.isArray(data) ? data.map(c => ({
id: c._id || c.id || "unknown",
name: c.name || "Unnamed Group",
isGroup: c.type === "group" || c.isGroup || true
})) : [];
setRooms(loadedRooms);
// Auto-join first room
if (!currentRoom && loadedRooms.length > 0) {
const firstRoom = loadedRooms[0];
setCurrentRoom(firstRoom.id);
joinRoom(firstRoom.id);
}
})
.catch(err => {
console.error("Failed to fetch conversations", err);
});
}, [isConnected, currentRoom, joinRoom, setCurrentRoom]);
// ── Scroll to bottom on new messages ──────────────────────────────
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages, notices]);
// ── Filtered rooms ────────────────────────────────────────────────
const filteredRooms = useMemo(() => {
if (!debouncedSearch.trim()) return rooms;
return rooms.filter((r) =>
r.name.toLowerCase().includes(debouncedSearch.toLowerCase())
);
}, [rooms, debouncedSearch]);
// ── Messages for current room ─────────────────────────────────────
const roomMessages = useMemo(
() => messages.filter((m) => m.roomId === currentRoom),
[messages, currentRoom]
);
const roomNotices = useMemo(
() => notices.filter((n) => n.roomId === currentRoom),
[notices, currentRoom]
);
// ── Handlers ──────────────────────────────────────────────────────
const handleSelectRoom = (room: Room) => {
if (currentRoom === room.id) return;
// Leave old room
if (currentRoom) {
leaveRoom(currentRoom);
}
// Join new room
setCurrentRoom(room.id);
joinRoom(room.id);
};
const handleSend = () => {
if (!text.trim() || !currentRoom) return;
sendMessage(currentRoom, text.trim());
setText("");
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend();
}
};
const handleCreateRoom = async () => {
const name = newRoomName.trim();
if (!name) return;
try {
// Actually create the room on the backend
const created = await createConversation({ name, type: "group", participants: [user?.username || "unknown"] });
const newRoom: Room = {
id: created._id || created.id || name.toLowerCase().replace(/\s+/g, "-"),
name: created.name || name,
isGroup: true
};
setRooms((prev) => {
if (prev.find((r) => r.id === newRoom.id)) return prev;
return [...prev, newRoom];
});
setNewRoomName("");
setActiveTab("rooms");
handleSelectRoom(newRoom);
} catch (err) {
console.error("Error creating room", err);
}
};
const handleLogout = () => {
if (currentRoom) leaveRoom(currentRoom);
clearMessages();
logout();
};
// ── Loading / Auth guard ──────────────────────────────────────────
if (authLoading || !user) {
return (
<div className="flex min-h-screen items-center justify-center bg-background">
<Loader2 className="w-8 h-8 animate-spin text-primary" />
</div>
);
}
const selectedRoom = rooms.find((r) => r.id === currentRoom);
return (
<div className="flex h-screen">
{/* ================= LEFT SIDEBAR ================= */}
<div className="w-1/3 border-r flex flex-col bg-background">
{/* HEADER */}
<div className="flex items-center justify-between p-4">
<div className="flex items-center gap-2">
<h2 className="text-xl font-semibold">Chats</h2>
{/* Connection indicator */}
{isConnected ? (
<Wifi className="w-4 h-4 text-green-500" />
) : (
<WifiOff className="w-4 h-4 text-red-500" />
)}
</div>
<div className="flex items-center gap-1">
<Button
size="icon"
variant="ghost"
className="rounded-full"
onClick={() => setActiveTab(activeTab === "create" ? "rooms" : "create")}
title="Create room"
>
<Plus className="w-4 h-4" />
</Button>
<Button
size="icon"
variant="ghost"
className="rounded-full"
onClick={handleLogout}
title="Logout"
>
<LogOut className="w-4 h-4" />
</Button>
</div>
</div>
{/* USER INFO */}
<div className="px-4 pb-2 text-sm text-muted-foreground">
Logged in as <span className="font-medium text-foreground">{user.username}</span>
</div>
{/* TABS */}
<div className="flex gap-6 px-4 text-sm font-medium border-b pb-2">
<button
onClick={() => setActiveTab("rooms")}
className={`pb-1 ${
activeTab === "rooms"
? "text-primary border-b-2 border-primary"
: "text-muted-foreground"
}`}
>
Rooms
</button>
<button
onClick={() => setActiveTab("create")}
className={`pb-1 ${
activeTab === "create"
? "text-primary border-b-2 border-primary"
: "text-muted-foreground"
}`}
>
Create
</button>
</div>
{/* CREATE ROOM PANEL */}
{activeTab === "create" && (
<div className="p-4 space-y-3 border-b">
<Input
placeholder="Room name..."
value={newRoomName}
onChange={(e) => setNewRoomName(e.target.value)}
className="rounded-full bg-muted"
onKeyDown={(e) => e.key === "Enter" && handleCreateRoom()}
/>
<Button
onClick={handleCreateRoom}
disabled={!newRoomName.trim()}
className="w-full rounded-full"
>
<Plus className="w-4 h-4 mr-2" />
Create Room
</Button>
</div>
)}
{/* SEARCH */}
<div className="p-4">
<Input
placeholder="Search rooms..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="rounded-full bg-muted"
/>
</div>
{/* ROOM LIST */}
<div className="flex-1 overflow-y-auto px-2 space-y-1">
{filteredRooms.length === 0 && (
<p className="p-4 text-sm text-muted-foreground">
No rooms found
</p>
)}
{filteredRooms.map((room) => {
const isActive = currentRoom === room.id;
const unreadCount = messages.filter(
(m) => m.roomId === room.id && m.senderId !== mySocketId
).length;
return (
<div
key={room.id}
onClick={() => handleSelectRoom(room)}
className={`flex items-center gap-3 p-3 rounded-xl cursor-pointer transition
${
isActive
? "bg-primary text-primary-foreground"
: "hover:bg-muted"
}
`}
>
<div
className={`w-10 h-10 flex items-center justify-center rounded-full ${
isActive ? "bg-white/20" : "bg-primary/10"
}`}
>
{room.isGroup ? (
<Users className={`w-5 h-5 ${isActive ? "text-white" : "text-primary"}`} />
) : (
<Hash className={`w-5 h-5 ${isActive ? "text-white" : "text-primary"}`} />
)}
</div>
<div className="flex-1 overflow-hidden">
<h3 className="font-semibold truncate">{room.name}</h3>
<p className="text-xs opacity-70 truncate">
#{room.id}
</p>
</div>
</div>
);
})}
</div>
</div>
{/* ================= RIGHT CHAT ================= */}
<div className="w-2/3 flex flex-col">
{/* HEADER */}
<div className="p-4 border-b font-semibold flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 flex items-center justify-center rounded-full bg-primary/10">
<Users className="w-5 h-5 text-primary" />
</div>
<div>
<span className="text-lg">{selectedRoom?.name || "Select a room"}</span>
{selectedRoom && (
<p className="text-xs text-muted-foreground font-normal">
#{selectedRoom.id} · {isConnected ? "Connected" : "Disconnected"}
</p>
)}
</div>
</div>
{/* Call Buttons */}
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="icon"
onClick={() => console.log("Audio call")}
>
<Phone className="w-5 h-5" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => console.log("Video call")}
>
<Video className="w-5 h-5" />
</Button>
</div>
</div>
{/* MESSAGES */}
<div className="flex-1 p-4 space-y-2 overflow-y-auto">
{!currentRoom && (
<div className="flex items-center justify-center h-full text-muted-foreground">
Select a room to start chatting
</div>
)}
{currentRoom && roomMessages.length === 0 && roomNotices.length === 0 && (
<div className="flex items-center justify-center h-full text-muted-foreground">
No messages yet. Say something!
</div>
)}
{/* Interleave messages and notices by order */}
{roomMessages.map((msg, idx) => {
const isMe = msg.senderId === mySocketId;
return (
<div
key={`msg-${idx}`}
className={`flex ${isMe ? "justify-end" : "justify-start"}`}
>
<div className="flex flex-col max-w-xs">
{/* Show sender name for others */}
{!isMe && (
<span className="text-xs text-muted-foreground mb-1 ml-1">
{msg.username}
</span>
)}
<div
className={`px-4 py-2 rounded-xl ${
isMe
? "bg-primary text-primary-foreground"
: "bg-muted"
}`}
>
{msg.text}
</div>
</div>
</div>
);
})}
{/* Room notices */}
{roomNotices.map((notice, idx) => (
<div key={`notice-${idx}`} className="flex justify-center">
<span className="text-xs text-muted-foreground bg-muted/50 px-3 py-1 rounded-full">
{notice.message}
</span>
</div>
))}
<div ref={messagesEndRef} />
</div>
{/* INPUT */}
<div className="p-4 border-t flex gap-2">
<Input
value={text}
onChange={(e) => setText(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={
currentRoom
? `Message #${currentRoom}...`
: "Select a room first..."
}
disabled={!currentRoom || !isConnected}
/>
<Button
onClick={handleSend}
disabled={!currentRoom || !isConnected || !text.trim()}
>
<Send className="w-4 h-4" />
</Button>
</div>
</div>
</div>
);
}