'use client'; import { useState, useEffect, useRef } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { useRouter } from 'next/navigation'; import Link from 'next/link'; import Image from 'next/image'; import { User, Mail, Phone, MessageCircle, Camera, Save, X, CheckCircle, AlertCircle, ArrowLeft, Building, Home, Calendar, MapPin, Edit, Loader2, Upload, Check, Pencil } from 'lucide-react'; import toast, { Toaster } from 'react-hot-toast'; export default function ProfilePage() { const router = useRouter(); const [user, setUser] = useState(null); const [isLoading, setIsLoading] = useState(true); const [isSaving, setIsSaving] = useState(false); const [editingField, setEditingField] = useState(null); const [formData, setFormData] = useState({ name: '', email: '', phone: '', whatsapp: '', bio: '', location: '', joinedDate: '' }); const [tempValues, setTempValues] = useState({}); const [avatar, setAvatar] = useState(null); const [avatarPreview, setAvatarPreview] = useState(''); const [errors, setErrors] = useState({}); const fileInputRef = useRef(null); const inputRefs = { name: useRef(null), email: useRef(null), phone: useRef(null), whatsapp: useRef(null), location: useRef(null), bio: useRef(null) }; useEffect(() => { const storedUser = localStorage.getItem('user'); if (storedUser) { const userData = JSON.parse(storedUser); setUser(userData); const savedProfile = localStorage.getItem('userProfile'); let profileData; if (savedProfile) { profileData = JSON.parse(savedProfile); } else { profileData = { name: userData.name || '', email: userData.email || '', phone: '', whatsapp: '', bio: '', location: '', joinedDate: new Date().toLocaleDateString('ar-SA', { month: 'long', year: 'numeric' }) }; } setFormData(profileData); setTempValues(profileData); const savedAvatar = localStorage.getItem('userAvatar'); if (savedAvatar) { setAvatarPreview(savedAvatar); } setIsLoading(false); } else { router.push('/login'); } }, [router]); useEffect(() => { if (editingField && inputRefs[editingField]?.current) { inputRefs[editingField].current.focus(); } }, [editingField]); const handleImageUpload = (file) => { if (!file) return; if (!file.type.startsWith('image/')) { toast.error('الرجاء اختيار صورة صالحة'); return; } if (file.size > 2 * 1024 * 1024) { toast.error('حجم الصورة يجب أن يكون أقل من 2 ميجابايت'); return; } const reader = new FileReader(); reader.onloadend = () => { setAvatarPreview(reader.result); localStorage.setItem('userAvatar', reader.result); toast.success('تم تغيير الصورة بنجاح'); }; reader.readAsDataURL(file); }; const validateField = (field, value) => { if (field === 'email' && value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) { return 'البريد الإلكتروني غير صالح'; } if ((field === 'phone' || field === 'whatsapp') && value && !/^(09|05)[0-9]{8}$/.test(value)) { return 'رقم الهاتف غير صالح (يجب أن يبدأ 09 أو 05)'; } if (field === 'name' && !value?.trim()) { return 'الاسم مطلوب'; } return null; }; const startEditing = (field) => { setEditingField(field); setTempValues(prev => ({ ...prev, [field]: formData[field] })); setErrors(prev => ({ ...prev, [field]: null })); }; const cancelEditing = () => { setEditingField(null); setTempValues({}); setErrors({}); }; const saveField = (field) => { const value = tempValues[field]; const error = validateField(field, value); if (error) { setErrors(prev => ({ ...prev, [field]: error })); return; } const updatedData = { ...formData, [field]: value }; setFormData(updatedData); localStorage.setItem('userProfile', JSON.stringify(updatedData)); if (field === 'name') { const updatedUser = { ...user, name: value }; localStorage.setItem('user', JSON.stringify(updatedUser)); setUser(updatedUser); } setEditingField(null); setTempValues({}); toast.success(`تم تحديث ${getFieldLabel(field)} بنجاح`); }; const handleKeyDown = (e, field) => { if (e.key === 'Enter') { saveField(field); } else if (e.key === 'Escape') { cancelEditing(); } }; const getFieldLabel = (field) => { const labels = { name: 'الاسم', email: 'البريد الإلكتروني', phone: 'رقم الهاتف', whatsapp: 'رقم الواتساب', location: 'الموقع', bio: 'نبذة عني' }; return labels[field] || field; }; const getFieldIcon = (field) => { const icons = { name: User, email: Mail, phone: Phone, whatsapp: MessageCircle, location: MapPin, bio: User }; const Icon = icons[field]; return Icon ? : null; }; const fadeInUp = { initial: { opacity: 0, y: 20 }, animate: { opacity: 1, y: 0 }, transition: { duration: 0.5 } }; if (isLoading) { return (

جاري تحميل الملف الشخصي...

); } return (
العودة للرئيسية
fileInputRef.current?.click()}> {avatarPreview ? ( {formData.name} ) : ( formData.name?.charAt(0).toUpperCase() || 'U' )}
handleImageUpload(e.target.files?.[0])} className="hidden" />
{editingField === 'name' ? (
setTempValues({...tempValues, name: e.target.value})} onKeyDown={(e) => handleKeyDown(e, 'name')} className="text-3xl font-bold text-center border-b-2 border-amber-500 outline-none px-2 py-1 w-64" placeholder="الاسم الكامل" />
) : ( <>

{formData.name}

)}
{errors.name && (

{errors.name}

)}
{editingField === 'location' ? (
setTempValues({...tempValues, location: e.target.value})} onKeyDown={(e) => handleKeyDown(e, 'location')} className="border-b border-amber-500 outline-none px-2 py-1" placeholder="الموقع" />
) : ( <> {formData.location || 'الموقع غير محدد'} )}
عضو منذ {formData.joinedDate}
{editingField !== 'email' && ( )}
{editingField === 'email' ? (
setTempValues({...tempValues, email: e.target.value})} onKeyDown={(e) => handleKeyDown(e, 'email')} className="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent" placeholder="example@domain.com" />
{errors.email && (

{errors.email}

)}
) : (
{formData.email}
)}
{editingField !== 'phone' && ( )}
{editingField === 'phone' ? (
setTempValues({...tempValues, phone: e.target.value})} onKeyDown={(e) => handleKeyDown(e, 'phone')} className="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent" placeholder="09XXXXXXXX" />
{errors.phone && (

{errors.phone}

)}
) : (
{formData.phone || 'غير محدد'}
)}
{editingField !== 'whatsapp' && ( )}
{editingField === 'whatsapp' ? (
setTempValues({...tempValues, whatsapp: e.target.value})} onKeyDown={(e) => handleKeyDown(e, 'whatsapp')} className="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent" placeholder="09XXXXXXXX" />
{errors.whatsapp && (

{errors.whatsapp}

)}
) : (
{formData.whatsapp || 'غير محدد'}
)}
{user?.role === 'owner' ? ( <> مالك عقار ) : ( <> مستأجر )}
{editingField !== 'bio' && ( )}
{editingField === 'bio' ? (