from rest_framework import viewsets, status, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from .models import Booking
from .serializers import BookingSerializer, BookingCreateSerializer
from common.permissions import IsPlaceAdmin, IsPlaceOwner
from common.pagination import StandardResultsSetPagination
from notifications.tasks import send_booking_reminder, schedule_booking_reminders
from notifications.services import send_fcm_notification


class BookingViewSet(viewsets.ModelViewSet):
    """Booking ViewSet"""
    permission_classes = [IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['place', 'status', 'type', 'date']
    ordering_fields = ['date', 'time', 'created_at']
    ordering = ['-date', '-time']
    
    def get_serializer_class(self):
        if self.action == 'create':
            return BookingCreateSerializer
        return BookingSerializer
    
    def get_queryset(self):
        user = self.request.user
        
        # Super Admin and Admin can see all bookings
        if user.role in ['super_admin', 'admin']:
            return Booking.objects.select_related('place', 'user', 'place__owner').all()
        
        # Place Admin can see bookings for their place
        if user.role == 'place_admin' and hasattr(user, 'place_admin_profile'):
            return Booking.objects.select_related('place', 'user', 'place__owner').filter(
                place=user.place_admin_profile.place
            )
        
        # Regular users can only see their own bookings
        return Booking.objects.select_related('place', 'user', 'place__owner').filter(user=user)
    
    def perform_create(self, serializer):
        """Create booking and send notifications"""
        booking = serializer.save()
        
        # Schedule booking reminders
        schedule_booking_reminders.delay()
        
        # Send notification to user
        if booking.user.fcm_token:
            send_fcm_notification(
                booking.user.fcm_token,
                'تم إنشاء الحجز',
                f'تم إنشاء حجز في {booking.place.name}',
                {
                    'booking_id': booking.id,
                    'place_id': booking.place.id,
                    'type': 'booking_created'
                }
            )
        
        # Send notification to place admin
        if hasattr(booking.place.owner, 'place_admin_profile') and booking.place.owner.fcm_token:
            send_fcm_notification(
                booking.place.owner.fcm_token,
                'حجز جديد',
                f'حجز جديد من {booking.user.username}',
                {
                    'booking_id': booking.id,
                    'place_id': booking.place.id,
                    'type': 'new_booking'
                }
            )
        
        return booking
    
    @action(detail=True, methods=['post'])
    def confirm(self, request, pk=None):
        """Confirm a booking"""
        booking = self.get_object()
        if not self._can_manage_booking(request.user, booking):
            return Response(
                {'error': 'You do not have permission to manage this booking'},
                status=status.HTTP_403_FORBIDDEN
            )
        booking.status = 'confirmed'
        booking.save()
        
        # Send notification to user
        if booking.user.fcm_token:
            send_fcm_notification(
                booking.user.fcm_token,
                'تم تأكيد الحجز',
                f'تم تأكيد حجزك في {booking.place.name}',
                {
                    'booking_id': booking.id,
                    'place_id': booking.place.id,
                    'type': 'booking_confirmed'
                }
            )
        
        return Response(BookingSerializer(booking).data)
    
    @action(detail=True, methods=['post'])
    def cancel(self, request, pk=None):
        """Cancel a booking"""
        booking = self.get_object()
        if not (self._can_manage_booking(request.user, booking) or booking.user == request.user):
            return Response(
                {'error': 'You do not have permission to cancel this booking'},
                status=status.HTTP_403_FORBIDDEN
            )
        booking.status = 'cancelled'
        booking.save()
        
        # Send notification
        if booking.user.fcm_token:
            cancelled_by = 'أنت' if booking.user == request.user else booking.place.name
            send_fcm_notification(
                booking.user.fcm_token,
                'تم إلغاء الحجز',
                f'تم إلغاء حجزك في {booking.place.name}',
                {
                    'booking_id': booking.id,
                    'place_id': booking.place.id,
                    'type': 'booking_cancelled'
                }
            )
        
        # Notify place admin if cancelled by user
        if booking.user == request.user and hasattr(booking.place.owner, 'place_admin_profile') and booking.place.owner.fcm_token:
            send_fcm_notification(
                booking.place.owner.fcm_token,
                'تم إلغاء الحجز',
                f'تم إلغاء حجز من {booking.user.username}',
                {
                    'booking_id': booking.id,
                    'place_id': booking.place.id,
                    'type': 'booking_cancelled'
                }
            )
        
        return Response(BookingSerializer(booking).data)
    
    @action(detail=True, methods=['post'])
    def complete(self, request, pk=None):
        """Complete a booking"""
        booking = self.get_object()
        if not self._can_manage_booking(request.user, booking):
            return Response(
                {'error': 'You do not have permission to manage this booking'},
                status=status.HTTP_403_FORBIDDEN
            )
        booking.status = 'completed'
        booking.save()
        return Response(BookingSerializer(booking).data)
    
    def _can_manage_booking(self, user, booking):
        """Check if user can manage booking"""
        if user.role in ['super_admin', 'admin']:
            return True
        if user.role == 'place_admin' and hasattr(user, 'place_admin_profile'):
            return user.place_admin_profile.place == booking.place
        return False
