'use client'; import { useState, useEffect } from 'react'; import { useSession } from 'next-auth/react'; import Image from 'next/image'; // Import shared components import { InfoCard, ExperienceSection, ProfileCard, SpecializationSection, TestimonialsSection, StatusButtons, ContactInfo, PhotoUploadModal, } from '@/components/profile'; import { agentsService, AgentProfile, FieldValueResponse } from '@/services/agents.service'; import { uploadService } from '@/services/upload.service'; import { mapFieldValuesToExperience, mapFieldValuesToProfileCard, mapFieldValuesToAvailability, mapFieldValuesToSpecializationFields, ExperienceData, ProfileCardData, AvailabilityData, SpecializationFieldsData } from '@/utils/profileDataMapper'; // Mock data for sections not yet available from API const mockData = { experience: { years: '10+ years', contracts: '10+ Contracts', licensingAreas: ['Colorado Springs', 'Monument', 'Falcon', 'Castle Rock', 'Fountain', 'Momentum'], expertiseYears: [ { area: 'Colorado', years: '10 yrs' }, { area: 'Falcon', years: '10 yrs' }, { area: 'Colorado', years: '10 yrs' }, { area: 'Colorado', years: '10 yrs' }, ], certifications: [ { name: 'Certified Residential Specialist (CRS)', org: 'RESIDENTIAL REAL ESTATE COUNCIL' }, { name: 'Certified Residential Specialist (CRS)', org: 'RESIDENTIAL REAL ESTATE COUNCIL' }, ], }, availability: { type: 'Full-time', days: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], }, preferredWorkEnvironment: 'Preferred work environment includes on-site property visits, in-depth market research, client consultations, property tours, and active involvement in negotiations to ensure the best outcomes', testimonialHighlight: "The most amazing experience I've had as a real estate professional is helping a family secure their dream home and seeing their happiness when they received the keys.", testimonials: [ { id: 1, text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean commodo ligula eget dolor. Sed dignissim, nisl eget tincidunt vulputate, lacus justo bibendum ipsum, vitae tempus risus lorem at nunc. Integer sed arcu vitae risus feugiat vehicula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.', author: 'Kenedy Kenney', role: 'Chief Operations Officer', rating: 5, }, { id: 2, text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean commodo ligula eget dolor. Sed dignissim, nisl eget tincidunt vulputate, lacus justo bibendum ipsum, vitae tempus risus lorem at nunc. Integer sed arcu vitae risus feugiat vehicula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.', author: 'Kenedy Kenney', role: 'Chief Operations Officer', rating: 5, }, { id: 3, text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean commodo ligula eget dolor. Sed dignissim, nisl eget tincidunt vulputate, lacus justo bibendum ipsum, vitae tempus risus lorem at nunc. Integer sed arcu vitae risus feugiat vehicula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.', author: 'Kenedy Kenney', role: 'Chief Operations Officer', rating: 5, }, ], }; // Default experience data when no field values are available const defaultExperience: ExperienceData = { years: '-', contracts: '-', licensingAreas: [], expertiseYears: [], certifications: [], }; // Default profile card data when no field values are available const defaultProfileCardData: ProfileCardData = { bio: '', expertise: [], serviceAreas: [], }; // Default availability data when no field values are available const defaultAvailabilityData: AvailabilityData = { type: '', schedule: [], }; // Default specialization fields data when no field values are available const defaultSpecializationFieldsData: SpecializationFieldsData = { fields: [], }; export default function AgentDashboard() { const { data: session } = useSession(); const [agentProfile, setAgentProfile] = useState(null); const [fieldValues, setFieldValues] = useState([]); const [experienceData, setExperienceData] = useState(defaultExperience); const [profileCardData, setProfileCardData] = useState(defaultProfileCardData); const [availabilityData, setAvailabilityData] = useState(defaultAvailabilityData); const [specializationFieldsData, setSpecializationFieldsData] = useState(defaultSpecializationFieldsData); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [isPhotoModalOpen, setIsPhotoModalOpen] = useState(false); const [imageError, setImageError] = useState(false); const [avatarUrl, setAvatarUrl] = useState(null); const defaultImage = '/assets/demo_images/8f017153a7b4a239a4f0691234ef97dd55092282.jpg'; // Helper to check if avatar is an S3 key (not a full URL or local path) const isS3Key = (avatar: string | null | undefined): boolean => { if (!avatar) return false; // S3 keys don't start with http or / return !avatar.startsWith('http') && !avatar.startsWith('/'); }; // Fetch agent profile and field values on mount useEffect(() => { const fetchData = async () => { try { setLoading(true); setError(null); // Fetch profile and field values in parallel const [profile, fieldValuesResponse] = await Promise.all([ agentsService.getMyProfile(), agentsService.getFieldValues(), ]); setAgentProfile(profile); setFieldValues(fieldValuesResponse.fieldValues); // Map field values to experience data structure const mappedExperience = mapFieldValuesToExperience(fieldValuesResponse.fieldValues); setExperienceData(mappedExperience); // Map field values to profile card data (bio, expertise) const mappedProfileCard = mapFieldValuesToProfileCard(fieldValuesResponse.fieldValues); setProfileCardData(mappedProfileCard); // Map field values to availability data const mappedAvailability = mapFieldValuesToAvailability(fieldValuesResponse.fieldValues); setAvailabilityData(mappedAvailability); // Map field values to specialization fields data (only fields from "Specialization" section) const mappedSpecializationFields = mapFieldValuesToSpecializationFields(fieldValuesResponse.fieldValues); setSpecializationFieldsData(mappedSpecializationFields); // If avatar is an S3 key, fetch presigned URL if (profile.avatar && isS3Key(profile.avatar)) { try { const presignedUrl = await uploadService.getPresignedDownloadUrl(profile.avatar); setAvatarUrl(presignedUrl); } catch (avatarErr) { console.error('Failed to get avatar URL:', avatarErr); // Don't fail the whole page, just use default image } } else if (profile.avatar) { // It's already a full URL or local path setAvatarUrl(profile.avatar); } } catch (err) { console.error('Failed to fetch profile:', err); setError('Failed to load profile data'); } finally { setLoading(false); } }; fetchData(); }, []); const handlePhotoUpload = async (file: File) => { // Upload avatar to S3 (uses agent ID as filename for auto-replacement) const uploadedFile = await uploadService.uploadAvatar(file); // Update agent profile with the S3 key const updatedProfile = await agentsService.updateProfile({ avatar: uploadedFile.url }); setImageError(false); // Reset error state for new image setAgentProfile(updatedProfile); // Fetch new presigned URL for the uploaded avatar if (uploadedFile.url && isS3Key(uploadedFile.url)) { try { const presignedUrl = await uploadService.getPresignedDownloadUrl(uploadedFile.url); setAvatarUrl(presignedUrl); } catch (err) { console.error('Failed to get presigned URL for new avatar:', err); } } }; const getProfileImageUrl = () => { // If image failed to load, return default if (imageError) { return defaultImage; } // If we have a presigned URL from S3, use it if (avatarUrl) { return avatarUrl; } // Check for null, undefined, or empty string if (!agentProfile?.avatar || agentProfile.avatar.trim() === '') { return defaultImage; } // For relative paths (local assets), return as-is if (agentProfile.avatar.startsWith('/')) { return agentProfile.avatar; } // Default fallback return defaultImage; }; if (loading) { return (

