import React, { useState, useCallback, useEffect } from 'react'; import { TextInput, FlatList, TouchableOpacity, StyleSheet, ActivityIndicator } from 'react-native'; import { ThemedText, ThemedView } from '@/components/theme/Theme'; import { getUser } from '@/components/services/SecureStore'; import { Colors } from '@/constants/Colors'; import { useColorScheme } from '@/hooks/useColorScheme'; import debounce from 'lodash.debounce'; import { searchUsers, sendRelationshipRequest } from '@/constants/APIs'; import type { User, RelationshipData } from '@/constants/Types'; const RequestRelationship: React.FC<{ onRequestSent: (data: RelationshipData) => void }> = ({ onRequestSent }) => { const scheme = useColorScheme() ?? 'dark'; const [searchTerm, setSearchTerm] = useState(''); const [searchResults, setSearchResults] = useState([]); const [isLoading, setIsLoading] = useState(false); const [currentUserId, setCurrentUserId] = useState(null); useEffect(() => { const fetchCurrentUser = async () => { const user = await getUser(); if (user) { setCurrentUserId(user.id); } }; fetchCurrentUser(); }, []); const handleSearchUsers = useCallback(debounce(async (term: string) => { if (term.length < 3) { setSearchResults([]); return; } setIsLoading(true); const users: User[] = await searchUsers(encodeURIComponent(term)) as User[]; setSearchResults(users); }, 300), []); const handleSearch = async (text: string) => { setSearchTerm(text); handleSearchUsers(text); }; const handleSendRequest = async (targetUserId: number) => { if (!currentUserId) return; try { const relationshipData: RelationshipData = await sendRelationshipRequest(currentUserId, targetUserId) as RelationshipData; onRequestSent(relationshipData); } catch (error) { console.error('Error sending relationship request:', error); } }; const renderUserItem = ({ item }: { item: User }) => ( handleSendRequest(item.id)}> {item.fullName} {item.email} ); return ( {isLoading ? ( ) : ( item.id.toString()} ListEmptyComponent={No users found} /> )} ); }; export default RequestRelationship; const styles = StyleSheet.create({ container: { flex: 1, padding: 20, }, searchInput: { height: 40, borderColor: 'gray', borderWidth: 1, marginBottom: 20, paddingHorizontal: 10, }, userItem: { padding: 10, borderBottomWidth: 1, borderBottomColor: 'gray', }, });