import { View, Text, Image, TouchableOpacity, Pressable, ActivityIndicator } from 'react-native'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import TabBar from '../themes/TabBar'
import { ArrowRightStartOnRectangleIcon, ChevronLeftIcon, ChevronRightIcon, ClipboardDocumentListIcon, Cog6ToothIcon, CreditCardIcon, ExclamationCircleIcon, LockClosedIcon, PencilSquareIcon, UserIcon, UserPlusIcon } from 'react-native-heroicons/outline'
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import pic from "../../assets/images/pic.jpg"
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import {
BottomSheetModal,
BottomSheetView,
BottomSheetModalProvider,
} from '@gorhom/bottom-sheet';
import { BackHandler, Alert } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { getUserData, logout, updateProfilePicture } from '../api';
import * as ImagePicker from 'expo-image-picker';
export default function ProfileScreen() {
const navigation = useNavigation();
const [userData, setUserData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// Fetch user data when the screen loads
useEffect(() => {
const fetchUser = async () => {
try {
setLoading(true);
const user = await getUserData();
setUserData(user);
setError(null);
} catch (error) {
console.error('Error fetching user data:', error);
setError('Failed to load user profile');
} finally {
setLoading(false);
}
};
fetchUser();
}, []);
const handleLogout = async () => {
try {
setLoading(true);
await logout();
navigation.navigate("SignIn");
} catch (error) {
Alert.alert('Logout Failed', 'Could not log out. Please try again.');
console.error('Logout error:', error);
} finally {
setLoading(false);
}
};
// ref
const bottomSheetModalRef = useRef(null);
// callbacks
const handlePresentModalPress = useCallback(() => {
bottomSheetModalRef.current?.present();
}, []);
useEffect(() => {
const onBackPress = () => {
if (bottomSheetModalRef.current) {
bottomSheetModalRef.current.close(); // Dismiss the BottomSheetModal
return true; // Prevent default back button behavior
}
return false; // Allow default back button behavior if modal is not open
};
const backHandler = BackHandler.addEventListener('hardwareBackPress', onBackPress);
return () => backHandler.remove(); // Cleanup
}, []);
const handleProfilePictureUpdate = async () => {
try {
// Request permission to access the camera roll
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
Alert.alert(
'Permission Required',
'Please grant permission to access your photos to update your profile picture.',
[{ text: 'OK' }]
);
return;
}
// Launch image picker
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [1, 1],
quality: 0.8,
base64: false,
});
if (!result.canceled && result.assets && result.assets[0]) {
setLoading(true);
try {
// Update profile picture
const updatedUser = await updateProfilePicture(result.assets[0].uri);
setUserData(updatedUser);
Alert.alert(
'Success',
'Profile picture updated successfully',
[{ text: 'OK' }]
);
} catch (error) {
console.error('Error updating profile picture:', error);
Alert.alert(
'Error',
'Failed to update profile picture. Please try again.',
[{ text: 'OK' }]
);
} finally {
setLoading(false);
}
}
} catch (error) {
console.error('Error in image picker:', error);
Alert.alert(
'Error',
'Failed to access image picker. Please try again.',
[{ text: 'OK' }]
);
}
};
if (loading) {
return (
);
}
if (error) {
return (
{error}
{
setLoading(true);
getUserData()
.then(user => {
setUserData(user);
setError(null);
})
.catch(err => setError('Failed to load user profile'))
.finally(() => setLoading(false));
}}
style={{ backgroundColor: '#704f38', padding: 10, borderRadius: 20 }}
>
Retry
);
}
// Format user's name
const fullName = userData ?
`${userData.first_name || ''} ${userData.last_name || ''}`.trim() || userData.username :
'User';
return (
}
titleStyle={{
color: "black",
fontWeight: "bold",
fontSize: 20
}}
prefixStyle={{
backgroundColor: "transparent"
}}
suffixStyle={{
backgroundColor: "white",
borderWidth: 1,
borderColor: "black"
}}
containerStyle=""
suffixAction={() => navigation.goBack()}
/>
{fullName}
{userData?.email && (
{userData.email}
)}
{userData?.phone && (
{userData.phone}
)}
{userData?.address && (
{userData.address}
)}
{ navigation.navigate('Complete your Profile') }}
className={`mx-4 flex-row items-center justify-between py-4 border-b border-gray-300`}
>
Your Profile
{ navigation.navigate('Payment Method') }} className={`mx-4 flex-row items-center justify-between py-4 border-b border-gray-300`}>
Payment Methods
{ navigation.navigate('Order') }} className={`mx-4 flex-row items-center justify-between py-4 border-b border-gray-300`}>
My Order
{ navigation.navigate('Setting') }} className={`mx-4 flex-row items-center justify-between py-4 border-b border-gray-300`}>
Settings
{ navigation.navigate('Help Center') }} className={`mx-4 flex-row items-center justify-between py-4 border-b border-gray-300`}>
Help Center
{ navigation.navigate('Privacy Policy') }} className={`mx-4 flex-row items-center justify-between py-4 border-b border-gray-300`}>
Privacy Policy
{ navigation.navigate('Invite Friends') }} className={`mx-4 flex-row items-center justify-between py-4 border-b border-gray-300`}>
Invites Friends
Log Out
LOG OUT
Are you sure you want to Log Out?
bottomSheetModalRef.current?.close()}
className={`flex-1 bg-white border border-primary flex-row items-center justify-center py-3 rounded-full`}
>
Cancel
{loading ? (
) : (
Yes, Logout
)}
);
}