"use client" import React, { useState, useEffect } from "react"; import { useRouter, useSearchParams } from "next/navigation"; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { ArrowLeft, Send, RefreshCw, Search, User } from "lucide-react"; import { toast } from "sonner"; import { clientFetch } from "@/lib/client-utils"; import debounce from "lodash/debounce"; interface User { telegramUserId: string; telegramUsername: string | null; } interface Store { _id: string; name: string; } export default function NewChatForm() { const router = useRouter(); const searchParams = useSearchParams(); // State management const [buyerId, setBuyerId] = useState(""); const [searchQuery, setSearchQuery] = useState(""); const [searchResults, setSearchResults] = useState([]); const [initialMessage, setInitialMessage] = useState(""); const [vendorStores, setVendorStores] = useState([]); const [selectedStore, setSelectedStore] = useState(""); const [selectedUser, setSelectedUser] = useState(null); // Loading states const [searching, setSearching] = useState(false); const [loading, setLoading] = useState(false); const [loadingUser, setLoadingUser] = useState(false); const [loadingStores, setLoadingStores] = useState(false); // UI state const [open, setOpen] = useState(false); // Parse URL parameters for buyerId and fetch user details if present useEffect(() => { const buyerIdParam = searchParams.get('buyerId'); if (buyerIdParam) { setBuyerId(buyerIdParam); } }, [searchParams]); // Fetch vendor stores on component mount useEffect(() => { fetchVendorStores(); }, []); // Fetch user information if buyer ID changes useEffect(() => { if (buyerId && vendorStores.length > 0) { fetchUserById(buyerId); } }, [buyerId, vendorStores]); // Fetch user information by ID const fetchUserById = async (userId: string) => { if (!userId || !vendorStores[0]?._id) return; setLoadingUser(true); try { const userData = await clientFetch(`/chats/user/${userId}`); if (userData) { setSelectedUser(userData); setSearchQuery(userData.telegramUsername || `User ${userId}`); } } catch (error) { console.error("Error fetching user:", error); // Still keep the buyerId } finally { setLoadingUser(false); } }; // Fetch vendor stores const fetchVendorStores = async () => { setLoadingStores(true); try { // Get stores const stores = await clientFetch('/storefront'); // Handle both array and single object responses if (Array.isArray(stores)) { setVendorStores(stores); if (stores.length > 0) { setSelectedStore(stores[0]._id); } } else if (stores && typeof stores === 'object' && stores._id) { const singleStore = [stores]; setVendorStores(singleStore); setSelectedStore(stores._id); } } catch (error) { console.error("Error fetching stores:", error); toast.error("Failed to load your stores"); // Redirect if there's a login issue if (error instanceof Error && error.message.includes('logged in')) { router.push("/auth/login"); } } finally { setLoadingStores(false); } }; // Debounced search function const searchUsers = debounce(async (query: string) => { if (!query.trim() || !selectedStore) return; setSearching(true); try { const results = await clientFetch( `/chats/search/users?query=${encodeURIComponent(query)}&storeId=${selectedStore}` ); setSearchResults(results); } catch (error) { console.error("Error searching users:", error); toast.error("Failed to search users"); } finally { setSearching(false); } }, 300); // Handle search input change const handleSearchChange = (value: string) => { setSearchQuery(value); searchUsers(value); setOpen(true); }; // Handle user selection const handleUserSelect = (user: User) => { setBuyerId(user.telegramUserId); setSelectedUser(user); setSearchQuery(user.telegramUsername || user.telegramUserId); setOpen(false); }; // Navigation handlers const handleBackClick = () => { router.push("/dashboard/chats"); }; // Start new chat const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!buyerId || !initialMessage.trim() || !selectedStore) { toast.error("Please fill in all required fields"); return; } setLoading(true); try { const response = await clientFetch('/chats', { method: 'POST', body: JSON.stringify({ buyerId, storeId: selectedStore, initialMessage: initialMessage.trim() }), headers: { 'Content-Type': 'application/json' } }); // Navigate to the new chat toast.success("Chat created successfully"); router.push(`/dashboard/chats/${response._id}`); } catch (error) { console.error("Error creating chat:", error); toast.error("Failed to create chat. Please try again."); } finally { setLoading(false); } }; return ( Start a New Conversation Start a new conversation with a customer by their Telegram ID
handleSearchChange(e.target.value)} placeholder="Search by username or ID..." className="pr-10" />
{loadingUser ? ( ) : ( )}
{open && searchQuery && (
{searching ? (
Searching...
) : searchResults.length === 0 ? (
No customers found
) : (
{searchResults.map((user) => ( ))}
)}
)}

This is the customer's Telegram ID or username. You can search for them above or ask them to use the /myid command in your Telegram bot.

{buyerId && !searchQuery && (

Using Telegram ID: {buyerId}

)}