import { React, useState, useEffect } from 'react'; import { tokenService } from '../../services/TokenService'; import { contactApi } from '../../api/contactApi'; import styles from './ViewContact.module.css'; function ViewContact({ selectedContact, onSelectedContact }) { const [contacts, setContacts] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const [searchTerm, setSearchTerm] = useState(''); useEffect(() => { try { console.log('Going'); fetchContacts(); } catch (err) { setError(err.message); } finally { setIsLoading(false); } }, []); const fetchContacts = async () => { try { setIsLoading(true); console.log('Loading contacts'); const userId = tokenService.getUserId(); const response = await contactApi.getContactsWithUserId( userId, tokenService.bearerToken() ); if (!response) { throw new Error('Failed to fetch contacts'); } else { const data = response.data; setContacts(data); setError(null); } } catch (err) { setError(err.message); console.error('Error fetching contacts:', err); } finally { setIsLoading(false); } }; const filteredContacts = contacts.filter( (contact) => contact.phone_number.toLowerCase().includes(searchTerm.toLowerCase()) || contact.first_name?.toLowerCase().includes(searchTerm.toLowerCase()) || contact.last_name?.toLowerCase().includes(searchTerm.toLowerCase()) || contact.nickname?.toLowerCase().includes(searchTerm.toLowerCase()) ); const formatContactDisplay = (contact) => { const phone = contact.phone_number || 'No phone'; const name = [contact.first_name, contact.last_name].filter(Boolean).join(' ') || 'Unnamed'; const nickname = contact.nickname ? `"${contact.nickname}"` : ''; return `${phone} - ${name} ${nickname}`.trim(); }; if (isLoading) { return (

Loading contacts...

); } if (error) { return (

Error loading contacts: {error}

); } return (
setSearchTerm(e.target.value)} className={styles.searchInput} />
{filteredContacts.length === 0 ? (
👤

No contacts found

{searchTerm ? 'Try a different search term' : 'No contacts available'}

) : ( filteredContacts.map((contact) => (
onSelectedContact(contact)} >
{contact.first_name?.[0]?.toUpperCase() || '?'}
{contact.phone_number} {contact.nickname && ( "{contact.nickname}" )}
{[contact.first_name, contact.last_name] .filter(Boolean) .join(' ') || 'Unnamed Contact'}
{selectedContact?.id === contact.id && (
✓ Selected
)}
)) )}
); } export default ViewContact;