chatbot.js
"use client";
import { useState, useEffect, useRef } from "react";
import { getCookie } from "cookies-next";
import axios from "../../utils/axiosInstance";
import Spinner from "@/components/spinner";
import toast, { Toaster } from "react-hot-toast";
import InfiniteScroll from "react-infinite-scroll-component";
import {
PhotoIcon,
VideoCameraIcon,
DocumentTextIcon,
PaperAirplaneIcon,
PaperClipIcon,
XCircleIcon,
} from "@heroicons/react/24/outline";
export default function Chatbot({ contactId, name, whatsapp }) {
const [messages, setMessages] = useState([]);
const [nextPage, setNextPage] = useState(null);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true); // Indicates if there are more messages to load
const [renderedMessages, setRenderedMessages] = useState([]);
const [newMessage, setNewMessage] = useState("");
const [fileDetail, setFileDetail] = useState(null);
const [loadingMediaId, setLoadingMediaId] = useState(false);
const [showAttachments, setShowAttachments] = useState(false);
const [loader, setLoader] = useState(false);
const chatContainerRef = useRef(null);
const inputRef = useRef(null);
const attachmentRef = useRef(null);
// Fetch initial messages when the component mounts
useEffect(() => {
const fetchMessages = async () => {
setLoading(true);
try {
const response = await axios.get(
`${process.env.NEXT_PUBLIC_BASE_URL}/chat/`,
{
params: { contact_id: contactId },
}
);
const transformedMessages =
response.data?.results.reverse()?.map((msg) => ({
id: msg.id,
content: msg.content,
outgoing: msg.is_outgoing,
timestamp: msg.timestamp || msg.created_at,
messageType: msg.message_type,
fileId: msg.file_id,
mimeType: msg.mime_type,
filename: msg.filename,
})) || [];
setMessages(transformedMessages);
setNextPage(response.data.next);
setHasMore(!!response.data.next);
} catch (err) {
console.error("Failed to fetch messages:", err);
} finally {
setLoading(false);
}
};
if (contactId) fetchMessages();
}, [contactId]);
// Fetch more messages when the user scrolls up
const fetchMoreMessages = async () => {
if (!nextPage || loading) return;
setLoading(true);
try {
const response = await axios.get(nextPage);
const transformedMessages =
response.data?.results?.map((msg) => ({
id: msg.id,
content: msg.content,
outgoing: msg.is_outgoing,
timestamp: msg.timestamp || msg.created_at,
messageType: msg.message_type,
fileId: msg.file_id,
mimeType: msg.mime_type,
filename: msg.filename,
})) || [];
setMessages((prevMessages) => [...transformedMessages, ...prevMessages]);
setNextPage(response.data.next);
setHasMore(!!response.data.next);
} catch (err) {
console.error("Failed to fetch more messages:", err);
} finally {
setLoading(false);
}
};
// Detect when the user scrolls to the top
const handleScroll = () => {
if (chatContainerRef.current.scrollTop < 20 && hasMore) {
fetchMoreMessages();
}
};
// Close speed dial when clicking outside
useEffect(() => {
const handleClickOutside = (event) => {
if (
attachmentRef.current &&
!attachmentRef.current.contains(event.target)
) {
setShowAttachments(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
// Render message content with media URLs
useEffect(() => {
const renderMessages = async () => {
const rendered = await Promise.all(
messages.map(async (message) => ({
...message,
renderedContent: await renderMessageContent(message),
}))
);
setRenderedMessages(rendered);
};
renderMessages();
}, [messages]);
// Scroll to bottom when messages change
useEffect(() => {
if (chatContainerRef.current) {
chatContainerRef.current.scrollTop =
chatContainerRef.current.scrollHeight;
}
}, [renderedMessages]);
useEffect(() => {
if (chatContainerRef.current) {
chatContainerRef.current.scrollTop =
chatContainerRef.current.scrollHeight;
}
}, []);
// File Upload Handlers
const handleUploadFile = (type) => {
const input = document.createElement("input");
input.type = "file";
if (type === "image") {
input.accept = "image/jpeg, image/png";
} else if (type === "video") {
input.accept = "video/mp4, video/3gp";
} else if (type === "document") {
input.accept =
"application/pdf, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation, text/plain";
}
input.onchange = (event) => {
const file = event.target.files[0];
if (file) {
// Validate file size
const maxSize =
type === "image"
? 5 * 1024 * 1024 // 5 MB
: type === "video"
? 16 * 1024 * 1024 // 16 MB
: 100 * 1024 * 1024; // 100 MB
if (file.size > maxSize) {
alert(`The selected ${type} exceeds the maximum size limit.`);
return;
}
setFileDetail(file);
console.log(`Uploading ${type}:`, file);
// Add your upload logic here
}
};
input.click();
};
const handleSendMessage = async () => {
if (!newMessage.trim() && !fileDetail) return;
setLoader(true);
const phoneNumberId = getCookie("pni");
const contactId = whatsapp;
const accessToken = getCookie("at");
let message = {
id: Date.now(),
outgoing: true,
timestamp: new Date().toISOString(),
messageType: "text",
content: newMessage,
file_id: null,
mime_type: null,
filename: null,
sha256: null,
};
try {
// If there's a file to upload
if (fileDetail) {
const fileType = fileDetail.type.split("/")[0]; // "image", "video", "application" for document
const formData = new FormData();
formData.append("file", fileDetail);
formData.append("type", fileDetail.type);
formData.append("messaging_product", "whatsapp");
// Upload the media to Facebook
const uploadResponse = await fetch(
`https://graph.facebook.com/v21.0/${phoneNumberId}/media`,
{
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
},
body: formData,
}
);
if (!uploadResponse.ok) {
throw new Error("Failed to upload media to Facebook");
}
const uploadData = await uploadResponse.json();
const mediaId = uploadData.id;
message.file_id = mediaId;
message.mime_type = fileDetail.type;
message.filename = fileDetail.name;
// Determine message type for sending to WhatsApp
let whatsappMessageType =
fileType === "image"
? "image"
: fileType === "video"
? "video"
: "document";
// Build the document message payload
const messagePayload = {
messaging_product: "whatsapp",
recipient_type: "individual",
to: contactId,
type: whatsappMessageType,
[whatsappMessageType]: {
id: mediaId,
...(whatsappMessageType === "document" && {
filename: fileDetail.name,
}), // Include filename for document
...(newMessage.trim() && { caption: newMessage }), // Include caption if available
},
};
// Send the media message to WhatsApp
const sendMediaResponse = await fetch(
`https://graph.facebook.com/v21.0/${phoneNumberId}/messages`,
{
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify(messagePayload),
}
);
if (!sendMediaResponse.ok) {
throw new Error("Failed to send media message to WhatsApp");
}
const sendMediaData = await sendMediaResponse.json();
message.message_id = sendMediaData.messages[0].id;
message.messageType = whatsappMessageType;
} else {
// Send the text message to WhatsApp
const sendTextResponse = await fetch(
`https://graph.facebook.com/v21.0/${phoneNumberId}/messages`,
{
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
messaging_product: "whatsapp",
recipient_type: "individual",
to: contactId,
type: "text",
text: {
body: newMessage,
},
}),
}
);
if (!sendTextResponse.ok) {
throw new Error("Failed to send text message to WhatsApp");
}
const sendTextData = await sendTextResponse.json();
message.message_id = sendTextData.messages[0].id;
}
// Save the message to the backend
await axios.post(`${process.env.NEXT_PUBLIC_BASE_URL}/chat/`, {
contact: contactId,
message_id: message.message_id,
timestamp: message.timestamp,
message_type: message.messageType,
content: message.content || null,
file_id: message.file_id || null,
mime_type: message.mime_type || null,
filename: message.filename || null,
sha256: message.sha256 || null,
is_outgoing: true,
});
// Add the message to the local state
setMessages((prev) => [...prev, message]);
setNewMessage("");
setLoader(false);
toast.success("Message Sent");
setFileDetail(null); // Clear file input
if (inputRef.current) {
inputRef.current.style.height = "auto"; // Reset textarea height
}
} catch (err) {
setLoader(false);
toast.error("Message Not Sent");
console.error("Failed to send message:", err);
}
};
const formatTimestamp = (timestamp) => {
const date = new Date(timestamp);
return {
time: date.toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
hour12: true,
}),
date: date.toLocaleDateString([], {
year: "numeric",
month: "short",
day: "numeric",
}),
};
};
const fetchMediaUrl = async (fileId) => {
const accessToken = getCookie("at");
try {
const response = await fetch(
`https://graph.facebook.com/v21.0/${fileId}`,
{
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
if (!response.ok) {
throw new Error("Failed to fetch media URL");
}
const data = await response.json();
return data; // This contains the URL to fetch the media
} catch (error) {
console.error("Failed to fetch media URL:", error);
return null;
}
};
const loadMediaContent = async (mediaUrl) => {
let newWindow = null;
try {
// Open a new tab immediately to avoid popup blockers
newWindow = window.open("", "_blank");
if (!newWindow) {
throw new Error("Failed to open new window. Popup blocked?");
}
// Inform the user while content is loading
newWindow.document.write("<p>Loading content, please wait...</p>");
newWindow.document.close();
// Fetch the media content from the backend
const response = await fetch(
`/api/fetchMedia?url=${encodeURIComponent(mediaUrl)}`,
{ method: "GET" }
);
if (!response.ok) {
throw new Error("Failed to fetch media content");
}
// Get the content type from headers
const contentType = response.headers.get("Content-Type");
// Convert response to a blob
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
// Update the new window content based on the media type
newWindow.document.body.innerHTML = ""; // Clear the loading message
if (contentType.startsWith("image/")) {
// Display image
const img = newWindow.document.createElement("img");
img.src = objectUrl;
img.alt = "Fetched Media";
img.style = "max-width: 100%; height: auto;";
newWindow.document.body.appendChild(img);
} else if (contentType.startsWith("video/")) {
// Display video
const video = newWindow.document.createElement("video");
video.src = objectUrl;
video.controls = true;
video.style = "max-width: 100%; height: auto;";
newWindow.document.body.appendChild(video);
} else {
// Provide download link for other file types
const link = newWindow.document.createElement("a");
link.href = objectUrl;
link.download = `file.${contentType.split("/")[1]}`; // Dynamically determine file extension
link.textContent = "Click here to download the file";
link.style = "display: block; margin-top: 20px;";
newWindow.document.body.appendChild(link);
}
} catch (error) {
console.error("Failed to load media content:", error);
if (newWindow) {
newWindow.document.body.innerHTML = `<p style="color: red;">Failed to load content. Please try again later.</p>`;
}
}
};
const renderMessageContent = async (message) => {
const handleViewMedia = async () => {
setLoadingMediaId(true); // Start loader
try {
// Fetch the media URL data
const mediaUrlData = await fetchMediaUrl(message.fileId);
if (!mediaUrlData || !mediaUrlData.url) {
alert("Unable to fetch media URL.");
throw new Error("Invalid media URL data.");
}
console.log(mediaUrlData, "this is mediaUrl data");
// Load the media content and open it
await loadMediaContent(mediaUrlData.url);
} catch (error) {
console.error("Error viewing media:", error);
alert("Failed to view media. Please try again later.");
} finally {
setLoadingMediaId(false); // Stop loader regardless of success or failure
}
};
switch (message.messageType) {
case "text":
return (
<p className="break-words whitespace-pre-wrap text-gray-800">
{message.content}
</p>
);
case "image":
return (
<div>
<div className="bg-gray-100 p-3 rounded-lg max-w-[250px] shadow-md hover:shadow-lg">
{message.url ? (
<img
src={message.url}
alt={message.filename || "Image"}
className="w-full h-24 object-cover rounded-md mb-2"
/>
) : (
<div className="flex items-center justify-center h-20 bg-gray-200 rounded-md mb-2">
<PhotoIcon className="w-8 h-8 text-gray-500" />
</div>
)}
<div className="flex flex-col items-center">
<span className="text-gray-700 text-sm font-medium truncate">
{message.filename || "Image"}
</span>
<button
onClick={handleViewMedia}
disabled={loadingMediaId}
className={`mt-2 px-4 py-1 bg-indigo-600 text-white rounded-md text-sm hover:bg-indigo-500 ${
loadingMediaId ? "opacity-50 cursor-not-allowed" : ""
}`}
>
{loadingMediaId ? "Loading..." : "View"}
</button>
</div>
</div>
{/* Render message content outside the media card */}
{message.content && (
<div className="mt-3 text-gray-700 text-sm">
<p className="break-words whitespace-pre-wrap text-gray-800">
{message.content}
</p>
</div>
)}
</div>
);
case "video":
return (
<div>
<div className="bg-gray-100 p-3 rounded-lg max-w-[250px] shadow-md hover:shadow-lg">
<div className="flex items-center justify-center h-20 bg-gray-200 rounded-md mb-2">
<VideoCameraIcon className="w-8 h-8 text-gray-500" />
</div>
<div className="flex flex-col items-center">
<span className="text-gray-700 text-sm font-medium truncate">
{message.filename || "Video"}
</span>
<button
onClick={handleViewMedia}
disabled={loadingMediaId}
className={`mt-2 px-4 py-1 bg-indigo-600 text-white rounded-md text-sm hover:bg-indigo-500 ${
loadingMediaId ? "opacity-50 cursor-not-allowed" : ""
}`}
>
{loadingMediaId ? "Loading..." : "View"}
</button>
</div>
</div>
{/* Render message content outside the media card */}
{message.content && (
<div className="mt-3 text-gray-700 text-sm">
<p>{message.content}</p>
</div>
)}
</div>
);
case "document":
return (
<div>
<div className="bg-gray-100 p-3 rounded-lg max-w-[250px] shadow-md hover:shadow-lg">
<div className="flex items-center justify-center h-20 bg-gray-200 rounded-md mb-2">
<DocumentTextIcon className="w-8 h-8 text-gray-500" />
</div>
<div className="flex flex-col items-center">
<span className="text-gray-700 text-sm font-medium truncate">
{message.filename || "Document"}
</span>
<button
onClick={handleViewMedia}
disabled={loadingMediaId}
className={`mt-2 px-4 py-1 bg-indigo-600 text-white rounded-md text-sm hover:bg-indigo-500 ${
loadingMediaId ? "opacity-50 cursor-not-allowed" : ""
}`}
>
{loadingMediaId ? "Loading..." : "View"}
</button>
</div>
</div>
{/* Render message content outside the media card */}
{message.content && (
<div className="mt-3 text-gray-700 text-sm">
<p>{message.content}</p>
</div>
)}
</div>
);
case "button":
return (
<p className="break-words whitespace-pre-wrap text-gray-800">
{message.content}
</p>
);
default:
return <p className="text-gray-500">Unsupported message type</p>;
}
};
return (
<div className="flex flex-col h-screen max-h-screen">
{/* Header */}
<div className="sticky top-0 z-10 bg-gradient-to-r from-indigo-50 to-indigo-100 shadow-sm">
<div className="flex items-center p-4 space-x-4">
<div className="flex items-center justify-center h-12 w-12 rounded-full bg-indigo-200 text-indigo-700 text-xl font-bold">
{name.charAt(0).toUpperCase()}
</div>
<div>
<h1 className="text-xl font-semibold text-indigo-800">{name}</h1>
<p className="text-sm text-indigo-600">{whatsapp}</p>
</div>
</div>
</div>
{/* Chat Messages Container */}
<div
ref={chatContainerRef}
id="chat-container"
className="flex-grow overflow-y-auto p-4 bg-gradient-to-b from-indigo-50 to-white"
onScroll={handleScroll} // Detect scroll for loading more messages
>
{loading && (
<div className="flex justify-center mt-2">
<Spinner />
</div>
)}
{renderedMessages.map((message) => (
<div
key={message.id}
className={`flex ${
message.outgoing ? "justify-end" : "justify-start"
} items-end space-x-3 mb-4`}
>
{!message.outgoing && (
<div className="flex items-center justify-center h-10 w-10 rounded-full bg-indigo-200 text-indigo-700 text-lg font-bold">
{name.charAt(0).toUpperCase()}
</div>
)}
<div
className={`
max-w-[70%] px-4 py-2 rounded-2xl
${
message.outgoing
? "bg-indigo-100 text-indigo-900"
: "bg-white text-gray-800 shadow-sm"
}
relative flex flex-col
`}
>
{message.renderedContent}
<div className="text-xs text-gray-500 mt-1 text-right">
<span>{formatTimestamp(message.timestamp).time}</span>
<span className="block text-[0.6rem] text-gray-400">
{formatTimestamp(message.timestamp).date}
</span>
</div>
</div>
{message.outgoing && (
<div className="flex items-center justify-center h-10 w-10 rounded-full bg-indigo-200 text-indigo-700 text-lg font-bold">
U
</div>
)}
</div>
))}
</div>
{/* Message Input - Fixed at Bottom */}
<div className="bg-white border-t border-gray-200 p-4 shadow-md relative">
<div className="flex items-center space-x-3 max-w-full">
{/* Attachment Button with Speed Dial */}
<div className="relative" ref={attachmentRef}>
<button
onClick={() => setShowAttachments((prev) => !prev)}
className="text-gray-500 hover:text-indigo-600 flex-shrink-0"
>
<PaperClipIcon className="w-6 h-6" />
</button>
{/* Speed Dial Options */}
{showAttachments && (
<div className="absolute bottom-12 left-0 flex flex-col items-start space-y-2 bg-white p-3 rounded-lg shadow-lg border border-gray-200 z-50">
<button
onClick={() => handleUploadFile("image")}
className="flex items-center px-4 py-2 text-sm text-gray-700 hover:text-indigo-600 hover:bg-gray-100 rounded-lg w-full"
>
<PhotoIcon className="w-5 h-5 mr-2 text-gray-500" />
Image
</button>
<button
onClick={() => handleUploadFile("video")}
className="flex items-center px-4 py-2 text-sm text-gray-700 hover:text-indigo-600 hover:bg-gray-100 rounded-lg w-full"
>
<VideoCameraIcon className="w-5 h-5 mr-2 text-gray-500" />
Video
</button>
<button
onClick={() => handleUploadFile("document")}
className="flex items-center px-4 py-2 text-sm text-gray-700 hover:text-indigo-600 hover:bg-gray-100 rounded-lg w-full"
>
<DocumentTextIcon className="w-5 h-5 mr-2 text-gray-500" />
Document
</button>
</div>
)}
</div>
{/* Text Area for Chat */}
<div className="flex-grow">
<textarea
ref={inputRef} // Attach ref
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
// onKeyPress={(e) =>
// e.key === "Enter" && !e.shiftKey && handleSendMessage()
// }
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-300 resize-none"
rows="1"
placeholder="Type your message..."
onInput={(e) => {
e.target.style.height = "auto"; // Reset height
e.target.style.height = `${e.target.scrollHeight}px`; // Adjust to content
}}
></textarea>
{/* Attached File Display */}
{fileDetail && (
<div className="mt-2 bg-gray-100 p-2 rounded-lg flex items-center space-x-2">
<span className="truncate text-sm text-gray-700 flex-grow">
{fileDetail.name}
</span>
<button
onClick={() => setFileDetail(null)}
className="text-gray-500 hover:text-red-500"
>
<XCircleIcon className="w-5 h-5" />
</button>
</div>
)}
</div>
{/* Send Button */}
<button
onClick={handleSendMessage}
disabled={loader} // Disable the button when loader is true
className={`bg-indigo-600 text-white p-2 rounded-full transition duration-300 flex-shrink-0 ${
loader ? "cursor-not-allowed opacity-50" : "hover:bg-indigo-700"
}`}
>
{loader ? (
<Spinner className="w-4 h-4 text-white" />
) : (
<PaperAirplaneIcon className="w-6 h-6 transform rotate-[315deg]" />
)}
</button>
</div>
</div>
</div>
);
}
Comments
Post a Comment