"""
Admin API views for managing WhatsApp orders and configuration.
"""
import logging
from django.utils import timezone
from rest_framework import generics, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import Booking
from .permissions import IsAdmin, IsRestaurantOwnerOrAdmin
from .serializers import BookingSerializer
from . import whatsapp_service as wa

logger = logging.getLogger(__name__)


class WhatsAppOrderListView(generics.ListAPIView):
    """
    GET: List all WhatsApp-originated orders with filtering.
    Query params:
      - restaurant_id: filter by restaurant
      - status: filter by order status
      - date_from / date_to: date range filter
      - page / page_size: pagination
    """
    serializer_class = BookingSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        qs = Booking.objects.filter(
            order_notes__icontains='WhatsApp'
        ).select_related('restaurant', 'customer').prefetch_related('items__menu_item')

        # Filter by restaurant
        restaurant_id = self.request.query_params.get('restaurant_id')
        if restaurant_id:
            qs = qs.filter(restaurant_id=restaurant_id)

        # Filter by status
        order_status = self.request.query_params.get('status')
        if order_status:
            qs = qs.filter(status=order_status)

        # Filter by booking type
        booking_type = self.request.query_params.get('booking_type')
        if booking_type:
            qs = qs.filter(booking_type=booking_type)

        # Date range
        date_from = self.request.query_params.get('date_from')
        if date_from:
            qs = qs.filter(created_at__date__gte=date_from)
        date_to = self.request.query_params.get('date_to')
        if date_to:
            qs = qs.filter(created_at__date__lte=date_to)

        # Restrict non-admin users to their own restaurants
        user = self.request.user
        if user.role not in ('ADMIN',):
            qs = qs.filter(restaurant__owner=user)

        return qs.order_by('-created_at')


class WhatsAppOrderStatusUpdateView(APIView):
    """
    PATCH: Update a WhatsApp order's status and automatically notify the customer.
    Body: {"status": "PREPARING"}
    """
    permission_classes = [IsAuthenticated]

    def patch(self, request, pk):
        try:
            booking = Booking.objects.get(pk=pk)
        except Booking.DoesNotExist:
            return Response({'error': 'Order not found'}, status=status.HTTP_404_NOT_FOUND)

        # Authorization check
        user = request.user
        if user.role != 'ADMIN' and booking.restaurant.owner != user:
            return Response({'error': 'Permission denied'}, status=status.HTTP_403_FORBIDDEN)

        new_status = request.data.get('status')
        valid_statuses = [s[0] for s in Booking.STATUS_CHOICES]
        if new_status not in valid_statuses:
            return Response(
                {'error': f'Invalid status. Valid: {", ".join(valid_statuses)}'},
                status=status.HTTP_400_BAD_REQUEST
            )

        old_status = booking.status
        booking.status = new_status
        booking.save(update_fields=['status'])

        return Response({
            'id': booking.id,
            'old_status': old_status,
            'new_status': new_status,
            'message': f'Order #{booking.id} status updated to {new_status}',
        })


class WhatsAppDashboardStatsView(APIView):
    """
    GET: Dashboard statistics for WhatsApp orders.
    Returns counts by status, today's orders, revenue, etc.
    """
    permission_classes = [IsAuthenticated]

    def get(self, request):
        from django.db.models import Count, Sum, Q

        # Base queryset
        qs = Booking.objects.filter(order_notes__icontains='WhatsApp')

        # Restrict non-admin to their restaurants
        user = request.user
        restaurant_id = request.query_params.get('restaurant_id')
        if user.role != 'ADMIN':
            qs = qs.filter(restaurant__owner=user)
        if restaurant_id:
            qs = qs.filter(restaurant_id=restaurant_id)

        today = timezone.now().date()

        # Today's stats
        today_qs = qs.filter(created_at__date=today)

        stats = {
            'total_orders': qs.count(),
            'today_orders': today_qs.count(),
            'today_revenue': float(today_qs.aggregate(
                total=Sum('total_amount')
            )['total'] or 0),
            'pending_orders': qs.filter(status='CONFIRMED').count(),
            'preparing_orders': qs.filter(status='PREPARING').count(),
            'ready_orders': qs.filter(status='READY').count(),
            'completed_today': today_qs.filter(status='COMPLETED').count(),
            'by_type': {
                'takeaway': qs.filter(booking_type='TAKEAWAY').count(),
                'delivery': qs.filter(booking_type='DELIVERY').count(),
                'dine_in': qs.filter(booking_type='DINE_IN').count(),
            },
            'by_status': dict(
                qs.values_list('status').annotate(count=Count('id')).values_list('status', 'count')
            ),
        }

        return Response(stats)
