import React, { useState, useEffect, useRef } from 'react'; import { useAuth } from '@/contexts/AuthContext'; import { useChat } from '@/hooks/useChat'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Input } from '@/components/ui/input'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { toast } from 'sonner'; import { MessageCircle, Car, UtensilsCrossed, Hotel as HotelIcon, Shield, MapPin, Send, Search, Plus, Phone, Video, Paperclip, Smile, Circle, HeadphonesIcon } from 'lucide-react'; type ServiceType = 'all' | 'taxi' | 'restaurant' | 'hotel' | 'guide' | 'politur' | 'support'; const serviceIcons = { taxi: Car, restaurant: UtensilsCrossed, hotel: HotelIcon, guide: MapPin, politur: Shield, support: HeadphonesIcon }; const serviceColors = { taxi: 'bg-yellow-500/10 text-yellow-700 border-yellow-200', restaurant: 'bg-orange-500/10 text-orange-700 border-orange-200', hotel: 'bg-blue-500/10 text-blue-700 border-blue-200', guide: 'bg-green-500/10 text-green-700 border-green-200', politur: 'bg-red-500/10 text-red-700 border-red-200', support: 'bg-purple-500/10 text-purple-700 border-purple-200' }; const Messages = () => { const { user } = useAuth(); const [selectedChatId, setSelectedChatId] = useState(null); const [messageText, setMessageText] = useState(''); const [searchQuery, setSearchQuery] = useState(''); const [serviceFilter, setServiceFilter] = useState('all'); const messagesEndRef = useRef(null); const { chats, messages, onlineUsers, loading, error, loadMessages, sendMessage, searchUsers, createChat, getChatById, clearError } = useChat(); const selectedChat = selectedChatId ? getChatById(selectedChatId) : null; // Filter chats by service type const filteredChats = chats.filter(chat => { const matchesService = serviceFilter === 'all' || chat.serviceType === serviceFilter; const matchesSearch = !searchQuery || chat.name.toLowerCase().includes(searchQuery.toLowerCase()); return matchesService && matchesSearch; }); // Auto-scroll to bottom of messages const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToBottom(); }, [messages]); // Load messages when chat is selected useEffect(() => { if (selectedChatId) { loadMessages(selectedChatId); } }, [selectedChatId, loadMessages]); // Auto-select first chat useEffect(() => { if (chats.length > 0 && !selectedChatId) { setSelectedChatId(chats[0].id); } }, [chats, selectedChatId]); // Handle send message const handleSendMessage = async () => { if (!messageText.trim() || !selectedChatId) return; try { await sendMessage(selectedChatId, messageText); setMessageText(''); } catch (err) { toast.error('No se pudo enviar el mensaje'); } }; // Format time const formatTime = (timestamp: string) => { const date = new Date(timestamp); const now = new Date(); const diffInHours = (now.getTime() - date.getTime()) / (1000 * 60 * 60); if (diffInHours < 24) { return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); } else if (diffInHours < 168) { return date.toLocaleDateString([], { weekday: 'short' }); } else { return date.toLocaleDateString(); } }; const getServiceIcon = (serviceType?: string) => { if (!serviceType) return MessageCircle; return serviceIcons[serviceType as keyof typeof serviceIcons] || MessageCircle; }; const getServiceBadgeClass = (serviceType?: string) => { if (!serviceType) return 'bg-muted'; return serviceColors[serviceType as keyof typeof serviceColors] || 'bg-muted'; }; return (
{/* Chat List Sidebar */}
{/* Header */}

Mensajes

Comunícate con servicios turísticos

{/* Search */}
setSearchQuery(e.target.value)} />
{/* Service Filter Tabs */}
setServiceFilter(v as ServiceType)}> Todos
{/* Chat List */}
{loading && (
Cargando conversaciones...
)} {!loading && filteredChats.length === 0 && (
No hay conversaciones
)} {filteredChats.map((chat) => { const ServiceIcon = getServiceIcon(chat.serviceType); return (
setSelectedChatId(chat.id)} >
{chat.online && (
)} {chat.unreadCount > 0 && (
{chat.unreadCount}
)}
{chat.name}
{chat.lastMessage ? formatTime(chat.lastMessage.timestamp) : ''}
{chat.serviceType && ( {chat.serviceType.charAt(0).toUpperCase() + chat.serviceType.slice(1)} )}

{chat.lastMessage?.content || 'No hay mensajes'}

); })}
{/* Chat Area */}
{selectedChat ? ( <> {/* Chat Header */}
{React.createElement(getServiceIcon(selectedChat.serviceType), { className: 'h-5 w-5' })}

{selectedChat.name} {selectedChat.serviceType && ( {selectedChat.serviceType} )}

{selectedChat.online ? 'En línea' : 'Desconectado'}
{/* Messages */}
{messages.length === 0 ? (

Inicia la conversación

Envía el primer mensaje a {selectedChat.name}

) : ( messages.map((message) => (
{!message.isOwn && ( {message.senderName?.charAt(0)} )}
{!message.isOwn && ( {message.senderName} )}

{message.content}

{message.timestamp}
)) )}
{/* Message Input */}
setMessageText(e.target.value)} onKeyPress={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSendMessage(); } }} />
) : (

Selecciona una conversación

Elige un servicio para comunicarte: taxis, restaurantes, hoteles, guías turísticos o POLITUR

)}
); }; export default Messages;