import { useState, useCallback } from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
interface MessageSearchPanelProps {
user?: CometChat.User;
group?: CometChat.Group;
onMessageSelect: (message: CometChat.BaseMessage) => void;
onClose: () => void;
}
function MessageSearchPanel({ user, group, onMessageSelect, onClose }: MessageSearchPanelProps) {
const [keyword, setKeyword] = useState("");
const [results, setResults] = useState<CometChat.BaseMessage[]>([]);
const [loading, setLoading] = useState(false);
const handleSearch = useCallback(async () => {
if (!keyword.trim()) return;
setLoading(true);
try {
const builder = new CometChat.MessagesRequestBuilder()
.setSearchKeyword(keyword)
.setLimit(50);
if (user) {
builder.setUID(user.getUid());
} else if (group) {
builder.setGUID(group.getGuid());
}
const request = builder.build();
const messages = await request.fetchPrevious();
setResults(messages);
} catch (error) {
console.error("Search failed:", error);
} finally {
setLoading(false);
}
}, [keyword, user, group]);
return (
<div style={{ width: "350px", borderLeft: "1px solid #e0e0e0", display: "flex", flexDirection: "column" }}>
{/* Header */}
<div style={{ padding: "12px 16px", borderBottom: "1px solid #e0e0e0", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
<h3 style={{ margin: 0, fontSize: "16px" }}>Search Messages</h3>
<button onClick={onClose} aria-label="Close search panel">✕</button>
</div>
{/* Search input */}
<div style={{ padding: "12px 16px" }}>
<input
type="text"
placeholder="Search messages..."
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
style={{ width: "100%", padding: "8px 12px", borderRadius: "8px", border: "1px solid #e0e0e0" }}
aria-label="Search keyword"
/>
</div>
{/* Results */}
<div style={{ flex: 1, overflowY: "auto", padding: "0 16px" }}>
{loading && <p>Searching...</p>}
{!loading && results.length === 0 && keyword && <p>No messages found.</p>}
{results.map((message) => (
<button
key={message.getId()}
onClick={() => onMessageSelect(message)}
style={{ display: "block", width: "100%", textAlign: "left", padding: "10px", marginBottom: "8px", border: "1px solid #e0e0e0", borderRadius: "8px", background: "none", cursor: "pointer" }}
>
<span style={{ fontSize: "12px", color: "#666" }}>
{message.getSender()?.getName()} •{" "}
{new Date(message.getSentAt() * 1000).toLocaleDateString()}
</span>
<p style={{ margin: "4px 0 0", fontSize: "14px" }}>
{(message as CometChat.TextMessage).getText?.() || "Media message"}
</p>
</button>
))}
</div>
</div>
);
}
export default MessageSearchPanel;