'use client';
import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import {
PlusCircle,
Building,
Home,
DollarSign,
MapPin,
Bed,
Bath,
Square,
Edit,
Trash2,
Eye,
Calendar,
TrendingUp,
Users,
FileText,
Image as ImageIcon,
CheckCircle,
XCircle,
AlertCircle,
ChevronRight,
ChevronLeft,
Loader2,
Clock,
Wifi,
Zap,
Flame,
Droplets,
Cigarette,
Dog,
Music,
Sofa,
DoorOpen,
Warehouse,
Layers,
Wind,
Pencil,
Save,
X
} from 'lucide-react';
import toast, { Toaster } from 'react-hot-toast';
import AuthService from '../../services/AuthService';
import { getMyRentListings } from '../../utils/api';
const DeleteConfirmationModal = ({ isOpen, onClose, onConfirm, propertyTitle }) => {
if (!isOpen) return null;
return (
e.stopPropagation()}
>
تأكيد الحذف
هل أنت متأكد من حذف العقار: "{propertyTitle}"؟
هذا الإجراء لا يمكن التراجع عنه
);
};
const PropertyViewModal = ({ isOpen, onClose, property }) => {
if (!isOpen || !property) return null;
const getServiceIcon = (serviceId) => {
const icons = {
electricity: Zap,
internet: Wifi,
heating: Flame,
water: Droplets,
airConditioning: Wind,
parking: Warehouse,
elevator: Layers
};
const Icon = icons[serviceId];
return Icon ? : null;
};
return (
e.stopPropagation()}
>
{property.title}
تم الإضافة: {new Date(property.createdAt).toLocaleDateString('ar-SA')}
{property.images && property.images.length > 0 && (
صور العقار
{property.images.map((image, index) => (
))}
)}
معلومات أساسية
نوع العقار:
{property.propertyType === 'apartment' ? 'شقة' :
property.propertyType === 'villa' ? 'فيلا' :
property.propertyType === 'suite' ? 'سويت' : 'غرفة ضمن شقة'}
الحالة:
{property.furnished ? 'مفروش' : 'غير مفروش'}
حالة العقار:
{property.status === 'available' ? 'متاح' : 'مؤجر'}
{property.description && (
الوصف:
{property.description}
)}
التفاصيل
{property.bedrooms}
غرف
{property.bathrooms}
حمامات
{property.area}
م²
{property.livingRooms && (
{property.livingRooms}
صالونات
)}
الموقع
{property.address || 'لم يتم تحديد العنوان'}
{property.city && `، ${property.city}`}
{property.district && `، ${property.district}`}
{property.services && Object.values(property.services).some(v => v) && (
الخدمات المتوفرة
{Object.entries(property.services).map(([key, value]) => {
if (!value) return null;
const Icon = getServiceIcon(key);
return (
{Icon}
{key === 'electricity' && 'كهرباء'}
{key === 'internet' && 'انترنت'}
{key === 'heating' && 'تدفئة'}
{key === 'water' && 'ماء'}
{key === 'airConditioning' && 'تكييف'}
{key === 'parking' && 'موقف سيارات'}
{key === 'elevator' && 'مصعد'}
);
})}
)}
{property.terms && Object.values(property.terms).some(v => v) && (
شروط الاستخدام
{Object.entries(property.terms).map(([key, value]) => {
if (!value) return null;
return (
{key === 'noSmoking' && ' ممنوع التدخين'}
{key === 'noPets' && ' ممنوع الحيوانات'}
{key === 'noParties' && ' ممنوع الحفلات'}
{key === 'noAlcohol' && ' ممنوع الكحول'}
{key === 'suitableForChildren' && ' مناسب للأطفال'}
{key === 'suitableForElderly' && ' مناسب لكبار السن'}
);
})}
)}
معلومات السعر
{property.purpose === 'rent' ? (
{property.dailyPrice && (
السعر اليومي:
{Number(property.dailyPrice).toLocaleString()} ل.س
)}
{property.monthlyPrice && (
السعر الشهري:
{Number(property.monthlyPrice).toLocaleString()} ل.س
)}
نوع الإيجار: {
property.rentType === 'daily' ? 'يومي' :
property.rentType === 'monthly' ? 'شهري' : 'يومي وشهري'
}
) : (
سعر البيع:
{Number(property.salePrice).toLocaleString()} ل.س
)}
);
};
const PropertyEditModal = ({ isOpen, onClose, property, onSave }) => {
const [formData, setFormData] = useState({ ...property });
const [isSaving, setIsSaving] = useState(false);
const [editingField, setEditingField] = useState(null);
const [tempValues, setTempValues] = useState({});
const sections = [
{
title: 'معلومات أساسية',
fields: [
{ id: 'title', label: 'عنوان العقار', type: 'text' },
{ id: 'description', label: 'الوصف', type: 'textarea' },
{
id: 'propertyType',
label: 'نوع العقار',
type: 'select',
options: [
{ value: 'apartment', label: 'شقة' },
{ value: 'villa', label: 'فيلا' },
{ value: 'suite', label: 'سويت' },
{ value: 'room', label: 'غرفة ضمن شقة' }
],
},
{
id: 'furnished',
label: 'حالة العقار',
type: 'radio',
options: [
{ value: true, label: 'مفروش' },
{ value: false, label: 'غير مفروش' }
],
}
]
},
{
title: 'التفاصيل',
fields: [
{ id: 'bedrooms', label: 'عدد الغرف', type: 'number' },
{ id: 'bathrooms', label: 'عدد الحمامات', type: 'number' },
{ id: 'livingRooms', label: 'عدد الصالونات', type: 'number' },
{ id: 'area', label: 'المساحة (م²)', type: 'number' }
]
},
{
title: 'الموقع',
fields: [
{ id: 'address', label: 'العنوان الكامل', type: 'text' },
{ id: 'city', label: 'المدينة', type: 'text' },
{ id: 'district', label: 'الحي', type: 'text' }
]
},
{
title: 'السعر',
fields: formData?.purpose === 'rent' ? [
{ id: 'dailyPrice', label: 'السعر اليومي', type: 'number' },
{ id: 'monthlyPrice', label: 'السعر الشهري', type: 'number' },
{
id: 'rentType',
label: 'نوع الإيجار',
type: 'select',
options: [
{ value: 'daily', label: 'يومي' },
{ value: 'monthly', label: 'شهري' },
{ value: 'both', label: 'يومي وشهري' }
],
}
] : [
{ id: 'salePrice', label: 'سعر البيع', type: 'number' }
]
}
];
const startEditing = (fieldId) => {
setEditingField(fieldId);
setTempValues({ ...tempValues, [fieldId]: formData[fieldId] });
};
const cancelEditing = () => {
setEditingField(null);
setTempValues({});
};
const saveField = (fieldId) => {
setFormData({
...formData,
[fieldId]: tempValues[fieldId]
});
setEditingField(null);
setTempValues({});
const fieldLabel = sections.flatMap(s => s.fields).find(f => f.id === fieldId)?.label;
toast.success(`تم تحديث ${fieldLabel}`);
};
const handleTempChange = (fieldId, value) => {
setTempValues({ ...tempValues, [fieldId]: value });
};
const handleSave = () => {
setIsSaving(true);
setTimeout(() => {
onSave(formData);
setIsSaving(false);
onClose();
toast.success('تم تحديث العقار بنجاح');
}, 1000);
};
if (!isOpen || !property) return null;
return (
e.stopPropagation()}
>
تعديل العقار
يمكنك تعديل أي حقل بالضغط على أيقونة القلم
{formData.images && formData.images.length > 0 && (
صور العقار
{formData.images.map((image, index) => (
))}
)}
{sections.map((section, sectionIndex) => (
{section.title}
{section.fields.map((field) => (
{editingField !== field.id && (
)}
{editingField === field.id ? (
{field.type === 'textarea' ? (
) : (
{field.type === 'select' ? (
field.options.find(opt => opt.value === formData[field.id])?.label || formData[field.id]
) : field.type === 'radio' ? (
formData[field.id] ? 'مفروش' : 'غير مفروش'
) : field.id.includes('Price') ? (
formData[field.id] ? `${Number(formData[field.id]).toLocaleString()} ل.س` : '—'
) : (
formData[field.id] || '—'
)}
)}
))}
))}
);
};
export default function OwnerPropertiesPage() {
const router = useRouter();
const [user, setUser] = useState(null);
const [properties, setProperties] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [showAddMenu, setShowAddMenu] = useState(false);
const [deleteModal, setDeleteModal] = useState({ isOpen: false, property: null });
const [viewModal, setViewModal] = useState({ isOpen: false, property: null });
const [editModal, setEditModal] = useState({ isOpen: false, property: null });
useEffect(() => {
const authUser = AuthService.getUser();
if (authUser && AuthService.isOwner()) {
setUser({
name: authUser.name || authUser.email,
email: authUser.email,
role: 'owner',
});
loadProperties();
} else {
router.push('/auth/choose-role');
}
}, [router]);
const loadProperties = async () => {
const authUser = AuthService.getUser();
const userId = authUser?.id;
if (!userId) {
console.warn('[OwnerProperties] No user ID found');
setIsLoading(false);
return;
}
try {
console.log('[OwnerProperties] Fetching listings for user:', userId);
const data = await getMyRentListings(userId);
const list = Array.isArray(data) ? data : (data ? [data] : []);
console.log('[OwnerProperties] API returned:', list.length, 'properties');
const mapped = list.map((item) => {
const info = item.propertyInformation || {};
const details = (() => {
try { return JSON.parse(info.detailsJSON || '{}'); } catch { return {}; }
})();
return {
id: item.id,
title: info.address || `عقار #${item.id}`,
propertyType: { 0: 'apartment', 1: 'villa', 2: 'house' }[info.buildingType] || 'apartment',
purpose: 'rent',
rentType: { 0: 'daily', 1: 'weekly', 2: 'monthly' }[item.rentType] || 'daily',
dailyPrice: item.dailyRent || 0,
monthlyPrice: item.monthlyRent || 0,
deposit: item.deposit || 0,
location: info.address || '',
bedrooms: info.numberOfBedRooms || 0,
bathrooms: info.numberOfBathRooms || 0,
area: info.space || 0,
livingRooms: details.livingRooms || 0,
status: { 0: 'available', 1: 'booked', 2: 'maintenance' }[info.status] || 'available',
images: (() => {
const apiBase = typeof window !== 'undefined' ? (process.env.NEXT_PUBLIC_API_URL || 'http://45.93.137.91/api') : '';
const raw = Array.isArray(info.images) ? info.images : [];
return raw.length > 0 ? raw.map(img => img.startsWith('http') ? img : `${apiBase}${img.startsWith('/') ? '' : '/'}${img}`) : ['/property-placeholder.jpg'];
})(),
createdAt: item.createdAt || new Date().toISOString(),
furnished: details.furnished || false,
description: info.description || '',
address: info.address || '',
city: '',
district: '',
services: details.services || {},
terms: details.terms || {},
rating: item.rating || 0,
currencyId: item.currencyId,
_raw: item,
};
});
setProperties(mapped);
} catch (err) {
console.error('[OwnerProperties] Failed to load properties:', err);
toast.error('فشل في تحميل العقارات');
} finally {
setIsLoading(false);
}
};
const updatePropertiesInStorage = (newProperties) => {
setProperties(newProperties);
localStorage.setItem('ownerProperties', JSON.stringify(newProperties));
};
const handleDelete = () => {
if (deleteModal.property) {
const newProperties = properties.filter(p => p.id !== deleteModal.property.id);
updatePropertiesInStorage(newProperties);
setDeleteModal({ isOpen: false, property: null });
toast.success('تم حذف العقار بنجاح');
}
};
const handleSaveEdit = (updatedProperty) => {
const newProperties = properties.map(p =>
p.id === updatedProperty.id ? updatedProperty : p
);
updatePropertiesInStorage(newProperties);
setEditModal({ isOpen: false, property: null });
};
const fadeInUp = {
initial: { opacity: 0, y: 20 },
animate: { opacity: 1, y: 0 },
transition: { duration: 0.5 }
};
if (isLoading) {
return (
);
}
return (
setDeleteModal({ isOpen: false, property: null })}
onConfirm={handleDelete}
propertyTitle={deleteModal.property?.title}
/>
setViewModal({ isOpen: false, property: null })}
property={viewModal.property}
/>
setEditModal({ isOpen: false, property: null })}
property={editModal.property}
onSave={handleSaveEdit}
/>
عقاراتي
مرحباً {user?.name}، لديك {properties.length} عقار
setShowAddMenu(!showAddMenu)}
className="bg-gradient-to-r from-amber-500 to-amber-600 text-white px-6 py-3 rounded-xl font-medium flex items-center gap-2 shadow-lg hover:shadow-xl transition-all"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
إضافة عقار جديد
{showAddMenu && (
setShowAddMenu(false)}
>
عقار للإيجار
أضف عقار متاح للإيجار
setShowAddMenu(false)}
>
عقار للبيع
أضف عقار متاح للبيع
)}
{properties.length === 0 ? (
لا توجد عقارات بعد
ابدأ بإضافة أول عقار لك الآن
إضافة عقار جديد
) : (
{properties.map((property, index) => (
{property.images && property.images.length > 0 ? (

) : (
)}
{property.status === 'available' ? 'متاح' : 'مؤجر'}
{property.title}
{property.address || property.location || 'موقع غير محدد'}
{property.bedrooms}
{property.bathrooms}
{property.area}م²
{property.purpose === 'rent' ? (
{property.dailyPrice && (
{Number(property.dailyPrice).toLocaleString()} ل.س
)}
{property.rentType === 'daily' ? '/يوم' :
property.rentType === 'monthly' ? '/شهر' :
property.dailyPrice && property.monthlyPrice ? '/يوم وشهر' : ''}
) : (
{Number(property.salePrice).toLocaleString()} ل.س
للبيع
)}
))}
)}
);
}