from rest_framework import generics, permissions
from rest_framework.views import APIView
from category.models import Category
from garments.models import Garment
from .models import Service
from .serializers import ServiceSerializer
from common.response_helper import ResponseHelper


class ServiceListAPIView(generics.ListAPIView):
    """Public list of services. Returns standardized envelope using ResponseHelper."""
    queryset = Service.objects.all()
    serializer_class = ServiceSerializer
    permission_classes = [permissions.AllowAny]

    def list(self, request, *args, **kwargs):
        qs = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(qs)
        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='Services list')

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


class ServiceDetailAPIView(generics.RetrieveAPIView):
    """Public service detail endpoint. Returns standardized envelope using ResponseHelper."""
    queryset = Service.objects.all()
    serializer_class = ServiceSerializer
    permission_classes = [permissions.AllowAny]

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

class HousekeepingServiceAPIView(APIView):
    """
    API View to list Housekeeping services grouped by sub-categories (In-house, B2B).
    Pricing is 'After Inspection'.
    """
    permission_classes = [permissions.AllowAny]

    def get(self, request, *args, **kwargs):
        try:
            # Find the main Housekeeping category
            parent_category = Category.objects.filter(name__iexact='Housekeeping', trash=False).first()
            if not parent_category:
                return ResponseHelper.error(message="Housekeeping category not found.")

            # Find sub-categories (In-house, B2B)
            sub_categories = Category.objects.filter(parent=parent_category, trash=False)

            data = []
            for sub in sub_categories:
                # Find items (Garments) for this sub-category
                items = Garment.objects.filter(category=sub, trash=False)
                
                items_data = []
                for item in items:
                    items_data.append({
                        "id": item.id,
                        "name": item.name,
                        "description": item.description,
                        # Garment model currently doesn't have an image field
                        "pricing_type": "inspection",
                        "price_label": "After Inspection"
                    })

                data.append({
                    "category_id": sub.id,
                    "category_name": sub.name,
                    "category_image": sub.image.url if sub.image else None,
                    "items": items_data
                })

            return ResponseHelper.success(data=data, message="Housekeeping services list")

        except Exception as e:
            return ResponseHelper.server_error(message=str(e))
