"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 axios from "axios"; import { toast } from "sonner"; import { getCookie } from "@/lib/client-utils"; import debounce from "lodash/debounce"; import { clientFetch } from "@/lib/client-utils"; interface User { telegramUserId: string; telegramUsername: string | null; } export default function NewChatForm() { const router = useRouter(); const searchParams = useSearchParams(); const [buyerId, setBuyerId] = useState(""); const [searchQuery, setSearchQuery] = useState(""); const [searchResults, setSearchResults] = useState([]); const [searching, setSearching] = useState(false); const [open, setOpen] = useState(false); const [initialMessage, setInitialMessage] = useState(""); const [loading, setLoading] = useState(false); const [loadingUser, setLoadingUser] = useState(false); const [vendorStores, setVendorStores] = useState<{ _id: string, name: string }[]>([]); const [selectedStore, setSelectedStore] = useState(""); const [selectedUser, setSelectedUser] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); // Create an axios instance with auth const getAuthAxios = () => { const authToken = getCookie("Authorization"); if (!authToken) return null; return axios.create({ baseURL: process.env.NEXT_PUBLIC_API_URL, headers: { Authorization: `Bearer ${authToken}` } }); }; // Parse URL parameters for buyerId and fetch user details if present useEffect(() => { const buyerIdParam = searchParams.get('buyerId'); if (buyerIdParam) { setBuyerId(buyerIdParam); // We'll fetch user details after stores are loaded } }, [searchParams]); // Fetch user information by ID const fetchUserById = async (userId: string) => { if (!userId || !vendorStores[0]?._id) return; const authAxios = getAuthAxios(); if (!authAxios) { toast.error("You need to be logged in"); router.push("/auth/login"); return; } setLoadingUser(true); try { const response = await authAxios.get(`/chats/user/${userId}`); if (response.data) { setSelectedUser(response.data); setSearchQuery(response.data.telegramUsername || `User ${userId}`); } else { // Just leave the buyerId as is without username display } } catch (error) { console.error("Error fetching user:", error); // Still keep the buyerId } finally { setLoadingUser(false); } }; // Check if a chat already exists with this user const checkExistingChat = async (userId: string) => { try { // Use clientFetch instead of direct axios calls const response = await clientFetch(`/chats/user/${userId}`); // If a chat is found, redirect to it if (response && Array.isArray(response) && response.length > 0) { toast.info("Chat already exists, redirecting..."); router.push(`/dashboard/chats/${response[0]._id}`); return true; } return false; } catch (error) { console.error("Error checking existing chat:", error); return false; } }; // Search for users by Telegram username or ID const searchUsers = async (query: string) => { setSearching(true); try { if (!query || query.length < 2) { setSearchResults([]); return; } // Use clientFetch instead of direct axios calls const response = await clientFetch(`/chats/search/users?query=${encodeURIComponent(query)}&storeId=${vendorStores[0]._id}`); setSearchResults(response || []); } catch (error) { console.error("Error searching users:", error); toast.error("Failed to search for users"); setSearchResults([]); } finally { setSearching(false); } }; // 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); }; // Fetch vendor stores useEffect(() => { const fetchVendorStores = async () => { const authAxios = getAuthAxios(); if (!authAxios) { toast.error("You must be logged in to start a chat"); router.push("/auth/login"); return; } try { // Get vendor profile first const vendorResponse = await authAxios.get('/auth/me'); // Extract vendor ID properly const vendorId = vendorResponse.data.vendor?._id; if (!vendorId) { console.error("Vendor ID not found in profile response:", vendorResponse.data); toast.error("Could not retrieve vendor information"); return; } // Fetch store const storeResponse = await authAxios.get(`/storefront`); // Handle both array and single object responses if (Array.isArray(storeResponse.data)) { setVendorStores(storeResponse.data); if (storeResponse.data.length > 0) { setSelectedStore(storeResponse.data[0]._id); } } else if (storeResponse.data && typeof storeResponse.data === 'object' && storeResponse.data._id) { const singleStore = [storeResponse.data]; setVendorStores(singleStore); setSelectedStore(storeResponse.data._id); } else { console.error("Expected store data but received:", storeResponse.data); setVendorStores([]); toast.error("Failed to load store data in expected format"); } // Now that we have the store, fetch user details if buyerId was set const buyerIdParam = searchParams.get('buyerId'); if (buyerIdParam) { fetchUserById(buyerIdParam); } } catch (error) { console.error("Error fetching store:", error); toast.error("Failed to load store"); setVendorStores([]); } }; fetchVendorStores(); }, []); const handleBackClick = () => { router.push("/dashboard/chats"); }; // Create a new chat with the selected user const createChat = async (e?: React.FormEvent) => { if (e) e.preventDefault(); if (!selectedUser) { toast.error("Please select a user first"); return; } setIsSubmitting(true); try { // Check for existing chat first const chatExists = await checkExistingChat(selectedUser.telegramUserId); if (chatExists) { setIsSubmitting(false); return; } // Get current vendor info // Use clientFetch instead of direct axios calls const vendorResponse = await clientFetch('/auth/me'); const vendorId = vendorResponse.vendor?._id; if (!vendorId) { toast.error("Vendor ID not found"); return; } // Get store ID from the current vendor // Use clientFetch instead of direct axios calls const storeResponse = await clientFetch(`/storefront`); const storeId = storeResponse?.store?._id; if (!storeId) { toast.error("Store ID not found"); return; } // Create chat data object const chatData = { buyerId: selectedUser.telegramUserId, vendorId, storeId, initialMessage: initialMessage.trim() || "Hello! How can I help you today?", }; // Create the chat // Use clientFetch instead of direct axios calls const response = await clientFetch('/chats', { method: 'POST', body: JSON.stringify(chatData), }); if (response && response._id) { toast.success("Chat created successfully"); router.push(`/dashboard/chats/${response._id}`); } else { toast.error("Failed to create chat"); } } catch (error) { console.error("Error creating chat:", error); toast.error("Failed to create chat"); } finally { setIsSubmitting(false); } }; return ( Start a New Conversation Start a new conversation with a customer by their Telegram ID
createChat(e)} className="space-y-6">
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}

)}