'use client'; import { useState, useEffect, useCallback } from 'react'; import { useAuth } from '@/context/AuthContext'; import { storage, db, requestNotificationPermission, onMessageListener } from '@/lib/firebase'; import { ref, uploadBytes, getDownloadURL } from 'firebase/storage'; import { doc, getDoc, updateDoc } from 'firebase/firestore'; import { useTheme } from 'next-themes'; import Image from 'next/image'; interface UserProfile { avatarUrl?: string; theme?: string; categories?: string[]; notificationsEnabled?: boolean; fcmToken?: string; } export default function Profile() { const { user } = useAuth(); const { theme, setTheme } = useTheme(); const [profile, setProfile] = useState({}); const [uploading, setUploading] = useState(false); const [newCategory, setNewCategory] = useState(''); const [notificationsEnabled, setNotificationsEnabled] = useState(false); const loadProfile = useCallback(async () => { if (!user) return; try { const docRef = doc(db, 'users', user.uid); const docSnap = await getDoc(docRef); if (docSnap.exists()) { setProfile(docSnap.data() as UserProfile); setNotificationsEnabled(docSnap.data().notificationsEnabled ?? false); } } catch (error) { console.error('Error loading profile:', error); } }, [user]); useEffect(() => { if (user) { loadProfile(); } }, [user, loadProfile]); // Listen for FCM messages useEffect(() => { if (notificationsEnabled) { onMessageListener().then((payload: any) => { console.log('Message received:', payload); // Handle incoming messages (e.g., show notification) new Notification(payload.notification.title, { body: payload.notification.body, icon: '/icon-192x192.png' }); }).catch(err => console.log('Failed to listen for messages:', err)); } }, [notificationsEnabled]); const handleAvatarUpload = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file || !user) return; setUploading(true); try { const storageRef = ref(storage, `avatars/${user.uid}`); await uploadBytes(storageRef, file); const url = await getDownloadURL(storageRef); await updateDoc(doc(db, 'users', user.uid), { avatarUrl: url }); setProfile(prev => ({ ...prev, avatarUrl: url })); } catch (error) { console.error('Error uploading avatar:', error); } finally { setUploading(false); } }; const handleThemeChange = async (newTheme: string) => { setTheme(newTheme); if (user) { await updateDoc(doc(db, 'users', user.uid), { theme: newTheme }); setProfile(prev => ({ ...prev, theme: newTheme })); } }; const handleNotificationToggle = async (enabled: boolean) => { if (!user) return; try { if (enabled) { const token = await requestNotificationPermission(); if (token) { await updateDoc(doc(db, 'users', user.uid), { notificationsEnabled: true, fcmToken: token }); setProfile(prev => ({ ...prev, notificationsEnabled: true, fcmToken: token })); setNotificationsEnabled(true); } else { alert('Notification permission denied. Please enable notifications in your browser settings.'); } } else { await updateDoc(doc(db, 'users', user.uid), { notificationsEnabled: false, fcmToken: null }); setProfile(prev => ({ ...prev, notificationsEnabled: false, fcmToken: undefined })); setNotificationsEnabled(false); } } catch (error) { console.error('Error updating notification settings:', error); } }; const addCategory = async () => { if (!newCategory.trim() || !user) return; const updatedCategories = [...(profile.categories || []), newCategory.trim()]; await updateDoc(doc(db, 'users', user.uid), { categories: updatedCategories }); setProfile(prev => ({ ...prev, categories: updatedCategories })); setNewCategory(''); }; const removeCategory = async (category: string) => { if (!user) return; const updatedCategories = (profile.categories || []).filter(c => c !== category); await updateDoc(doc(db, 'users', user.uid), { categories: updatedCategories }); setProfile(prev => ({ ...prev, categories: updatedCategories })); }; const toggleNotifications = async () => { if (!user) return; const newStatus = !notificationsEnabled; setNotificationsEnabled(newStatus); await updateDoc(doc(db, 'users', user.uid), { notificationsEnabled: newStatus }); if (newStatus) { requestNotificationPermission(); } }; return (

Profile Settings

Manage your account and preferences

{/* Avatar Section */}

Profile Picture

{profile.avatarUrl ? ( Avatar ) : (
No Image
)}
{uploading &&

Uploading...

}
{/* Theme Section */}

Appearance

{/* Notifications Section */}

Notifications

handleNotificationToggle(e.target.checked)} className="w-5 h-5 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500 focus:ring-2" />

Get notified about your prayer schedule and when prayers are answered.

{/* Categories Section */}

Prayer Categories

setNewCategory(e.target.value)} placeholder="Add a new category" className="flex-1 p-3 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
{(profile.categories || []).map(category => ( {category} ))}
); }