import React, { useEffect, useState } from 'react'; import { io } from 'socket.io-client'; import { Image, StyleSheet, AppState } from 'react-native'; import { ThemedText, ThemedView } from '@/components/theme/Theme'; import { getUser, getRelationship, getPartner, saveRelationshipData } from '@/components/services/SecureStore'; import RequestRelationship from '@/components/home/RequestRelationship'; import TextButton from '@/components/theme/buttons/TextButton'; import { checkRelationshipStatus, updateRelationshipStatus } from '@/constants/APIs'; import type { User, Relationship, RelationshipData } from '@/constants/Types'; type RelationshipProps = { pfpUrl: string | null; }; const RelationshipView: React.FC = ({ pfpUrl }) => { const [status, setStatus] = useState(null); const [user, setUser] = useState(null); const [relationship, setRelationship] = useState(null); const [showRequestRelationship, setShowRequestRelationship] = useState(false); const [loading, setLoading] = useState(true); useEffect(() => { fetchRelationshipStatus(); }, []); useEffect(() => { if (pfpUrl && user) { setUser(prevUser => prevUser ? {...prevUser, pfpUrl: pfpUrl} : null); } }, [pfpUrl]); useEffect(() => { if (!user || !relationship) { console.log('User or relationship not found'); return; } const socket = io(process.env.EXPO_PUBLIC_WEBSOCKET_URL as string, { transports: ['websocket'], }); socket.on('connect', () => { console.log('Connected to WebSocket server'); socket.emit('join', { relationshipId: relationship.id }); }); socket.on('connect_error', (error) => { console.error('Error connecting to WebSocket server:', error); }); socket.on('relationship_status_change', async (relationshipStatus) => { handleCheckRelationshipStatus(); }); return () => { socket.disconnect(); }; }, [relationship]); const handleRequestSent = (relationshipData: RelationshipData) => { setStatus(relationshipData); setShowRequestRelationship(false); }; const fetchRelationshipStatus = async () => { setLoading(true); try { const userFromStore: User = await getUser() as User; if (!userFromStore) throw new Error('User not found in store.'); setUser(userFromStore); const relationshipFromStore: Relationship = await getRelationship() as Relationship; setRelationship(relationshipFromStore); const partnerFromStore: User = await getPartner() as User; if (!relationshipFromStore || !partnerFromStore) throw new Error('Relationship not found in store.'); setStatus({ relationship: relationshipFromStore, partner: partnerFromStore, }); await handleCheckRelationshipStatus(); } catch (error) { console.log('Error fetching relationship status:', error); } finally { setLoading(false); } }; const handleCheckRelationshipStatus = async () => { try { const userFromStore: User = await getUser() as User; if (!userFromStore) throw new Error('User not found in store.'); const relationshipData: RelationshipData = await checkRelationshipStatus(userFromStore.id); setStatus(relationshipData); await saveRelationshipData(relationshipData); } catch (error) { console.log('No relationship found or error checking relationship status:', error); setStatus(null); } finally { setLoading(false); } }; const handleUpdateRelationshipStatus = async (newStatus: 'accepted' | 'rejected') => { if (!status || !status.relationship || !user || !user.id) { console.error('No relationship found.'); return; } try { if (newStatus === 'accepted') { const updatedRelationshipData: RelationshipData = await updateRelationshipStatus(user.id, newStatus) as RelationshipData; setStatus(updatedRelationshipData); await saveRelationshipData(updatedRelationshipData); } else { await updateRelationshipStatus(user.id, newStatus); console.log('Rejected relationship. Relationship deleted.'); setStatus(null); } } catch (error) { console.log('Error updating relationship status:', error); } }; const handleAcceptRequest = () => handleUpdateRelationshipStatus('accepted'); const handleRejectRequest = () => handleUpdateRelationshipStatus('rejected'); if (loading) { return ( Loading... ); } const renderRelationshipContent = () => { if (!status || !status.relationship) { // Case 1: Not in a relationship return showRequestRelationship ? ( setShowRequestRelationship(false)} /> ) : ( setShowRequestRelationship(true)} /> ); } else if (!status.relationship.isAccepted && user?.id === status.relationship.requestorId) { // Case 2: Pending relationship & our user requested it return ( <> Pending Relationship {status.partner.fullName} ); } else if (!status.relationship.isAccepted && user?.id !== status.relationship.requestorId) { // Case 3: Pending relationship & someone else requested it return ( <> Pending Relationship {status.partner.fullName} ); } else if (status.relationship.isAccepted) { // Case 4: In an accepted relationship return ( <> {status.relationship.title} {user && ( {user.fullName.split(' ')[0]} )} {status.partner && ( {status.partner.fullName.split(' ')[0]} )} handleRejectRequest()} /> ); } }; return ( {renderRelationshipContent()} ); }; export default RelationshipView; const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', }, title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20, }, profileContainer: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, profileWrapper: { alignItems: 'center', marginHorizontal: 10, }, profilePicture: { width: 100, height: 100, borderRadius: 50, marginBottom: 10, }, name: { fontSize: 12, fontWeight: 'bold', }, lastChecked: { fontSize: 12, marginBottom: 10, }, buttonContainer: { alignItems: 'center', justifyContent: 'space-around', width: '100%', marginTop: 20, }, });