import { useState, useEffect, useCallback } from 'react'; import { DATA_KEY_ACCESS_TOKEN } from '../constants/app'; import { tokenService } from '../services/TokenService'; import { contactApi } from '../api/contactApi'; import './ViewContact.css'; const ViewContact = ({ isOpen, onClose, title = 'View Contacts' }) => { const [contacts, setContacts] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [lastUpdated, setLastUpdated] = useState(null); const [searchTerm, setSearchTerm] = useState(''); // Fetch contacts when the popup opens const fetchContacts = useCallback(async () => { try { setLoading(true); setError(null); const accessToken = localStorage.getItem(DATA_KEY_ACCESS_TOKEN); const userId = tokenService.getUserId(); if (!accessToken) { throw new Error('Authentication required. Please log in again.'); } const result = await contactApi.getContactsWithUserId( userId, tokenService.bearerToken() ); if (result.data) { setContacts(result.data); setLastUpdated(new Date()); } else { setLoading(false); throw new Error(result.message || 'Failed to load contacts'); } } catch (err) { console.error('Error fetching contacts:', err); setError(err.message || 'Failed to load contacts. Please try again.'); setContacts([]); } finally { setLoading(false); } }, []); useEffect(() => { if (isOpen) { console.log('This is when I would fetch contacts'); fetchContacts(); } }, [isOpen, fetchContacts]); // Handle refresh button click const handleRefresh = () => { fetchContacts(); }; // Filter contacts based on search term const filteredContacts = contacts.filter((contact) => { const searchLower = searchTerm.toLowerCase(); return ( (contact.phone_number && contact.phone_number.toLowerCase().includes(searchLower)) || (contact.first_name && contact.first_name.toLowerCase().includes(searchLower)) || (contact.last_name && contact.last_name.toLowerCase().includes(searchLower)) || (contact.id && contact.id.toString().includes(searchTerm)) ); }); // Format phone number for display const formatPhoneNumber = (phone) => { if (!phone) return 'N/A'; // Simple formatting - you can customize this const cleaned = phone.replace(/\D/g, ''); if (cleaned.length === 10) { return `(${cleaned.slice(0, 3)}) ${cleaned.slice(3, 6)}-${cleaned.slice(6)}`; } return phone; }; // Format timestamp const formatLastUpdated = () => { if (!lastUpdated) return 'Never'; return lastUpdated.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', }); }; if (!isOpen) return null; return (
Loading contacts...
{searchTerm ? 'No matching contacts found' : 'No contacts available'}
{searchTerm ? 'Try a different search term' : 'Add your first contact to get started'}
{searchTerm && ( )}📱 {formatPhoneNumber(contact.phone_number)}