feat: enable user profile avatar upload and display across header and settings.
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import Image from 'next/image';
|
||||
import { useSession, signIn } from 'next-auth/react';
|
||||
import { uploadService } from '@/services/upload.service';
|
||||
import { agentsService } from '@/services/agents.service';
|
||||
|
||||
interface ProfileSettingsFormProps {
|
||||
initialData?: {
|
||||
@@ -10,6 +13,7 @@ interface ProfileSettingsFormProps {
|
||||
email: string;
|
||||
phone: string;
|
||||
location: string;
|
||||
avatar?: string;
|
||||
};
|
||||
onSave?: (data: {
|
||||
fullName: string;
|
||||
@@ -22,34 +26,234 @@ interface ProfileSettingsFormProps {
|
||||
}
|
||||
|
||||
export function ProfileSettingsForm({
|
||||
initialData = {
|
||||
fullName: 'Brain Neeland',
|
||||
career: 'Real Estate Agent',
|
||||
email: 'Brain.Neeland1234@gmail.com',
|
||||
phone: '+917483849544',
|
||||
location: 'New York',
|
||||
},
|
||||
initialData,
|
||||
onSave,
|
||||
descriptionText = 'This information will be displayed on your public profile page.',
|
||||
}: ProfileSettingsFormProps) {
|
||||
const [formData, setFormData] = useState(initialData);
|
||||
const { data: session, update: updateSession } = useSession();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
fullName: initialData?.fullName || '',
|
||||
career: initialData?.career || '',
|
||||
email: initialData?.email || '',
|
||||
phone: initialData?.phone || '',
|
||||
location: initialData?.location || '',
|
||||
});
|
||||
|
||||
const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [uploadProgress, setUploadProgress] = useState(0);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
|
||||
// Fetch profile data on mount
|
||||
useEffect(() => {
|
||||
const fetchProfile = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const profile = await agentsService.getMyProfile();
|
||||
|
||||
setFormData({
|
||||
fullName: `${profile.firstName || ''} ${profile.lastName || ''}`.trim(),
|
||||
career: profile.agentType?.name || 'Real Estate Agent',
|
||||
email: profile.email || session?.user?.email || '',
|
||||
phone: profile.phone || '',
|
||||
location: profile.serviceAreas?.[0] || '',
|
||||
});
|
||||
|
||||
// Handle avatar URL - if it's an S3 key, get presigned URL
|
||||
if (profile.avatar) {
|
||||
try {
|
||||
const presignedUrl = await uploadService.getPresignedDownloadUrl(profile.avatar);
|
||||
setAvatarUrl(presignedUrl);
|
||||
} catch {
|
||||
// If getting presigned URL fails, the avatar might be a full URL
|
||||
setAvatarUrl(profile.avatar);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch profile:', err);
|
||||
// Use session data as fallback
|
||||
if (session?.user) {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
fullName: session.user?.name || prev.fullName,
|
||||
email: session.user?.email || prev.email,
|
||||
}));
|
||||
if (session.user.image) {
|
||||
setAvatarUrl(session.user.image);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (session) {
|
||||
fetchProfile();
|
||||
}
|
||||
}, [session]);
|
||||
|
||||
const handleChange = (field: string, value: string) => {
|
||||
setFormData((prev) => ({ ...prev, [field]: value }));
|
||||
setError(null);
|
||||
setSuccessMessage(null);
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
if (onSave) {
|
||||
onSave(formData);
|
||||
} else {
|
||||
console.log('Saving profile settings:', formData);
|
||||
const handleUploadClick = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
// Validate file type
|
||||
const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
|
||||
if (!validTypes.includes(file.type)) {
|
||||
setError('Please upload a JPEG, PNG, or GIF image.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate file size (2MB max)
|
||||
const maxSize = 2 * 1024 * 1024;
|
||||
if (file.size > maxSize) {
|
||||
setError('File size must be less than 2MB.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsUploading(true);
|
||||
setError(null);
|
||||
setUploadProgress(0);
|
||||
|
||||
// Upload the avatar
|
||||
const uploadedFile = await uploadService.uploadAvatar(file, (progress) => {
|
||||
setUploadProgress(progress.percentage);
|
||||
});
|
||||
|
||||
// Update the profile with the new avatar key
|
||||
await agentsService.updateProfile({ avatar: uploadedFile.url });
|
||||
|
||||
// Get the presigned URL for display
|
||||
const presignedUrl = await uploadService.getPresignedDownloadUrl(uploadedFile.url);
|
||||
setAvatarUrl(presignedUrl);
|
||||
|
||||
// Update the session to reflect the new avatar
|
||||
await updateSession({
|
||||
...session,
|
||||
user: {
|
||||
...session?.user,
|
||||
image: presignedUrl,
|
||||
},
|
||||
});
|
||||
|
||||
setSuccessMessage('Profile picture updated successfully!');
|
||||
} catch (err) {
|
||||
console.error('Upload failed:', err);
|
||||
setError('Failed to upload profile picture. Please try again.');
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
setUploadProgress(0);
|
||||
// Reset file input
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = '';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteAvatar = async () => {
|
||||
try {
|
||||
setIsUploading(true);
|
||||
setError(null);
|
||||
|
||||
// Update profile to remove avatar
|
||||
await agentsService.updateProfile({ avatar: null });
|
||||
setAvatarUrl(null);
|
||||
|
||||
// Update session
|
||||
await updateSession({
|
||||
...session,
|
||||
user: {
|
||||
...session?.user,
|
||||
image: null,
|
||||
},
|
||||
});
|
||||
|
||||
setSuccessMessage('Profile picture removed successfully!');
|
||||
} catch (err) {
|
||||
console.error('Delete failed:', err);
|
||||
setError('Failed to remove profile picture. Please try again.');
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setError(null);
|
||||
|
||||
// Split full name into first and last name
|
||||
const nameParts = formData.fullName.trim().split(' ');
|
||||
const firstName = nameParts[0] || '';
|
||||
const lastName = nameParts.slice(1).join(' ') || '';
|
||||
|
||||
// Update profile
|
||||
await agentsService.updateProfile({
|
||||
firstName,
|
||||
lastName,
|
||||
email: formData.email,
|
||||
phone: formData.phone,
|
||||
serviceAreas: formData.location ? [formData.location] : [],
|
||||
});
|
||||
|
||||
// Update session with new name
|
||||
await updateSession({
|
||||
...session,
|
||||
user: {
|
||||
...session?.user,
|
||||
name: formData.fullName,
|
||||
},
|
||||
});
|
||||
|
||||
if (onSave) {
|
||||
onSave(formData);
|
||||
}
|
||||
|
||||
setSuccessMessage('Profile settings saved successfully!');
|
||||
} catch (err) {
|
||||
console.error('Save failed:', err);
|
||||
setError('Failed to save profile settings. Please try again.');
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setFormData(initialData);
|
||||
// Reset to initial data or session data
|
||||
if (session?.user) {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
fullName: session.user?.name || prev.fullName,
|
||||
email: session.user?.email || prev.email,
|
||||
}));
|
||||
}
|
||||
setError(null);
|
||||
setSuccessMessage(null);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="border border-[#00293d]/20 rounded-[15px] bg-white p-8 flex items-center justify-center min-h-[400px]">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#e58625]"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border border-[#00293d]/20 rounded-[15px] bg-white p-8">
|
||||
{/* Header */}
|
||||
@@ -62,27 +266,62 @@ export function ProfileSettingsForm({
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Error/Success Messages */}
|
||||
{error && (
|
||||
<div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-[10px] text-red-600 text-sm font-serif">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
{successMessage && (
|
||||
<div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-[10px] text-green-600 text-sm font-serif">
|
||||
{successMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Profile Photo Section */}
|
||||
<div className="mb-8">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-[60px] h-[60px] rounded-full overflow-hidden border border-[#00293D]/20 flex-shrink-0">
|
||||
<Image
|
||||
src="/assets/icons/user-placeholder-icon.svg"
|
||||
alt="Profile"
|
||||
width={60}
|
||||
height={60}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
<div className="w-[60px] h-[60px] rounded-full overflow-hidden border border-[#00293D]/20 flex-shrink-0 bg-gray-100">
|
||||
{avatarUrl ? (
|
||||
<img
|
||||
src={avatarUrl}
|
||||
alt="Profile"
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<Image
|
||||
src="/assets/icons/user-placeholder-icon.svg"
|
||||
alt="Profile"
|
||||
width={60}
|
||||
height={60}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-serif font-medium text-[14px] text-[#00293D] mb-2">
|
||||
Public Picture
|
||||
</p>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<button className="px-4 py-1.5 bg-[#e58625] text-white rounded-[20px] font-serif text-[12px] hover:bg-[#d47920] transition-colors">
|
||||
Upload Now
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/gif"
|
||||
onChange={handleFileChange}
|
||||
className="hidden"
|
||||
/>
|
||||
<button
|
||||
onClick={handleUploadClick}
|
||||
disabled={isUploading}
|
||||
className="px-4 py-1.5 bg-[#e58625] text-white rounded-[20px] font-serif text-[12px] hover:bg-[#d47920] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{isUploading ? `Uploading ${uploadProgress}%` : 'Upload Now'}
|
||||
</button>
|
||||
<button className="px-4 py-1.5 border border-[#00293D]/30 text-[#00293D] rounded-[20px] font-serif text-[12px] hover:bg-[#00293d]/5 transition-colors">
|
||||
<button
|
||||
onClick={handleDeleteAvatar}
|
||||
disabled={isUploading || !avatarUrl}
|
||||
className="px-4 py-1.5 border border-[#00293D]/30 text-[#00293D] rounded-[20px] font-serif text-[12px] hover:bg-[#00293d]/5 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
@@ -175,15 +414,17 @@ export function ProfileSettingsForm({
|
||||
<div className="mt-8 flex justify-end gap-3">
|
||||
<button
|
||||
onClick={handleCancel}
|
||||
className="px-8 py-3 border border-[#00293D]/30 text-[#00293D] rounded-[10px] font-serif font-medium text-[14px] hover:bg-[#00293d]/5 transition-colors"
|
||||
disabled={isSaving}
|
||||
className="px-8 py-3 border border-[#00293D]/30 text-[#00293D] rounded-[10px] font-serif font-medium text-[14px] hover:bg-[#00293d]/5 transition-colors disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
className="px-8 py-3 bg-[#e58625] text-white rounded-[10px] font-serif font-medium text-[14px] hover:bg-[#d47920] transition-colors"
|
||||
disabled={isSaving}
|
||||
className="px-8 py-3 bg-[#e58625] text-white rounded-[10px] font-serif font-medium text-[14px] hover:bg-[#d47920] transition-colors disabled:opacity-50"
|
||||
>
|
||||
Save Changes
|
||||
{isSaving ? 'Saving...' : 'Save Changes'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user