from datetime import datetime
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.exceptions import NotFound

from .models import VehiclePricing
from .serializers import (
    VehiclePricingCreateSerializer,
    VehiclePricingListSerializer,
    VehiclePricingDetailSerializer,
)
from vehicles.models import Vehicle
from .permissions import MethodRolePermission
from .authentication import JWTAuthentication


# -----------------------------------------------------------------------------
# 🔹 CREATE & LIST VEHICLE PRICINGS
# -----------------------------------------------------------------------------
class VehiclePricingView(APIView):
    """
    Handles creating (POST) and listing (GET) Vehicle Pricing entries.
    Each pricing record is directly linked to a specific Vehicle.
    """

    authentication_classes = [JWTAuthentication]
    permission_classes = [MethodRolePermission]

    allowed_roles = {
        "POST": ["admin"],
        "GET": ["admin", "partner"],
    }

    # ------------------ Utility Method ------------------

    def get_vehicle(self, vehicle_id):
        """
        Validate and fetch the Vehicle by ID.
        Returns (vehicle_obj, error_message)
        """
        if not vehicle_id:
            return None, "Vehicle ID is required."
        vehicle = Vehicle.objects(id=vehicle_id).first()
        if not vehicle:
            return None, f"Vehicle with ID '{vehicle_id}' not found."
        return vehicle, None

    # ------------------ POST: Create Pricing ------------------

    def post(self, request):
        """
        Create a new Vehicle Pricing record.
        Ensures valid vehicle and prevents duplicate pricing entries.
        """
        data = request.data
        vehicle_id = data.get("vehicle_id")

        # ✅ Validate vehicle reference
        vehicle, vehicle_err = self.get_vehicle(vehicle_id)
        if vehicle_err:
            return Response({"error": vehicle_err}, status=status.HTTP_400_BAD_REQUEST)

        # ✅ Check for duplicate pricing (1 pricing per vehicle)
        if VehiclePricing.objects(vehicle=vehicle).first():
            return Response(
                {"error": "Pricing for this vehicle already exists."},
                status=status.HTTP_400_BAD_REQUEST,
            )

        # ✅ Validate pricing data
        serializer = VehiclePricingCreateSerializer(data=data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        # ✅ Save new record
        pricing = serializer.save(vehicle=vehicle)

        return Response(
            {
                "message": "Vehicle Pricing created successfully.",
                "pricing_id": str(pricing.id),
            },
            status=status.HTTP_201_CREATED,
        )

    # ------------------ GET: List Pricings ------------------

    def get(self, request):
        """
        Retrieve all vehicles and their pricing data.
        If pricing not assigned, mark relevant fields as 'Not assigned'.
        """
        vehicles = Vehicle.objects.all()
        pricings = {str(p.vehicle.id): p for p in VehiclePricing.objects.all()}

        # Attach pricing object dynamically for serialization
        for vehicle in vehicles:
            vehicle.pricing = pricings.get(str(vehicle.id))

        serializer = VehiclePricingListSerializer(vehicles, many=True)

        return Response(
            {
                "count": len(vehicles),
                "results": serializer.data,
            },
            status=status.HTTP_200_OK,
        )



# -----------------------------------------------------------------------------
# 🔹 DETAIL / UPDATE VEHICLE PRICING
# -----------------------------------------------------------------------------
class VehiclePricingDetailView(APIView):
    """
    Retrieve or update Vehicle Pricing by Vehicle ID instead of Pricing ID.
    """

    authentication_classes = [JWTAuthentication]
    permission_classes = [MethodRolePermission]

    allowed_roles = {
        "GET": ["admin", "partner"],
        "PUT": ["admin"],
    }

    # ------------------ Utility: Fetch Pricing by Vehicle ID ------------------
    def get_object_by_vehicle(self, vehicle_id):
        """Fetch pricing by Vehicle ID or raise 404 if not found."""
        vehicle = Vehicle.objects(id=vehicle_id).first()
        if not vehicle:
            raise NotFound(detail=f"Vehicle with ID '{vehicle_id}' not found.")

        pricing = VehiclePricing.objects(vehicle=vehicle).first()
        if not pricing:
            raise NotFound(detail=f"Pricing for Vehicle ID '{vehicle_id}' not found.")

        return pricing

    # ------------------ GET: Retrieve Pricing by Vehicle ID ------------------
    def get(self, request, vehicle_id):
        """
        Retrieve a vehicle's pricing record by vehicle ID.
        If pricing is not assigned, return default values with NOT_ASSIGNED status.
        """
        vehicle = Vehicle.objects(id=vehicle_id).first()
        if not vehicle:
            raise NotFound(detail=f"Vehicle with ID '{vehicle_id}' not found.")

        pricing = VehiclePricing.objects(vehicle=vehicle).first()

        if pricing:
            # ✅ Pricing exists — serialize normally
            serializer = VehiclePricingDetailSerializer(pricing)
            data = serializer.data
            data["model_name"] = getattr(vehicle, "model_name", None)
            data["pickup_point_name"] = getattr(vehicle, "pickup_point_name", None)
            return Response(data, status=status.HTTP_200_OK)

        # ⚙️ Pricing not found — return default response
        # ⚙️ Pricing not found — return default response
        return Response(
            {
                "vehicle_id": str(vehicle.id),
                "status": "NOT_ASSIGNED",
                "model_name": getattr(vehicle, "model_name", None),
                "pickup_point_name": getattr(vehicle, "pickup_point_name", None),

                # Default pricing values
                "hourly_price_s": 0.0,
                "hourly_price_m": 0.0,
                "hourly_price_l": 0.0,
                "hourly_extra_price_per_km_s": 0.0,
                "hourly_extra_price_per_km_m": 0.0,
                "hourly_extra_price_per_km_l": 0.0,
                "monthly_price_s": 0.0,
                "monthly_price_m": 0.0,
                "monthly_price_l": 0.0,
                "monthly_extra_price_per_km_s": 0.0,
                "monthly_extra_price_per_km_m": 0.0,
                "monthly_extra_price_per_km_l": 0.0,
            },
            status=status.HTTP_200_OK,
        )



    # ------------------ PUT: Update Pricing by Vehicle ID ------------------
    def put(self, request, vehicle_id):
        """
        Update pricing for a given vehicle by vehicle ID.
        """
        vehicle = Vehicle.objects(id=vehicle_id).first()
        if not vehicle:
            raise NotFound(detail=f"Vehicle with ID '{vehicle_id}' not found.")

        pricing = VehiclePricing.objects(vehicle=vehicle).first()
        if not pricing:
            raise NotFound(detail=f"Pricing for Vehicle ID '{vehicle_id}' not found.")

        data = request.data

        # ✅ Validate serializer
        serializer = VehiclePricingDetailSerializer(pricing, data=data, partial=True)
        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        updated_pricing = serializer.save(vehicle=vehicle)

        return Response(
            {
                "message": "Vehicle Pricing updated successfully.",
                "data": VehiclePricingDetailSerializer(updated_pricing).data,
            },
            status=status.HTTP_200_OK,
        )