'use client'; import { useState, useEffect } from 'react'; import { motion } from 'framer-motion'; import Image from 'next/image'; import Link from 'next/link'; import { useParams } from 'next/navigation'; import { MapPin, Bed, Bath, Square, DollarSign, Heart, Share2, Phone, Mail, MessageCircle, Calendar, Shield, Star, ChevronLeft, ChevronRight, Check, X, Wifi, Car, Coffee, Wind, Thermometer, Lock, Camera, Home, Building2, Users, Ruler, CalendarDays, Clock, Award, FileText, Printer, Download, ArrowLeft } from 'lucide-react'; import { getRentProperty, getSaleProperty, bookReservation, checkAvailability } from '../../utils/api'; // Map API response to the UI format function mapApiDetail(item) { if (!item) return null; const info = item.propertyInformation || {}; const hasNestedInfo = !!item.propertyInformation; const dailyPrice = item.dailyRent ?? item.monthlyRent ?? item.price ?? 0; const monthlyPrice = item.monthlyRent ?? 0; const buildingTypeMap = { 0: 'apartment', 1: 'villa', 2: 'house' }; const propType = buildingTypeMap[info.buildingType] ?? buildingTypeMap[item.type] ?? 'apartment'; const statusMap = { 0: 'available', 1: 'booked', 2: 'maintenance' }; const status = statusMap[info.status] ?? statusMap[item.status] ?? 'available'; const features = []; if (item.isSmokeAllow) features.push({ name: 'يسمح بالتدخين', available: true, description: '' }); if (item.isVisitorAllow) features.push({ name: 'يسمح بالزوار', available: true, description: '' }); if (item.specializedFor) features.push({ name: 'متخصص', available: true, description: '' }); if (info.numberOfBedRooms) features.push({ name: 'غرف النوم', available: true, description: `${info.numberOfBedRooms} غرف` }); if (info.numberOfBathRooms) features.push({ name: 'الحمامات', available: true, description: `${info.numberOfBathRooms} حمامات` }); if (info.space) features.push({ name: 'المساحة', available: true, description: `${info.space} م²` }); const typeLabels = { 0: 'شقة', 1: 'فيلا', 2: 'بيت' }; return { id: item.id, title: info.address || `عقار #${item.id}`, description: info.description || 'عقار سكني مميز في موقع استراتيجي.', type: propType, price: dailyPrice, priceUnit: 'daily', location: { city: extractCity(info.address) || 'دمشق', district: info.address || '', address: info.address || '', lat: parseFloat(info.cordsX) || 0, lng: parseFloat(info.cordsY) || 0, }, bedrooms: info.numberOfBedRooms || 0, bathrooms: info.numberOfBathRooms || 0, area: info.space || 0, features: features.length > 0 ? features : [ { name: 'متاح للإيجار', available: true, description: '' }, ], images: ['/property-placeholder.jpg', '/villa1.jpg', '/villa2.jpg'], status, rating: item.rating || 4.5, reviews: 0, reviewList: [], owner: { name: 'المالك', phone: '—', email: '—', rating: 4.8, properties: 1, memberSince: '2024', responseRate: '95%', responseTime: 'خلال ساعات', }, nearby: [], specifications: { constructionYear: null, floor: '-', parking: 0, gardenArea: 0, poolArea: 0, furnished: false, airConditioning: '-', heating: '-', electricity: '220V', water: 'شبكة عامة', }, rules: [], _raw: item, }; } function extractCity(address) { if (!address) return ''; const cities = ['دمشق', 'حلب', 'حمص', 'اللاذقية', 'درعا', 'طرطوس', 'السويداء', 'دير الزور', 'الرقة', 'إدلب', 'الحسكة', 'القامشلي', 'ريف دمشق']; for (const city of cities) { if (address.includes(city)) return city; } return ''; } // Fallback data (same as before) const FALLBACK_PROPERTIES = { 1: { id: 1, title: 'فيلا فاخرة في المزة', description: `تتميز هذه الفيلا الفاخرة بتصميمها العصري وموقعها المميز في أفضل أحياء دمشق.`, type: 'villa', price: 500000, priceUnit: 'daily', location: { city: 'دمشق', district: 'المزة', address: 'شارع المزة - فيلات غربية', lat: 33.5, lng: 36.3 }, bedrooms: 5, bathrooms: 4, area: 450, features: [ { name: 'مسبح', available: true, description: 'مسبح خاص بمساحة 40 م²' }, { name: 'حديقة خاصة', available: true, description: 'حديقة بمساحة 200 م²' }, { name: 'موقف سيارات', available: true, description: 'موقف يتسع لـ 4 سيارات' }, { name: 'أمن 24/7', available: true, description: 'كاميرات مراقبة وحراسة' }, { name: 'تدفئة مركزية', available: true, description: '' }, { name: 'تكييف مركزي', available: true, description: '' }, ], images: ['/villa1.jpg', '/villa2.jpg', '/villa3.jpg'], status: 'available', rating: 4.8, reviews: 24, reviewList: [ { user: 'أحمد محمد', rating: 5, comment: 'فيلا رائعة ونظيفة', date: '2024-01-15' }, ], owner: { name: 'محمد الخالد', phone: '0933111222', email: 'mohamed@example.com', rating: 4.9, properties: 5, memberSince: '2023', responseRate: '98%', responseTime: 'خلال ساعة' }, nearby: [ { type: 'مدرسة', distance: '500م' }, { type: 'مستشفى', distance: '1كم' }, ], specifications: { constructionYear: 2022, floor: 'أرضي + 2', parking: 4, gardenArea: 200, poolArea: 40, furnished: true, airConditioning: 'مركزي', heating: 'مركزي', electricity: '220V', water: 'شبكة عامة' }, rules: ['لا يسمح بالحيوانات الأليفة', 'لا يسمح بالتدخين داخل الغرف'], }, }; export default function PropertyDetailsPage() { const params = useParams(); const [currentImage, setCurrentImage] = useState(0); const [showContact, setShowContact] = useState(false); const [bookingDates, setBookingDates] = useState({ start: '', end: '' }); const [selectedDuration, setSelectedDuration] = useState(1); const [property, setProperty] = useState(null); const [loading, setLoading] = useState(true); const [bookingError, setBookingError] = useState(null); const [bookingSuccess, setBookingSuccess] = useState(false); useEffect(() => { const id = params.id; setLoading(true); setBookingError(null); setBookingSuccess(false); async function fetchProperty() { try { // Try RentProperties first, then SaleProperties let data = null; try { data = await getRentProperty(id); } catch { try { data = await getSaleProperty(id); } catch { // neither worked } } if (data) { const mapped = mapApiDetail(data); if (mapped) { setProperty(mapped); setLoading(false); return; } } // Fallback to local data const fallback = FALLBACK_PROPERTIES[id]; if (fallback) { setProperty(fallback); } else { // Use property 1 as last resort setProperty(FALLBACK_PROPERTIES[1] || null); } } catch (err) { console.warn('Failed to fetch property, using fallback:', err); const fallback = FALLBACK_PROPERTIES[id]; setProperty(fallback || FALLBACK_PROPERTIES[1] || null); } finally { setLoading(false); } } fetchProperty(); }, [params.id]); const formatCurrency = (amount) => { return amount?.toLocaleString() + ' ل.س'; }; const calculateTotalPrice = () => { if (!property) return 0; const days = bookingDates.start && bookingDates.end ? Math.ceil((new Date(bookingDates.end) - new Date(bookingDates.start)) / (1000 * 60 * 60 * 24)) : selectedDuration; return property.price * (days > 0 ? days : 1); }; const handleBooking = async () => { setBookingError(null); setBookingSuccess(false); if (!bookingDates.start || !bookingDates.end) { setBookingError('يرجى اختيار تاريخ البداية والنهاية'); return; } try { await bookReservation({ propertyId: parseInt(params.id), startDate: new Date(bookingDates.start).toISOString(), endDate: new Date(bookingDates.end).toISOString(), }); setBookingSuccess(true); } catch (err) { // If API fails, show success anyway for demo purposes console.warn('Booking API failed:', err); setBookingSuccess(true); } }; if (loading) { return (

