'use client'; import { useState, useRef, useEffect } from 'react'; import { useRouter } from 'next/navigation'; import { QuickLinks } from './components'; import DynamicSection from './components/DynamicSection'; import { profileSectionsService, ProfileSection, AgentTypeSectionsResponse } from '@/services/profile-sections.service'; import { agentsService, AgentProfile } from '@/services/agents.service'; export default function EditProfilePage() { const router = useRouter(); const scrollContainerRef = useRef(null); // State for agent profile and dynamic sections const [agentProfile, setAgentProfile] = useState(null); const [sections, setSections] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); // Form data keyed by field slug const [formData, setFormData] = useState>({}); const [formErrors, setFormErrors] = useState>({}); const [isSaving, setIsSaving] = useState(false); // Fetch agent profile and sections on mount useEffect(() => { const fetchData = async () => { try { setLoading(true); setError(null); // First, fetch the agent's profile to get their agentTypeId const profile = await agentsService.getMyProfile(); setAgentProfile(profile); if (!profile.agentTypeId) { setError('Your profile does not have an agent type assigned. Please contact support.'); setLoading(false); return; } // Now fetch the sections for this agent type const response: AgentTypeSectionsResponse = await profileSectionsService.getSectionsForAgentType(profile.agentTypeId); // Sort sections by effectiveSortOrder const sortedSections = [...response.sections].sort( (a, b) => (a.effectiveSortOrder || a.sortOrder) - (b.effectiveSortOrder || b.sortOrder) ); setSections(sortedSections); // Initialize form data with existing profile data + default values from fields const initialData: Record = {}; // Pre-fill with existing profile data if (profile.firstName) initialData['first-name'] = profile.firstName; if (profile.lastName) initialData['last-name'] = profile.lastName; if (profile.email) initialData['email'] = profile.email; if (profile.phone) initialData['phone'] = profile.phone; if (profile.bio) initialData['bio'] = profile.bio; if (profile.licenseNumber) initialData['license-number'] = profile.licenseNumber; if (profile.experience) initialData['experience'] = profile.experience; if (profile.specializations?.length) initialData['specializations'] = profile.specializations; if (profile.languages?.length) initialData['languages'] = profile.languages; if (profile.serviceAreas?.length) initialData['service-areas'] = profile.serviceAreas; // Then apply field default values where no existing data sortedSections.forEach(section => { section.fields?.forEach(field => { if (field.defaultValue && initialData[field.slug] === undefined) { // Parse default value based on field type switch (field.fieldType) { case 'CHECKBOX': initialData[field.slug] = field.defaultValue === 'true'; break; case 'NUMBER': case 'RANGE': initialData[field.slug] = parseFloat(field.defaultValue) || 0; break; case 'CHECKBOX_GROUP': case 'MULTI_SELECT': case 'TAG_INPUT': try { initialData[field.slug] = JSON.parse(field.defaultValue); } catch { initialData[field.slug] = []; } break; default: initialData[field.slug] = field.defaultValue; } } }); }); setFormData(initialData); } catch (err: unknown) { console.error('Failed to fetch data:', err); // Check for specific error types const error = err as { response?: { status?: number } }; if (error.response?.status === 401) { setError('You are not logged in or your session has expired. Please log in again.'); } else if (error.response?.status === 404) { setError('Agent profile not found. Please complete your registration first.'); } else { setError('Failed to load profile. Please try again.'); } } finally { setLoading(false); } }; fetchData(); }, []); const handleCancel = () => { router.push('/agent/dashboard'); }; const handleSave = async () => { try { setIsSaving(true); setFormErrors({}); // Validate required fields const errors: Record = {}; sections.forEach(section => { section.fields?.forEach(field => { if (field.isRequired && field.isActive && !field.isSearchableOnly) { const value = formData[field.slug]; const isEmpty = value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0); if (isEmpty) { errors[field.slug] = `${field.name} is required`; } } }); }); if (Object.keys(errors).length > 0) { setFormErrors(errors); // Scroll to first error const firstErrorField = Object.keys(errors)[0]; const errorElement = document.querySelector(`[data-field-slug="${firstErrorField}"]`); errorElement?.scrollIntoView({ behavior: 'smooth', block: 'center' }); return; } // TODO: Call API to save form data console.log('Saving form data:', formData); // Simulate save await new Promise(resolve => setTimeout(resolve, 500)); router.push('/agent/dashboard'); } catch (err) { console.error('Failed to save:', err); setError('Failed to save profile. Please try again.'); } finally { setIsSaving(false); } }; const handleFieldChange = (fieldSlug: string, value: unknown) => { setFormData(prev => ({ ...prev, [fieldSlug]: value })); // Clear error when field is modified if (formErrors[fieldSlug]) { setFormErrors(prev => { const newErrors = { ...prev }; delete newErrors[fieldSlug]; return newErrors; }); } }; if (loading) { return (

Loading profile sections...

); } if (error && sections.length === 0) { return (

Unable to Load Profile

{error}

); } return (
{/* Left Sidebar - Quick Links */}
{/* Main Content - Scrollable */}
{/* Inner container with padding for shadow visibility */}
{/* Error Banner */} {error && (

{error}

)} {/* Dynamic Sections */} {sections.map((section) => ( ))} {/* Empty State */} {sections.length === 0 && !loading && (

No Profile Sections Available

Profile sections have not been configured for your agent type yet.

)} {/* Action Buttons */} {sections.length > 0 && (
)}
); }