import { useEffect, useState, useRef, useMemo, useCallback, memo, type ChangeEvent } from "react";
import clsx from 'clsx';
import "./rds-comp-chat.scss";
import RdsAvatar from "../../raaghu-elements/rds-avatar/rds-avatar";
import { SendOutlined as SendIcon, SentimentSatisfiedAltOutlined as EmojiIcon, ChatBubbleOutlineOutlined as ChatIcon, FilterListOutlined as FilterIcon, MoreVertOutlined as MoreIcon, ArrowBackIosNew as ArrowBackIcon } from "@mui/icons-material";
import RdsInput from "../../raaghu-elements/rds-input/rds-input";
import RdsButton from "../../raaghu-elements/rds-button/rds-button";
import RdsCompEmojiGenerator from "../rds-comp-emoji-generator/rds-comp-emoji-generator";
import Box from "@mui/material/Box";
export interface Comment {
firstName: string;
lastName: string;
comment: string;
image?: string;
video?: string;
}
export interface UserData {
firstName: string;
lastName: string;
activeDotButton: boolean;
status: string;
size: string;
colorVariant: string;
time: string;
profilePic: string;
messageStatus: string;
comments: Comment[];
profileType?: string;
withProfilePic?: boolean;
style?: string;
}
export interface RdsCompChatProps {
isChatScreenEnabled: boolean;
userData: UserData[];
handleAddComment: (comment: Comment) => void;
currentUserCommentBgColor?: string;
currentUserCommentTextColor?: string;
otherUserCommentBgColor?: string;
OtherUserCommentTextColor?: string;
}
interface ChatMessageProps {
comment: Comment;
isCurrentUser: boolean;
currentUserCommentBgColor: string;
otherUserCommentBgColor: string;
currentUserCommentTextColor: string;
otherUserCommentTextColor: string;
}
const ChatMessage = memo(({
comment,
isCurrentUser,
currentUserCommentBgColor,
otherUserCommentBgColor,
currentUserCommentTextColor,
otherUserCommentTextColor
}: ChatMessageProps) => (
{comment.comment}
{comment.image &&

}
{comment.video && (
)}
));
ChatMessage.displayName = "ChatMessage";
const AVATAR_PROPS = { alt: "User Avatar", subText: "Designation", displayStyle: "with-name" as const, title: "Jane Doe", showDesignation: true, activeDotBottom: true, showName: true, src: "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=150&h=150&fit=crop&crop=face" };
const RdsCompChat = ({
isChatScreenEnabled,
userData,
handleAddComment: onAddComment,
currentUserCommentBgColor = "var(--rds-primary-main)",
currentUserCommentTextColor = "var(--rds-primary-contrast-text, var(--rds-neutral-0))",
otherUserCommentBgColor = "var(--rds-neutral-300)",
OtherUserCommentTextColor = "var(--rds-text-primary)"
}: RdsCompChatProps) => {
const [state, setState] = useState({
isMobile: window.innerWidth <= 600,
isSmallMobile: window.innerWidth <= 320,
showChatWindow: false,
commentText: "",
showEmojiPicker: false,
selectedIndex: null as number | null,
commentList: userData[0]?.comments || [],
showCamera: false,
activeTab: "chat" as "chat" | "media",
currentUser: userData[0]
});
const videoRef = useRef(null);
const canvasRef = useRef(null);
const emojiPickerRef = useRef(null);
const updateState = useCallback((updates: Partial) => {
setState((prev) => ({ ...prev, ...updates }));
}, []);
useEffect(() => {
const handleResize = () => updateState({
isMobile: window.innerWidth <= 600,
isSmallMobile: window.innerWidth <= 320,
});
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, [updateState]);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (emojiPickerRef.current && !emojiPickerRef.current.contains(event.target as Node)) {
updateState({ showEmojiPicker: false });
}
};
if (state.showEmojiPicker) {
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}
}, [state.showEmojiPicker, updateState]);
const handleUserSelect = useCallback((index: number) => {
if (index >= 0 && index < userData.length) {
updateState({
currentUser: userData[index],
commentList: userData[index].comments || [],
selectedIndex: index,
showChatWindow: state.isMobile
});
}
}, [state.isMobile, updateState, userData]);
const addComment = useCallback((newComment: Comment) => {
const updatedComments = [...state.commentList, newComment];
updateState({ commentList: updatedComments });
onAddComment?.(newComment);
}, [onAddComment, state.commentList, updateState]);
const handleAddComment = useCallback(() => {
if (state.commentText.trim() && state.currentUser) {
addComment({
firstName: state.currentUser.firstName,
lastName: state.currentUser.lastName,
comment: state.commentText,
});
updateState({ commentText: "" });
}
}, [addComment, state.commentText, state.currentUser, updateState]);
const handleEmojiSelect = useCallback((emoji: string) => {
setState((prev) => ({
...prev,
commentText: prev.commentText + emoji,
showEmojiPicker: false
}));
}, []);
const handleImageUpload = useCallback((event: ChangeEvent) => {
const file = event.target.files?.[0];
if (file?.type.startsWith("image/") && state.currentUser) {
const reader = new FileReader();
reader.onloadend = () =>
addComment({
firstName: state.currentUser!.firstName,
lastName: state.currentUser!.lastName,
comment: "",
image: reader.result as string,
});
reader.readAsDataURL(file);
}
}, [addComment, state.currentUser]);
const stopVideoStream = useCallback(() => {
const stream = videoRef.current?.srcObject as MediaStream;
stream?.getTracks().forEach(track => track.stop());
}, []);
const capturePhoto = useCallback(() => {
if (canvasRef.current && videoRef.current && state.currentUser) {
const context = canvasRef.current.getContext("2d");
canvasRef.current.width = videoRef.current.videoWidth;
canvasRef.current.height = videoRef.current.videoHeight;
context?.drawImage(videoRef.current, 0, 0, canvasRef.current.width, canvasRef.current.height);
addComment({
firstName: state.currentUser.firstName,
lastName: state.currentUser.lastName,
comment: "",
image: canvasRef.current.toDataURL("image/png"),
});
updateState({ showCamera: false });
stopVideoStream();
}
}, [addComment, state.currentUser, stopVideoStream, updateState]);
const mediaItems = useMemo(() => {
const items: { type: "image" | "video"; src: string }[] = [];
userData.forEach(user => user.comments?.forEach(c => {
if (c.image) items.push({ type: "image", src: c.image });
if (c.video) items.push({ type: "video", src: c.video });
}));
return items;
}, [userData]);
const showUserList = isChatScreenEnabled && (!state.isMobile || !state.showChatWindow);
const showChat = !isChatScreenEnabled || (state.isMobile ? state.showChatWindow : true);
const hasCommentText = state.commentText.trim().length > 0;
return (
{showUserList && (
{userData.map((item, index) => (
handleUserSelect(index)}>
{item.time}
))}
)}
{showChat && (
{state.isMobile && isChatScreenEnabled && (
)}
{["chat", "media"].map(tab => (
))}
{state.activeTab === "chat" ? (
<>
{state.commentList.map((comment) => {
const isCurrentUser = comment.firstName === state.currentUser?.firstName && comment.lastName === state.currentUser?.lastName;
return (
);
})}
{state.currentUser?.messageStatus &&
{state.currentUser.messageStatus}
}
>
) : (
{mediaItems.length === 0 ? No media available
: mediaItems.map((m) => (
{m.type === "image" ?

: (
)}
))}
)}
{state.showEmojiPicker && (
)}
document.getElementById("fileUpload")?.click()} />
updateState({ commentText: e.target.value })} onKeyDown={(e: KeyboardEvent) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleAddComment(); } }} />
)}
{state.showCamera && (
)}
);
};
RdsCompChat.displayName = "RdsCompChat";
export default RdsCompChat;