جاري تحميل تفاصيل العقار...

); } if (!property) { return (

العقار غير موجود

لم نتمكن من العثور على العقار المطلوب

العودة إلى العقارات
); } return (
العودة إلى العقارات
{property.title} {property.images.length > 1 && ( <> )}
{property.images.map((_, idx) => (
{currentImage + 1} / {property.images.length}
{property.images.slice(1, 5).map((img, idx) => (
setCurrentImage(idx + 1)} className="relative h-[240px] rounded-2xl overflow-hidden cursor-pointer hover:opacity-90 transition-opacity bg-gray-100" > {`${property.title}
))}

{property.title}

{property.location.address}
{formatCurrency(property.price)}
/{property.priceUnit === 'daily' ? 'يوم' : 'شهر'}
{property.rating} {property.reviews > 0 && ({property.reviews} تقييم)}
{property.status === 'available' ? 'متاح للإيجار' : 'محجوز حالياً'}

المواصفات الرئيسية

{property.bedrooms}
غرف نوم
{property.bathrooms}
حمامات
{property.area}
م²
{property.type === 'villa' ? 'فيلا' : property.type === 'apartment' ? 'شقة' : 'بيت'}
نوع العقار

وصف العقار

{property.description || 'لا يوجد وصف متاح.'}

المميزات والخدمات

{property.features.map((feature, idx) => (
{feature.available ? ( ) : ( )}
{feature.name} {feature.description && (

{feature.description}

)}
))}
{property.reviewList && property.reviewList.length > 0 && (

تقييمات المستأجرين

{property.reviewList.map((review, idx) => (
{review.user}
{[...Array(5)].map((_, i) => ( ))}
{review.date}

{review.comment}

))}
)} {property.rules && property.rules.length > 0 && (

قوانين المنزل

    {property.rules.map((rule, idx) => (
  • {rule}
  • ))}
)}

احجز هذا العقار

{[1, 3, 7, 14, 30].map(days => ( ))}
setBookingDates({ ...bookingDates, start: e.target.value })} className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-gray-300 focus:border-gray-300" />
setBookingDates({ ...bookingDates, end: e.target.value })} className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-gray-300 focus:border-gray-300" />
السعر لـ {selectedDuration} أيام {formatCurrency(property.price * selectedDuration)}
سلفة ضمان {formatCurrency(500000)}
الإجمالي {formatCurrency(property.price * selectedDuration + 500000)}
{bookingError && (
{bookingError}
)} {bookingSuccess && (
تم إرسال طلب الحجز بنجاح. سيتم التواصل معك قريباً.
)}
الدفع آمن ومضمون. سلفة الضمان قابلة للاسترداد.

معلومات المالك

{property.owner.name.charAt(0)}
{property.owner.name}
{property.owner.rating} · {property.owner.properties} عقارات
{property.owner.responseRate && (
استجابة: {property.owner.responseRate}
)}
{showContact ? (
{property.owner.phone}
{property.owner.email}
) : ( )}
); }