managment screen upadte

This commit is contained in:
Abin Toppo
2025-09-17 16:45:20 +05:30
parent 66b509e58e
commit 6bc12ecbbb
14 changed files with 823 additions and 201 deletions
+119 -179
View File
@@ -9,21 +9,20 @@ import {
Alert,
ActivityIndicator,
StatusBar,
TextInput,
KeyboardAvoidingView,
Platform,
RefreshControl,
} from "react-native";
import * as Keychain from "react-native-keychain";
import { Ionicons } from "@react-native-vector-icons/ionicons";
import { Ionicons } from "@react-native-vector-icons/ionicons"; // Assuming you use expo-cli or have this package
import { launchImageLibrary } from "react-native-image-picker";
import { CustomButton, CustomInput } from "../../components/common/Custom";
import colors from "../../components/colors";
import SwitchNavigator from "./SwitchNavigator";
import { useFocusEffect } from "@react-navigation/native";
import { CommonActions, useFocusEffect, useNavigation } from "@react-navigation/native";
import { ApiResponse } from "../home/UserProfileStatus";
import { BASE_URL } from "../../utils/ApiUrls";
import AsyncStorage from "@react-native-async-storage/async-storage";
type UserProfile = {
id: string;
@@ -50,10 +49,12 @@ const Profile = () => {
const [editing, setEditing] = useState(false);
const [imageUpdating, setImageUpdating] = useState(false);
const [loading, setLoading] = useState(false);
const [refreshing, setRefreshing] = useState(false); // State for pull-to-refresh
const [statusData, setStatusData] = useState<null | { profileStatus: boolean; organizerStatus: string; role: string }>(null);
const [error, setError] = useState<string | null>(null);
const navigation = useNavigation<any>();
const fetchUserProfile = async () => {
const fetchUserProfile = async (isRefreshing = false) => {
try {
const credentials = await Keychain.getGenericPassword();
if (!credentials) {
@@ -62,17 +63,17 @@ const Profile = () => {
}
const token = credentials.password;
setFetching(true);
const response = await fetch(
`${BASE_URL}user/profile/view`,
{
method: "GET",
headers: {
Accept: "*/*",
Authorization: `Bearer ${token}`,
},
}
);
if (!isRefreshing) {
setFetching(true);
}
const response = await fetch(`${BASE_URL}user/profile/view`, {
method: "GET",
headers: {
Accept: "*/*",
Authorization: `Bearer ${token}`,
},
});
const result = await response.json();
if (result.status === "success") {
@@ -84,7 +85,10 @@ const Profile = () => {
console.error("❌ Error fetching profile:", error);
Alert.alert("Error", "Could not connect to server");
} finally {
setFetching(false);
if (!isRefreshing) {
setFetching(false);
}
setRefreshing(false);
}
};
@@ -97,25 +101,22 @@ const Profile = () => {
}
const token = credentials.password;
const response = await fetch(
`${BASE_URL}user/profile/update`,
{
method: "PUT",
headers: {
Accept: "*/*",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
address: user?.address || null,
email: user?.email || null,
firstName: user?.firstName || null,
gender: user?.gender || null,
lastName: user?.lastName || null,
username: user?.username || null,
}),
}
);
const response = await fetch(`${BASE_URL}user/profile/update`, {
method: "PUT",
headers: {
Accept: "*/*",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
address: user?.address || null,
email: user?.email || null,
firstName: user?.firstName || null,
gender: user?.gender || null,
lastName: user?.lastName || null,
username: user?.username || null,
}),
});
const result = await response.json();
if (result.status === "success") {
@@ -168,31 +169,23 @@ const Profile = () => {
name: "profile.jpg",
} as any);
const response = await fetch(
`${BASE_URL}user/update/userImg`,
{
method: "PUT",
headers: {
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
body: formData,
}
);
const response = await fetch(`${BASE_URL}user/update/userImg`, {
method: "PUT",
headers: {
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
body: formData,
});
const result = await response.json();
if (result.status === "success") {
Alert.alert("Success", "Profile image updated successfully");
// If API returns updated image, set it
if (result.data?.imageBlob) {
setUser((prev) => prev ? { ...prev, imageBlob: result.data.imageBlob, filePath: null } : prev);
} else {
// Otherwise, keep the local filePath until next fetch
setUser((prev) => prev ? { ...prev, filePath: user.filePath } : prev);
}
// Refresh profile from API as well
fetchUserProfile();
} else {
Alert.alert("Error", result.message || "Failed to update profile image");
@@ -225,11 +218,9 @@ const Profile = () => {
});
const json: ApiResponse = await response.json();
console.log("👤 Profile Status Response:", json);
if (json.status === "success") {
setStatusData(json.data);
} else {
setError(json.message || "Failed to fetch status");
}
@@ -240,19 +231,52 @@ const Profile = () => {
}
};
const handleLogout = async () => {
Alert.alert(
"Confirm Logout",
"Are you sure you want to log out?",
[
{ text: "Cancel", style: "cancel" },
{
text: "Logout",
style: "destructive",
onPress: async () => {
try {
await AsyncStorage.clear();
await Keychain.resetGenericPassword();
navigation.dispatch(
CommonActions.reset({
index: 0,
routes: [{ name: "Splash" }],
})
);
} catch (error) {
console.log("Logout error:", error);
Alert.alert("Error", "Could not log out. Please try again.");
}
},
},
]
);
};
const onRefresh = useCallback(() => {
setRefreshing(true);
fetchUserProfile(true).then(() => {
userStatus();
});
}, []);
useFocusEffect(
useCallback(() => {
userStatus();
}, [])
);
console.log("login user data :", user);
useEffect(() => {
fetchUserProfile();
}, []);
console.log("user image :", user?.filePath);
const getProfileImage = () => {
if (user?.imageBlob) {
return `data:image/jpeg;base64,${user.imageBlob}`;
@@ -263,7 +287,6 @@ const Profile = () => {
return "https://randomuser.me/api/portraits/men/1.jpg";
};
if (fetching || !user) {
return (
<View style={styles.loadingContainer}>
@@ -277,13 +300,18 @@ const Profile = () => {
<View style={styles.container}>
<StatusBar barStyle="light-content" />
{/* Header */}
<View style={styles.header}>
<Text style={styles.headerTitle}>User Profile</Text>
<TouchableOpacity onPress={fetchUserProfile} style={styles.refreshButton}>
<Ionicons name="refresh" size={24} color={colors.Profile} />
</TouchableOpacity>
<View style={styles.headerIcons}>
<TouchableOpacity onPress={() => fetchUserProfile(true)} style={styles.refreshButton}>
<Ionicons name="refresh" size={24} color={colors.Profile} />
</TouchableOpacity>
<TouchableOpacity onPress={handleLogout} style={styles.logoutButton}>
<Ionicons name="log-out-outline" size={26} color={"#ef4444"} />
</TouchableOpacity>
</View>
</View>
<KeyboardAvoidingView
style={{ flex: 1 }}
behavior={Platform.OS === "ios" ? "padding" : undefined}
@@ -291,16 +319,23 @@ const Profile = () => {
<ScrollView
contentContainerStyle={{ flexGrow: 1 }}
keyboardShouldPersistTaps="handled"
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={[colors.Profile]}
tintColor={colors.Profile}
/>
}
>
{/* Profile Card */}
<View style={styles.profileCard}>
{/* Profile Image Section */}
{
statusData?.role && statusData?.organizerStatus ?
<Text style={{ color: "#64748b", marginBottom: 16, textAlign: 'center', fontSize: 18 }}>Your Role: {statusData.role} | Organizer Status: {statusData.organizerStatus}</Text>
:
<SwitchNavigator role={statusData?.role || ''} status={statusData?.organizerStatus || ''} />}
{statusData?.role && statusData?.organizerStatus ? (
<Text style={{ color: "#64748b", marginBottom: 16, textAlign: 'center', fontSize: 18 }}>
Your Role: {statusData.role} | Organizer Status: {statusData.organizerStatus}
</Text>
) : (
<SwitchNavigator role={statusData?.role || ''} status={statusData?.organizerStatus || ''} />
)}
<View style={styles.profileImageSection}>
<View style={styles.avatarContainer}>
<Image
@@ -312,27 +347,19 @@ const Profile = () => {
<Ionicons name="camera" size={18} color="white" />
</TouchableOpacity>
</View>
<CustomButton
title={imageUpdating ? "Updating..." : "Update Image"}
onPress={handleUpdateImage}
icon={imageUpdating ? undefined : "cloud-upload"}
style={styles.updateImageButton}
buttonBackground={colors.Profile}
/>
</View>
{!editing ? (
<>
{/* Profile Details */}
<View style={styles.detailsSection}>
<Text style={styles.sectionTitle}>Personal Information</Text>
<View style={{ marginBottom: 16 }}>
<Text style={{ color: "#64748b", marginBottom: 16 }}>Become Organizer</Text>
</View>
<View style={styles.detailRow}>
<Ionicons name="person" size={20} color={colors.Profile} style={styles.detailIcon} />
<View>
@@ -340,7 +367,6 @@ const Profile = () => {
<Text style={styles.detailText}>{user.firstName} {user.lastName}</Text>
</View>
</View>
<View style={styles.detailRow}>
<Ionicons name="mail" size={20} color={colors.Profile} style={styles.detailIcon} />
<View>
@@ -348,7 +374,6 @@ const Profile = () => {
<Text style={styles.detailText}>{user.email || "Not provided"}</Text>
</View>
</View>
<View style={styles.detailRow}>
<Ionicons name="call" size={20} color={colors.Profile} style={styles.detailIcon} />
<View>
@@ -356,7 +381,6 @@ const Profile = () => {
<Text style={styles.detailText}>{user.mobile || "Not provided"}</Text>
</View>
</View>
<View style={styles.detailRow}>
<Ionicons name="at-circle" size={20} color={colors.Profile} style={styles.detailIcon} />
<View>
@@ -364,7 +388,6 @@ const Profile = () => {
<Text style={styles.detailText}>{user.username}</Text>
</View>
</View>
<View style={styles.detailRow}>
<Ionicons name="location" size={20} color={colors.Profile} style={styles.detailIcon} />
<View>
@@ -372,7 +395,6 @@ const Profile = () => {
<Text style={styles.detailText}>{user.address || "Not provided"}</Text>
</View>
</View>
<View style={styles.detailRow}>
<Ionicons name="male-female" size={20} color={colors.Profile} style={styles.detailIcon} />
<View>
@@ -380,7 +402,6 @@ const Profile = () => {
<Text style={styles.detailText}>{user.gender || "Not specified"}</Text>
</View>
</View>
<View style={styles.detailRow}>
<Ionicons name="key" size={20} color={colors.Profile} style={styles.detailIcon} />
<View>
@@ -389,7 +410,6 @@ const Profile = () => {
</View>
</View>
</View>
<CustomButton
title="Edit Profile"
onPress={() => setEditing(true)}
@@ -400,10 +420,8 @@ const Profile = () => {
</>
) : (
<>
{/* Edit Form */}
<View style={styles.editSection}>
<Text style={styles.sectionTitle}>Edit Profile</Text>
<CustomInput
label="First Name"
placeholder="Enter first name"
@@ -411,7 +429,6 @@ const Profile = () => {
onChangeText={(text) => setUser({ ...user, firstName: text })}
icon="person"
/>
<CustomInput
label="Last Name"
placeholder="Enter last name"
@@ -419,7 +436,6 @@ const Profile = () => {
onChangeText={(text) => setUser({ ...user, lastName: text })}
icon="person"
/>
<CustomInput
label="Email"
placeholder="Enter email"
@@ -428,7 +444,6 @@ const Profile = () => {
icon="mail"
keyboardType="email-address"
/>
<CustomInput
label="Username"
placeholder="Enter username"
@@ -480,19 +495,18 @@ const Profile = () => {
const styles = StyleSheet.create({
container: {
flex: 1,
// backgroundColor: colors.pastelBlue,
paddingBottom: '30%',
},
loadingContainer: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#f8fafc"
backgroundColor: "#f8fafc",
},
loadingText: {
marginTop: 10,
fontSize: 16,
color: "#64748b"
color: "#64748b",
},
header: {
flexDirection: "row",
@@ -500,24 +514,23 @@ const styles = StyleSheet.create({
alignItems: "center",
padding: 16,
paddingTop: 50,
// backgroundColor: "#6366f1",
borderBottomLeftRadius: 20,
borderBottomRightRadius: 20,
// elevation: 4,
// shadowColor: "#000",
// shadowOffset: { width: 0, height: 2 },
// shadowOpacity: 0.2,
// shadowRadius: 4,
},
headerTitle: {
fontSize: 22,
fontWeight: "700",
color: "#000"
color: "#000",
},
headerIcons: {
flexDirection: 'row',
alignItems: 'center',
gap: 16,
},
refreshButton: {
padding: 4,
},
logoutButton: {
padding: 4,
},
profileCard: {
borderRadius: 20,
margin: 16,
@@ -602,7 +615,6 @@ const styles = StyleSheet.create({
},
editSection: {
marginBottom: 20,
flex: 1,
},
editButtons: {
gap: 12,
@@ -613,79 +625,7 @@ const styles = StyleSheet.create({
cancelButton: {
marginTop: 4,
},
inputContainer: {
marginBottom: 16,
},
inputLabel: {
fontSize: 14,
fontWeight: "600",
color: "#374151",
marginBottom: 6,
},
inputWrapper: {
flexDirection: "row",
alignItems: "center",
position: "relative",
},
inputIcon: {
position: "absolute",
left: 12,
zIndex: 1,
},
input: {
borderWidth: 1,
borderColor: "#d1d5db",
borderRadius: 12,
padding: 12,
backgroundColor: "#fff",
color: "#1f2937",
fontSize: 16,
flex: 1,
},
inputWithIcon: {
paddingLeft: 40,
},
button: {
backgroundColor: "#6366f1",
paddingVertical: 14,
borderRadius: 12,
alignItems: "center",
justifyContent: "center",
flexDirection: "row",
shadowColor: "#6366f1",
shadowOpacity: 0.3,
shadowRadius: 6,
shadowOffset: { width: 0, height: 3 },
elevation: 4,
},
buttonSecondary: {
backgroundColor: "#f1f5f9",
},
buttonDanger: {
backgroundColor: "#ef4444",
},
buttonOutline: {
backgroundColor: "transparent",
borderWidth: 1,
borderColor: "#6366f1",
},
buttonText: {
color: "#fff",
fontSize: 16,
fontWeight: "600",
},
buttonTextSecondary: {
color: "#334155",
},
buttonTextDanger: {
color: "#fff",
},
buttonTextOutline: {
color: "#6366f1",
},
buttonIcon: {
marginRight: 8,
},
// Add any other styles you might need
});
export default Profile;
export default Profile;