Loading profile...

); } if (error || !agentProfile) { return (

Unable to Load Profile

{error || 'Profile not found'}

); } // Format member since date const formatMemberSince = (dateString?: string) => { if (!dateString) return 'Member'; try { const date = new Date(dateString); return date.toLocaleDateString('en-US', { month: 'long', year: 'numeric' }); } catch { return 'Member'; } }; return (
{/* Main Layout - Responsive: Column on mobile, Row on desktop */}
{/* Left Sidebar - Status & Contact */}
{/* Profile Image */}
{/* eslint-disable-next-line @next/next/no-img-element */} Profile { const target = e.target as HTMLImageElement; target.src = defaultImage; }} /> {/* Gradient Overlay */}
{/* Edit Icon - Top Right Outside */}
{/* Status Buttons */} {/* Contact Info */}
{/* Right Content - Profile Info + Experience + All Sections */}
{/* Profile Card */} {/* Experience Section - Dynamic data from profile fields */} {/* Info Cards Section */}
} content={
{availabilityData.type && (

{availabilityData.type}

)}
{availabilityData.schedule.length > 0 ? ( availabilityData.schedule.map((item, index) => (

{item}

)) ) : (

Not specified

)}
} /> } content={

{mockData.preferredWorkEnvironment}

} /> } content={

“{mockData.testimonialHighlight}”

} />
{/* Specialization Section */} {/* Testimonials Section */}
{/* Photo Upload Modal */} setIsPhotoModalOpen(false)} onUpload={handlePhotoUpload} currentPhoto={agentProfile.avatar} currentPhotoUrl={avatarUrl} />
); }