'use client';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import { useEffect, useState, FormEvent } from 'react';
import { getAuth, updateProfile, updatePassword } from 'firebase/auth';
import { app } from '@/lib/firebase';
export default function SettingsPage() {
const { user, isLoading } = useAuth();
const router = useRouter();
const [name, setName] = useState('');
const [currentPassword, setCurrentPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [saving, setSaving] = useState(false);
const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
useEffect(() => {
if (!isLoading && !user) {
router.push('/auth');
}
if (user) {
setName(user.name || '');
}
}, [user, isLoading, router]);
if (isLoading) {
return (
);
}
if (!user) return null;
const handleUpdateProfile = async (e: FormEvent) => {
e.preventDefault();
setSaving(true);
setMessage(null);
try {
const auth = getAuth(app);
if (auth.currentUser && name !== user.name) {
await updateProfile(auth.currentUser, { displayName: name });
setMessage({ type: 'success', text: 'Profile updated successfully!' });
}
} catch (error: any) {
setMessage({ type: 'error', text: error.message || 'Failed to update profile' });
} finally {
setSaving(false);
}
};
const handleChangePassword = async (e: FormEvent) => {
e.preventDefault();
setSaving(true);
setMessage(null);
if (newPassword !== confirmPassword) {
setMessage({ type: 'error', text: 'Passwords do not match' });
setSaving(false);
return;
}
if (newPassword.length < 6) {
setMessage({ type: 'error', text: 'Password must be at least 6 characters' });
setSaving(false);
return;
}
try {
const auth = getAuth(app);
if (auth.currentUser) {
await updatePassword(auth.currentUser, newPassword);
setMessage({ type: 'success', text: 'Password changed successfully!' });
setCurrentPassword('');
setNewPassword('');
setConfirmPassword('');
}
} catch (error: any) {
if (error.code === 'auth/requires-recent-login') {
setMessage({ type: 'error', text: 'Please log out and log back in to change your password' });
} else {
setMessage({ type: 'error', text: error.message || 'Failed to change password' });
}
} finally {
setSaving(false);
}
};
return (
{/* Navigation */}
Account Settings
Manage your profile and account preferences
{/* Success/Error Message */}
{message && (
{message.text}
)}
{/* Account Info */}
{/* Profile Settings */}
{/* Change Password */}
);
}