'use client';
import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import {
Calendar,
ChevronLeft,
ChevronRight,
Home,
Building,
MapPin,
Bed,
Bath,
Square,
DollarSign,
Eye,
ArrowLeft,
Loader2,
Filter,
Download,
Printer,
ChevronDown,
X,
CheckCircle,
XCircle,
Clock,
Users,
TrendingUp,
CalendarDays,
LayoutGrid,
List,
AlertCircle,
XCircle as XCircleIcon,
Calendar as CalendarIcon
} from 'lucide-react';
import toast, { Toaster } from 'react-hot-toast';
import AuthService from '../../../services/AuthService';
const MonthlyCalendar = ({ properties, selectedPropertyId, onDateClick, onPropertySelect }) => {
const [currentMonth, setCurrentMonth] = useState(new Date());
const [selectedDate, setSelectedDate] = useState(null);
const [viewType, setViewType] = useState('grid');
const monthNames = [
'يناير', 'فبراير', 'مارس', 'إبريل', 'مايو', 'يونيو',
'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'
];
const daysInMonth = new Date(
currentMonth.getFullYear(),
currentMonth.getMonth() + 1,
0
).getDate();
const firstDayOfMonth = new Date(
currentMonth.getFullYear(),
currentMonth.getMonth(),
1
).getDay();
const isDateBookedForProperty = (date, property) => {
if (!property?.bookings) return false;
const dateStr = date.toISOString().split('T')[0];
return property.bookings.some(booking => {
const start = new Date(booking.startDate);
const end = new Date(booking.endDate);
const current = new Date(date);
return current >= start && current <= end;
});
};
const getDayStatus = (date) => {
if (selectedPropertyId === 'all') {
const totalProperties = properties.length;
const bookedCount = properties.filter(p => isDateBookedForProperty(date, p)).length;
if (bookedCount === 0) return { status: 'all_available', label: 'جميع العقارات متاحة', color: 'bg-green-100 text-green-800' };
if (bookedCount === totalProperties) return { status: 'all_booked', label: 'جميع العقارات محجوزة', color: 'bg-red-100 text-red-800' };
return { status: 'partial', label: `${bookedCount}/${totalProperties} محجوز`, color: 'bg-yellow-100 text-yellow-800' };
} else {
const property = properties.find(p => p.id === selectedPropertyId);
if (!property) return { status: 'no_property', label: 'غير متاح', color: 'bg-gray-100 text-gray-500' };
const isBooked = isDateBookedForProperty(date, property);
return {
status: isBooked ? 'booked' : 'available',
label: isBooked ? 'محجوز' : 'متاح',
color: isBooked ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'
};
}
};
const handleDateClick = (date) => {
setSelectedDate(date);
onDateClick?.(date);
};
const changeMonth = (direction) => {
setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() + direction, 1));
};
const renderDays = () => {
const days = [];
const totalDays = daysInMonth + firstDayOfMonth;
for (let i = 0; i < totalDays; i++) {
if (i < firstDayOfMonth) {
days.push(
);
} else {
const dayNumber = i - firstDayOfMonth + 1;
const date = new Date(
currentMonth.getFullYear(),
currentMonth.getMonth(),
dayNumber
);
const isToday = date.toDateString() === new Date().toDateString();
const status = getDayStatus(date);
const isSelected = selectedDate?.toDateString() === date.toDateString();
days.push(
);
}
}
return days;
};
return (
{monthNames[currentMonth.getMonth()]} {currentMonth.getFullYear()}
{['أحد', 'إثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'].map((day, index) => (
{day}
))}
);
};
const PropertyCalendarList = ({ properties, selectedDate, onPropertyClick }) => {
const formatCurrency = (amount) => {
return amount?.toLocaleString() + ' ل.س';
};
const isDateBooked = (property, date) => {
if (!property?.bookings || !date) return false;
const dateStr = date.toISOString().split('T')[0];
return property.bookings.some(booking => {
const start = new Date(booking.startDate);
const end = new Date(booking.endDate);
const current = new Date(date);
return current >= start && current <= end;
});
};
const getBookingForDate = (property, date) => {
if (!property?.bookings || !date) return null;
const dateStr = date.toISOString().split('T')[0];
return property.bookings.find(booking => {
const start = new Date(booking.startDate);
const end = new Date(booking.endDate);
const current = new Date(date);
return current >= start && current <= end;
});
};
if (!selectedDate) {
return (
اختر تاريخاً
اضغط على أي يوم في التقويم لعرض حالة العقارات في ذلك التاريخ
);
}
const formattedDate = selectedDate.toLocaleDateString('ar-SA', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
return (
حالة العقارات في تاريخ: {formattedDate}
{properties.map((property) => {
const isBooked = isDateBooked(property, selectedDate);
const booking = getBookingForDate(property, selectedDate);
return (
onPropertyClick(property)}
>
{property.title}
{isBooked ? 'محجوز' : 'متاح'}
{property.location}
{property.bedrooms} غرف
{property.bathrooms} حمامات
{property.area} م²
{formatCurrency(property.price)}
/يوم
{isBooked && booking && (
مستأجر: {booking.tenantName || 'غير معروف'}
من: {booking.startDate} إلى {booking.endDate}
)}
);
})}
);
};
const PropertyDetailsModal = ({ property, isOpen, onClose }) => {
if (!isOpen || !property) return null;
const formatCurrency = (amount) => {
return amount?.toLocaleString() + ' ل.س';
};
return (
e.stopPropagation()}
>
{property.title}
{property.location}
{property.images && property.images.length > 0 && (
صور العقار
{property.images.slice(0, 4).map((image, index) => (
))}
)}
{property.bedrooms}
غرف نوم
{property.bathrooms}
حمامات
{formatCurrency(property.price)}
/يوم
{property.features && property.features.length > 0 && (
المميزات
{property.features.map((feature, index) => (
{feature}
))}
)}
{property.bookings && property.bookings.length > 0 && (
الحجوزات القادمة
{property.bookings.slice(0, 3).map((booking, index) => (
{booking.startDate} - {booking.endDate}
مستأجر: {booking.tenantName || 'غير معروف'}
{formatCurrency(booking.totalAmount)}
))}
)}
تعديل العقار
);
};
export default function OwnerCalendarPage() {
const router = useRouter();
const [user, setUser] = useState(null);
const [properties, setProperties] = useState([]);
const [filteredProperties, setFilteredProperties] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [selectedPropertyId, setSelectedPropertyId] = useState('all');
const [selectedDate, setSelectedDate] = useState(null);
const [selectedProperty, setSelectedProperty] = useState(null);
const [showFilters, setShowFilters] = useState(false);
useEffect(() => {
const storedUser = localStorage.getItem('user');
// User loaded via AuthService
// Handled above
if (userData.role !== 'owner') {
router.push('/');
} else {
setUser(userData);
loadProperties();
}
} else {
router.push('/auth/choose-role');
}
}, [router]);
const loadProperties = () => {
const storedProperties = localStorage.getItem('ownerProperties');
if (storedProperties) {
const props = JSON.parse(storedProperties);
setProperties(props);
setFilteredProperties(props);
} else {
const mockProperties = [
{
id: 1,
title: 'فيلا فاخرة في المزة',
location: 'دمشق، المزة',
bedrooms: 5,
bathrooms: 4,
area: 450,
price: 500000,
features: ['مسبح', 'حديقة خاصة', 'موقف سيارات', 'أمن 24/7'],
images: ['/villa1.jpg'],
status: 'available',
bookings: [
{ startDate: '2024-03-10', endDate: '2024-03-15', totalAmount: 2500000, tenantName: 'أحمد محمد' },
{ startDate: '2024-03-20', endDate: '2024-03-25', totalAmount: 2500000, tenantName: 'سارة أحمد' }
]
},
{
id: 2,
title: 'شقة حديثة في الشهباء',
location: 'حلب، الشهباء',
bedrooms: 3,
bathrooms: 2,
area: 180,
price: 250000,
features: ['مطبخ مجهز', 'بلكونة', 'موقف سيارات', 'مصعد'],
images: ['/apartment1.jpg'],
status: 'available',
bookings: [
{ startDate: '2024-03-05', endDate: '2024-03-08', totalAmount: 750000, tenantName: 'محمد علي' }
]
},
{
id: 3,
title: 'بيت عائلي في بابا عمرو',
location: 'حمص، بابا عمرو',
bedrooms: 4,
bathrooms: 3,
area: 300,
price: 350000,
features: ['حديقة كبيرة', 'موقف سيارات', 'مدفأة', 'كراج'],
images: ['/house1.jpg'],
status: 'booked',
bookings: []
}
];
setProperties(mockProperties);
setFilteredProperties(mockProperties);
localStorage.setItem('ownerProperties', JSON.stringify(mockProperties));
}
setIsLoading(false);
};
const calendarStats = {
totalProperties: properties.length,
availableToday: properties.filter(p => {
const today = new Date();
const isBooked = p.bookings?.some(b => {
const start = new Date(b.startDate);
const end = new Date(b.endDate);
return today >= start && today <= end;
});
return !isBooked;
}).length,
bookedToday: properties.filter(p => {
const today = new Date();
return p.bookings?.some(b => {
const start = new Date(b.startDate);
const end = new Date(b.endDate);
return today >= start && today <= end;
});
}).length,
upcomingBookings: properties.reduce((sum, p) => sum + (p.bookings?.length || 0), 0)
};
if (isLoading) {
return (
);
}
return (
setSelectedProperty(null)}
/>
تقويم العقارات
مرحباً {user?.name}، تتبع حالة عقاراتك عبر التقويم
{/*
*/}
{calendarStats.totalProperties}
إجمالي العقارات
{calendarStats.availableToday}
متاح اليوم
{calendarStats.bookedToday}
محجوز اليوم
{calendarStats.upcomingBookings}
حجوزات قادمة
{showFilters && (
)}
{selectedDate && (
اضغط على أي عقار لعرض التفاصيل الكاملة
)}
);
}