'use client'; import { useState, useEffect, useCallback } from 'react'; import { useSession } from 'next-auth/react'; import api from '@/services/api'; type DigestFrequency = 'instant' | 'daily' | 'weekly' | 'off'; interface NotificationCategory { id: string; label: string; description: string; email: boolean; inApp: boolean; } interface NotificationsFormProps { onSave?: (data: { notifications: NotificationCategory[]; digestFrequency: DigestFrequency; }) => void; } const DEFAULT_NOTIFICATIONS: NotificationCategory[] = [ { id: 'new_lead_alerts', label: 'New Lead Alerts', description: 'Choose what you want to be notified about and how.', email: true, inApp: true, }, { id: 'message_updates', label: 'Message Updates', description: 'Notices about new messages from clients or other agents.', email: false, inApp: true, }, { id: 'urgent_requests_tours', label: 'Urgent Requests & Tours', description: 'Immediate notifications for tour requests and time-sensitive items.', email: true, inApp: true, }, ]; export function NotificationsForm({ onSave }: NotificationsFormProps) { const { data: session } = useSession(); const [isLoading, setIsLoading] = useState(true); const [isSaving, setIsSaving] = useState(false); const [error, setError] = useState(null); const [success, setSuccess] = useState(null); const [notifications, setNotifications] = useState(DEFAULT_NOTIFICATIONS); const [digestFrequency, setDigestFrequency] = useState('instant'); const [savedNotifications, setSavedNotifications] = useState(DEFAULT_NOTIFICATIONS); const [savedDigestFrequency, setSavedDigestFrequency] = useState('instant'); const fetchPreferences = useCallback(async () => { if (!session) return; try { setIsLoading(true); const role = (session?.user as any)?.role; const endpoint = role === 'AGENT' ? '/agents/preferences/notifications' : '/users/preferences/notifications'; const response = await api.get(endpoint); const savedPrefs = response.data?.data || response.data || {}; if (savedPrefs.notifications) { const updated = DEFAULT_NOTIFICATIONS.map((item) => { const saved = savedPrefs.notifications[item.id]; if (saved) { return { ...item, email: saved.email ?? item.email, inApp: saved.inApp ?? item.inApp, }; } return item; }); setNotifications(updated); setSavedNotifications(updated); } if (savedPrefs.digestFrequency) { setDigestFrequency(savedPrefs.digestFrequency); setSavedDigestFrequency(savedPrefs.digestFrequency); } } catch { console.log('No saved notification preferences found, using defaults'); } finally { setIsLoading(false); } }, [session]); useEffect(() => { fetchPreferences(); }, [fetchPreferences]); const toggleNotification = (id: string, type: 'email' | 'inApp') => { setNotifications((prev) => prev.map((item) => item.id === id ? { ...item, [type]: !item[type] } : item ) ); }; const handleSave = async () => { setIsSaving(true); setError(null); setSuccess(null); try { const role = (session?.user as any)?.role; const endpoint = role === 'AGENT' ? '/agents/preferences/notifications' : '/users/preferences/notifications'; const preferences = { notifications: notifications.reduce( (acc, item) => ({ ...acc, [item.id]: { email: item.email, inApp: item.inApp }, }), {} ), digestFrequency, }; await api.put(endpoint, preferences); setSavedNotifications([...notifications]); setSavedDigestFrequency(digestFrequency); setSuccess('Notification preferences saved successfully!'); if (onSave) { onSave({ notifications, digestFrequency }); } setTimeout(() => setSuccess(null), 3000); } catch (err: unknown) { const error = err as { response?: { data?: { message?: string } } }; setError(error.response?.data?.message || 'Failed to save notification preferences. Please try again.'); } finally { setIsSaving(false); } }; const hasChanges = JSON.stringify(notifications) !== JSON.stringify(savedNotifications) || digestFrequency !== savedDigestFrequency; const handleCancel = () => { if (!hasChanges) return; setNotifications([...savedNotifications]); setDigestFrequency(savedDigestFrequency); setError(null); setSuccess(null); }; const Checkbox = ({ checked, onToggle, label, }: { checked: boolean; onToggle: () => void; label: string; }) => ( ); const frequencyOptions: { value: DigestFrequency; label: string }[] = [ { value: 'instant', label: 'Instant' }, { value: 'daily', label: 'Daily' }, { value: 'weekly', label: 'Weekly' }, { value: 'off', label: 'Off' }, ]; if (isLoading) { return (
); } return ( <> {/* Error Message */} {error && (
{error}
)} {/* Success Message */} {success && (
{success}
)} {/* Notification Preferences Card */}
{/* Title */}

Notification Preferences

{/* Divider */}
{/* Notification Categories */}
{notifications.map((item, index) => (

{item.label}

{item.description}

toggleNotification(item.id, 'email')} label="Email" /> toggleNotification(item.id, 'inApp')} label="In-App" />
{index < notifications.length - 1 && (
)}
))}
{/* Divider before Email Digest */}
{/* Email Digest Frequency */}

Email Digest Frequency

Choose how often you receive non-urgent email summaries

{/* Frequency Tabs */}
{frequencyOptions.map((option, index) => (
{index < frequencyOptions.length - 1 && (
)}
))}
{/* Action Buttons */}
); }