manage group

This commit is contained in:
Abin Toppo
2025-09-18 13:45:39 +05:30
26 changed files with 2044 additions and 501 deletions
+191 -143
View File
@@ -1,4 +1,4 @@
import React, { useState, useEffect, useCallback } from "react";
import React, { useState, useEffect, useCallback} from "react";
import {
StyleSheet,
View,
@@ -9,20 +9,22 @@ 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"; // Assuming you use expo-cli or have this package
import { Ionicons } from "@react-native-vector-icons/ionicons";
import { launchImageLibrary } from "react-native-image-picker";
import { CustomButton, CustomInput } from "../../components/common/Custom";
import colors from "../../components/colors";
import SwitchNavigator from "./SwitchNavigator";
import { CommonActions, useFocusEffect, useNavigation } from "@react-navigation/native";
import { useFocusEffect } from "@react-navigation/native";
import { ApiResponse } from "../home/UserProfileStatus";
import { BASE_URL } from "../../utils/ApiUrls";
import AsyncStorage from "@react-native-async-storage/async-storage";
import AppView from "../../components/AppView";
type UserProfile = {
id: string;
@@ -49,12 +51,10 @@ 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 (isRefreshing = false) => {
const fetchUserProfile = async () => {
try {
const credentials = await Keychain.getGenericPassword();
if (!credentials) {
@@ -63,19 +63,20 @@ const Profile = () => {
}
const token = credentials.password;
if (!isRefreshing) {
setFetching(true);
}
const response = await fetch(`${BASE_URL}user/profile/view`, {
method: "GET",
headers: {
Accept: "*/*",
Authorization: `Bearer ${token}`,
},
});
setFetching(true);
const response = await fetch(
`${BASE_URL}user/profile/view`,
{
method: "GET",
headers: {
Accept: "*/*",
Authorization: `Bearer ${token}`,
},
}
);
const result = await response.json();
console.log("👤 Profile Response:", result);
if (result.status === "success") {
setUser(result.data);
} else {
@@ -85,10 +86,7 @@ const Profile = () => {
console.error("❌ Error fetching profile:", error);
Alert.alert("Error", "Could not connect to server");
} finally {
if (!isRefreshing) {
setFetching(false);
}
setRefreshing(false);
setFetching(false);
}
};
@@ -101,22 +99,25 @@ 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") {
@@ -169,23 +170,31 @@ 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");
@@ -212,15 +221,17 @@ const Profile = () => {
const response = await fetch(`${BASE_URL}user/profile/status`, {
method: "GET",
headers: {
Accept: "*/*",
Accept: "/",
Authorization: `Bearer ${token}`,
},
});
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");
}
@@ -231,41 +242,7 @@ 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(() => {
@@ -274,9 +251,11 @@ const Profile = () => {
);
useEffect(() => {
userStatus();
fetchUserProfile();
}, []);
console.log("user image :", user?.filePath);
const getProfileImage = () => {
if (user?.imageBlob) {
return `data:image/jpeg;base64,${user.imageBlob}`;
@@ -287,31 +266,25 @@ const Profile = () => {
return "https://randomuser.me/api/portraits/men/1.jpg";
};
if (fetching || !user) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color={colors.Profile} />
<ActivityIndicator size="large" color={colors.pastelBlue} />
<Text style={styles.loadingText}>Loading profile...</Text>
</View>
);
}
return (
<View style={styles.container}>
<StatusBar barStyle="light-content" />
<AppView>
{/* Header */}
<View style={styles.header}>
<Text style={styles.headerTitle}>User Profile</Text>
<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>
<TouchableOpacity onPress={fetchUserProfile} style={styles.refreshButton}>
<Ionicons name="refresh" size={24} color={'#000'} />
</TouchableOpacity>
</View>
<KeyboardAvoidingView
style={{ flex: 1 }}
behavior={Platform.OS === "ios" ? "padding" : undefined}
@@ -319,23 +292,16 @@ 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}>
{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 || ''} />
)}
{/* 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 || ''} />} */}
<View style={styles.profileImageSection}>
<View style={styles.avatarContainer}>
<Image
@@ -344,84 +310,101 @@ const Profile = () => {
onError={() => console.log("Error loading image")}
/>
<TouchableOpacity style={styles.cameraIcon} onPress={pickImage}>
<Ionicons name="camera" size={18} color="white" />
<Ionicons name="camera" size={18} color="#000" />
</TouchableOpacity>
</View>
<CustomButton
title={imageUpdating ? "Updating..." : "Update Image"}
onPress={handleUpdateImage}
icon={imageUpdating ? undefined : "cloud-upload"}
style={styles.updateImageButton}
buttonBackground={colors.Profile}
buttonBackground={colors.pastelBlue}
/>
</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} />
<Ionicons name="person" size={20} color={colors.pastelBlue} style={styles.detailIcon} />
<View>
<Text style={styles.detailLabel}>Name</Text>
<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} />
<Ionicons name="mail" size={20} color={colors.pastelBlue} style={styles.detailIcon} />
<View>
<Text style={styles.detailLabel}>Email</Text>
<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} />
<Ionicons name="call" size={20} color={colors.pastelBlue} style={styles.detailIcon} />
<View>
<Text style={styles.detailLabel}>Mobile</Text>
<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} />
<Ionicons name="at-circle" size={20} color={colors.pastelBlue} style={styles.detailIcon} />
<View>
<Text style={styles.detailLabel}>Username</Text>
<Text style={styles.detailText}>{user.username}</Text>
</View>
</View>
<View style={styles.detailRow}>
<Ionicons name="location" size={20} color={colors.Profile} style={styles.detailIcon} />
<Ionicons name="location" size={20} color={colors.pastelBlue} style={styles.detailIcon} />
<View>
<Text style={styles.detailLabel}>Address</Text>
<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} />
<Ionicons name="male-female" size={20} color={colors.pastelBlue} style={styles.detailIcon} />
<View>
<Text style={styles.detailLabel}>Gender</Text>
<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} />
<Ionicons name="key" size={20} color={colors.pastelBlue} style={styles.detailIcon} />
<View>
<Text style={styles.detailLabel}>Role</Text>
<Text style={styles.detailText}>{user.role || "User"}</Text>
</View>
</View>
</View>
<CustomButton
title="Edit Profile"
onPress={() => setEditing(true)}
icon="create"
style={styles.editButton}
buttonBackground={colors.Profile}
buttonBackground={colors.pastelBlue}
/>
</>
) : (
<>
{/* Edit Form */}
<View style={styles.editSection}>
<Text style={styles.sectionTitle}>Edit Profile</Text>
<CustomInput
label="First Name"
placeholder="Enter first name"
@@ -429,6 +412,7 @@ const Profile = () => {
onChangeText={(text) => setUser({ ...user, firstName: text })}
icon="person"
/>
<CustomInput
label="Last Name"
placeholder="Enter last name"
@@ -436,6 +420,7 @@ const Profile = () => {
onChangeText={(text) => setUser({ ...user, lastName: text })}
icon="person"
/>
<CustomInput
label="Email"
placeholder="Enter email"
@@ -444,6 +429,7 @@ const Profile = () => {
icon="mail"
keyboardType="email-address"
/>
<CustomInput
label="Username"
placeholder="Enter username"
@@ -488,59 +474,61 @@ const Profile = () => {
</View>
</ScrollView>
</KeyboardAvoidingView>
</View>
</AppView>
);
};
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",
justifyContent: "space-between",
alignItems: "center",
padding: 16,
paddingTop: 50,
// 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",
},
headerIcons: {
flexDirection: 'row',
alignItems: 'center',
gap: 16,
color: "#000"
},
refreshButton: {
padding: 4,
},
logoutButton: {
padding: 4,
},
profileCard: {
borderRadius: 20,
margin: 16,
backgroundColor: "#fff",
padding: 20,
shadowColor: "#000",
shadowOpacity: 0.1,
shadowRadius: 10,
shadowOffset: { width: 0, height: 4 },
elevation: 5,
// backgroundColor: "#fff",
// padding: 20,
// shadowColor: "#000",
// shadowOpacity: 0.1,
// shadowRadius: 10,
// shadowOffset: { width: 0, height: 4 },
// elevation: 5,
},
profileImageSection: {
alignItems: "center",
@@ -564,7 +552,7 @@ const styles = StyleSheet.create({
position: "absolute",
right: 0,
bottom: 0,
backgroundColor: "#6366f1",
backgroundColor: colors.pastelBlue,
borderRadius: 20,
width: 40,
height: 40,
@@ -615,6 +603,7 @@ const styles = StyleSheet.create({
},
editSection: {
marginBottom: 20,
flex: 1,
},
editButtons: {
gap: 12,
@@ -625,7 +614,66 @@ const styles = StyleSheet.create({
cancelButton: {
marginTop: 4,
},
// Add any other styles you might need
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,
},
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,
},
});
export default Profile;
export default Profile;