import React, { useEffect, useState } from 'react'; import { Alert, KeyboardAvoidingView, Platform, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'; import { Image } from 'react-native'; import { useRouter } from 'expo-router'; import { useMutation } from '@tanstack/react-query'; import { Ionicons } from '@expo/vector-icons'; import { api, LocalFile } from '@/api'; import { useAuth } from '@/auth/AuthContext'; import { useT } from '@/i18n'; import { AppBar } from '@/components/AppBar'; import { Avatar, Button, Field, TextField } from '@/components/ui'; import { pickImageFromLibrary, takePhotoWithCamera } from '@/lib/pickImage'; import { colors, fontSize, spacing } from '@/theme'; export default function EditProfileScreen() { const { user, applyUser } = useAuth(); const router = useRouter(); const t = useT(); const [firstName, setFirstName] = useState(''); const [lastName, setLastName] = useState(''); const [phone, setPhone] = useState(''); const [address, setAddress] = useState(''); const [avatar, setAvatar] = useState(null); useEffect(() => { if (!user) return; setFirstName(user.firstName ?? ''); setLastName(user.lastName ?? ''); setPhone(user.phone ?? ''); setAddress(user.address ?? ''); }, [user]); const save = useMutation({ mutationFn: async () => { const updated = await api.auth.updateProfile({ firstName: firstName.trim() || null, lastName: lastName.trim() || null, phone: phone.trim() || null, address: address.trim() || null, }); // The avatar endpoint answers last, so its user object is the newer one. if (avatar) { try { return await api.auth.uploadAvatar(avatar); } catch { Alert.alert(t('addProperty.photoFailed')); } } return updated; }, onSuccess: (updated) => { applyUser(updated); router.back(); }, onError: (e: any) => Alert.alert(t('editProfile.failed'), e?.message ?? t('common.tryAgain')), }); function pickAvatar() { Alert.alert(t('editProfile.photo'), undefined, [ { text: t('addProperty.takePhoto'), onPress: async () => { const picked = await takePhotoWithCamera({ allowsEditing: true, aspect: [1, 1], fallbackName: 'avatar' }); if (picked) setAvatar(picked); }, }, { text: t('addProperty.fromGallery'), onPress: async () => { const picked = await pickImageFromLibrary({ allowsEditing: true, aspect: [1, 1], fallbackName: 'avatar' }); if (picked) setAvatar(picked); }, }, { text: t('common.cancel'), style: 'cancel' }, ]); } const initials = ((firstName[0] ?? '') + (lastName[0] ?? '')).toUpperCase() || 'U'; const avatarUri = avatar?.uri ?? user?.avatar ?? null; return ( {avatarUri ? ( ) : ( )} {t('editProfile.photo')} {t('editProfile.emailReadOnly')}