"""
Bookings Views
"""
from django.shortcuts import render, get_object_or_404, redirect
from django.db.models import Q
from django.utils import timezone
from config.decorators import login_required_web
from bookings.models import Booking, BookingStatus
from places.models import Place


@login_required_web
def my_bookings_view(request):
    """User bookings list"""
    status_filter = request.GET.get('status', '')
    
    bookings = Booking.objects.filter(
        user=request.user
    ).select_related('place', 'place__category', 'place__governorate').order_by('-date', '-time')
    
    if status_filter:
        bookings = bookings.filter(status=status_filter)
    
    # Separate upcoming and past bookings
    now = timezone.now()
    upcoming_bookings = []
    past_bookings = []
    
    for booking in bookings:
        booking_datetime = timezone.make_aware(
            timezone.datetime.combine(booking.date, booking.time)
        )
        if booking_datetime > now and booking.status != BookingStatus.CANCELLED:
            upcoming_bookings.append(booking)
        else:
            past_bookings.append(booking)
    
    context = {
        'title': 'حجوزاتي - دليلك IQ',
        'description': 'إدارة حجوزاتك',
        'upcoming_bookings': upcoming_bookings,
        'past_bookings': past_bookings,
        'status_filter': status_filter,
    }
    return render(request, 'bookings/list.html', context)


@login_required_web
def create_booking_view(request, slug):
    """Create booking page"""
    place = get_object_or_404(
        Place.objects.select_related('category', 'governorate'),
        slug=slug,
        is_active=True,
        has_booking=True
    )
    
    if request.method == 'POST':
        # Booking will be created via API from frontend
        messages.success(request, 'تم إرسال طلب الحجز بنجاح')
        return redirect('/my-bookings/')
    
    from datetime import date
    context = {
        'title': f'حجز موعد في {place.name} - دليلك IQ',
        'description': f'احجز موعدك في {place.name}',
        'place': place,
        'today': date.today().isoformat(),
    }
    return render(request, 'bookings/create.html', context)
