from celery import shared_task
from django.utils import timezone
from datetime import timedelta
from .models import Notification
from bookings.models import Booking
from offers.models import Offer


@shared_task
def send_booking_reminder(booking_id):
    """Send reminder notification for upcoming booking"""
    try:
        booking = Booking.objects.get(id=booking_id)
        user = booking.user
        
        # Create notification
        Notification.objects.create(
            user=user,
            type='booking_reminder',
            title='تذكير بالحجز',
            message=f'لديك حجز في {booking.place.name} في {booking.date} الساعة {booking.time}',
            data={'booking_id': booking.id, 'place_id': booking.place.id}
        )
        
        # Send FCM notification
        if user.fcm_token:
            from .services import send_fcm_notification
            send_fcm_notification(
                user.fcm_token,
                'تذكير بالحجز',
                message,
                {'booking_id': booking.id, 'place_id': booking.place.id, 'type': 'booking_reminder'}
            )
        
    except Booking.DoesNotExist:
        pass


@shared_task
def schedule_booking_reminders():
    """Schedule reminders for upcoming bookings"""
    # Remind 1 day before
    tomorrow = timezone.now() + timedelta(days=1)
    bookings = Booking.objects.filter(
        date=tomorrow.date(),
        status__in=['pending', 'confirmed']
    )
    
    for booking in bookings:
        send_booking_reminder.apply_async(
            args=[booking.id],
            eta=timezone.now() + timedelta(hours=20)  # 20 hours from now
        )
    
    # Remind 1 hour before
    one_hour_later = timezone.now() + timedelta(hours=1)
    bookings = Booking.objects.filter(
        date=one_hour_later.date(),
        time__hour=one_hour_later.hour,
        status__in=['pending', 'confirmed']
    )
    
    for booking in bookings:
        send_booking_reminder.apply_async(
            args=[booking.id],
            eta=one_hour_later
        )


@shared_task
def check_expired_offers():
    """Check and deactivate expired offers"""
    now = timezone.now()
    expired_offers = Offer.objects.filter(
        is_active=True,
        end_date__lt=now
    )
    
    for offer in expired_offers:
        offer.is_active = False
        offer.save()
        
        # Notify place admin
        if hasattr(offer.place.owner, 'place_admin_profile'):
            Notification.objects.create(
                user=offer.place.owner,
                type='offer_expired',
                title='انتهى العرض',
                message=f'انتهى عرض "{offer.title}"',
                data={'offer_id': offer.id}
            )


@shared_task
def send_new_review_notification(review_id):
    """Send notification when new review is added"""
    try:
        from reviews.models import Review
        review = Review.objects.get(id=review_id)
        place = review.place
        
        # Notify place admin
        if hasattr(place.owner, 'place_admin_profile'):
            Notification.objects.create(
                user=place.owner,
                type='review_new',
                title='تقييم جديد',
                message=f'تقييم جديد من {review.user.username} - {review.rating} نجوم',
                data={'review_id': review.id, 'place_id': place.id}
            )
    except Exception as e:
        print(f'Error sending review notification: {e}')

