import React, { useState, useCallback } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, TextInput, ScrollView, Image, Alert, KeyboardAvoidingView, Platform, } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import { router } from 'expo-router'; import { useFocusEffect } from '@react-navigation/native'; import { Ionicons } from '@expo/vector-icons'; import * as ImagePicker from 'expo-image-picker'; import { AppColors, Spacing, BorderRadius, FontSizes, FontWeights } from '@/constants/theme'; import { Button } from '@/components/ui/Button'; import { api } from '@/services/api'; export default function AddBeneficiaryScreen() { const [name, setName] = useState(''); const [address, setAddress] = useState(''); const [avatarUri, setAvatarUri] = useState(null); const [isLoading, setIsLoading] = useState(false); // Reset form when screen gains focus (fixes stale data when adding another beneficiary) useFocusEffect( useCallback(() => { setName(''); setAddress(''); setAvatarUri(null); setIsLoading(false); }, []) ); const handlePickAvatar = async () => { const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (status !== 'granted') { Alert.alert('Permission needed', 'Please allow access to your photo library.'); return; } const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ['images'], allowsEditing: true, aspect: [1, 1], quality: 0.5, }); if (!result.canceled && result.assets[0]) { setAvatarUri(result.assets[0].uri); } }; const handleTakePhoto = async () => { const { status } = await ImagePicker.requestCameraPermissionsAsync(); if (status !== 'granted') { Alert.alert('Permission needed', 'Please allow access to your camera.'); return; } const result = await ImagePicker.launchCameraAsync({ allowsEditing: true, aspect: [1, 1], quality: 0.5, }); if (!result.canceled && result.assets[0]) { setAvatarUri(result.assets[0].uri); } }; const handleAvatarPress = () => { Alert.alert( 'Add Photo', 'Choose how to add a photo', [ { text: 'Take Photo', onPress: handleTakePhoto }, { text: 'Choose from Library', onPress: handlePickAvatar }, { text: 'Cancel', style: 'cancel' }, ] ); }; const handleSave = async () => { if (!name.trim()) { Alert.alert('Name Required', 'Please enter a name for your loved one.'); return; } setIsLoading(true); try { // Create beneficiary through API (gets owner role automatically) const nameParts = name.trim().split(' '); const firstName = nameParts[0]; const lastName = nameParts.slice(1).join(' ') || undefined; const response = await api.createBeneficiary({ firstName, lastName, address: address.trim() ? { street: address.trim(), } : undefined, }); if (!response.ok) { Alert.alert('Error', response.error?.message || 'Failed to create beneficiary'); return; } // Navigate to the new beneficiary's detail page // response.data contains the created beneficiary with id if (response.data?.id) { router.replace(`/(tabs)/beneficiaries/${response.data.id}`); } else { // Fallback to home if no ID returned router.replace('/'); } } catch (error) { Alert.alert('Error', 'Failed to add beneficiary. Please try again.'); } finally { setIsLoading(false); } }; const nameInitial = name.trim() ? name.trim().charAt(0).toUpperCase() : '+'; return ( {/* Header */} router.back()}> Add Loved One {/* Avatar Section */} {avatarUri ? ( ) : ( {nameInitial} )} Tap to add photo {/* Form */} Name * Address (optional) {/* Info Box */} Next Step After adding, you can activate sensors to start monitoring wellness data. {/* Save Button */}