from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from .models import Cart
from .serializers import CartSerializer
from bookings.models import Booking
from bookings.serializers import BookingSerializer
from common.response_helper import ResponseHelper

class CartViewSet(viewsets.ModelViewSet):
    serializer_class = CartSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return Cart.objects.filter(user=self.request.user)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            paginated = self.get_paginated_response(serializer.data)
            return ResponseHelper.success(data=paginated.data, message='Cart list')

        serializer = self.get_serializer(queryset, many=True)
        return ResponseHelper.success(data=serializer.data, message='Cart list')

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            self.perform_create(serializer)
            return ResponseHelper.success(data=serializer.data, message='Cart created', status=status.HTTP_201_CREATED)
        return ResponseHelper.validation_error(errors=serializer.errors)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return ResponseHelper.success(data=serializer.data, message='Cart details')

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        if serializer.is_valid():
            self.perform_update(serializer)
            return ResponseHelper.success(data=serializer.data, message='Cart updated')
        return ResponseHelper.validation_error(errors=serializer.errors)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return ResponseHelper.success(message='Cart deleted', status=status.HTTP_204_NO_CONTENT)

    @action(detail=True, methods=['post'])
    def checkout(self, request, pk=None):
        cart = self.get_object()
        
        # Create Booking from Cart
        booking = Booking.objects.create(
            user=cart.user,
            quick_schedule=cart.quick_schedule,
            pickup_type=cart.pickup_type,
            schedule_pickup_date=cart.schedule_pickup_date,
            schedule_pickup_time=cart.schedule_pickup_time,
            contact_name=cart.contact_name,
            contact_mobile=cart.contact_mobile,
            pickup_instructions=cart.pickup_instructions,
            pickup_address=cart.pickup_address,
            geo_location=cart.geo_location,
            order_details=cart.order_details,
            premium_details=cart.premium_details,
            luxury_details=cart.luxury_details,
            total_quantity=cart.total_quantity,
            total_final_price=cart.total_final_price,
            currency_code=cart.currency_code
        )
        
        # Generate tags (Booking logic)
        booking.generate_item_tags()
        
        # Delete the cart after successful checkout
        cart.delete()
        
        # Return the created booking
        serializer = BookingSerializer(booking)
        return ResponseHelper.success(data=serializer.data, message='Cart checked out successfully', status=status.HTTP_201_CREATED)
