from datetime import datetime
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.utils import timezone
from rest_framework.exceptions import NotFound
import random
import string

from bson import ObjectId
from vehicles.models import Vehicle
from explorePlaces.models import Place
from accessories.models import Accessories,VehicleModel
from pricing.models import VehiclePricing
from accounts.authentication import JWTAuthentication
from accounts.permissions import MethodRolePermission
from orders.serializers import (
    FleetSerializer,
    CouponSerializer,
    SimpleAccessorySerializer,
    OrderSerializer,
    AdminBookingListSerializer
)
from .models import Coupon, Order

import traceback

# ================================================================
# 🔹 Fleet Pricing List (Fixed + with Image URL)
# ================================================================
class FleetPricingListView(APIView):
    """
    Fetch all available fleets (vehicles) WITH pricing and image URL,
    filtered by city name or pickup point.
    """

    authentication_classes = [JWTAuthentication]
    permission_classes = [MethodRolePermission]
    allowed_roles = {"GET": ["admin", "partner", "customer"]}

    def get(self, request):
        city_name = request.query_params.get("city_name")
        pickup_point_name = request.query_params.get("pickup_point")
        duration_type = request.query_params.get("duration_type", "HOURS").upper()
        vehicle_type = request.query_params.get("vehicle_type", "S").upper()

        try:
            # 1️⃣ Filter Vehicles
            if city_name:
                places = Place.objects(city__iexact=city_name)
                vehicles = Vehicle.objects(pickup_point__in=places, status="Active", verification_status__ne="Booked")

            elif pickup_point_name:
                place = Place.objects(name__iexact=pickup_point_name).first()
                if not place:
                    return Response(
                        {"message": "Pickup point not found"},
                        status=status.HTTP_404_NOT_FOUND,
                    )
                vehicles = Vehicle.objects(pickup_point__in=places, status="Active", verification_status__ne="Booked")
            else:
                return Response(
                    {"message": "Please provide either 'city_name' or 'pickup_point'"},
                    status=status.HTTP_400_BAD_REQUEST,
                )

            # 2️⃣ Filter Vehicles with Pricing
            priced_vehicles = [
                v for v in vehicles if VehiclePricing.objects(vehicle=v, status="ASSIGNED").first()
            ]
            if not priced_vehicles:
                return Response(
                    {"message": "No priced vehicles found for given filters"},
                    status=status.HTTP_404_NOT_FOUND,
                )

            # 3️⃣ Serialize fleet data
            serializer = FleetSerializer(priced_vehicles, many=True, context={"request": request})
            serialized_data = serializer.data

            # 4️⃣ Combine with pricing + image
            response_fleets = []
            for idx, fleet_data in enumerate(serialized_data):
                vehicle_obj = priced_vehicles[idx]  # directly use matching object
                pricing_data = fleet_data.pop("pricing", None)
                base_price = None

                # 🖼️ Add Image URL
                image_url = None
                if getattr(vehicle_obj, "vehicle_images", []):
                    image_url = str(vehicle_obj.vehicle_images[0])

                # 🏷️ Determine Base Price
                if pricing_data:
                    if duration_type == "HOURS":
                        base_km_key = f"hourly_base_km_{vehicle_type.lower()}"
                        price_key = f"hourly_price_{vehicle_type.lower()}"
                        price_type = "hourly"
                    else:
                        base_km_key = f"monthly_base_km_{vehicle_type.lower()}"
                        price_key = f"monthly_price_{vehicle_type.lower()}"
                        price_type = "monthly"

                    base_km = pricing_data.get(base_km_key, 0)
                    price_value = pricing_data.get(price_key, 0)

                    base_price = {
                        "type": price_type,
                        "vehicle_size": vehicle_type,
                        "price": price_value,
                        "base_km": base_km,
                    }

                # ✅ Add clean vehicle data
                fleet_data["id"] = str(vehicle_obj.id)
                fleet_data["image_url"] = image_url
                fleet_data["base_price"] = base_price

                response_fleets.append(fleet_data)

            # ✅ Final response
            return Response(
                {
                    "filters": {
                        "city_name": city_name,
                        "pickup_point": pickup_point_name,
                        "duration_type": duration_type,
                        "vehicle_type": vehicle_type,
                    },
                    "fleets": response_fleets,
                },
                status=status.HTTP_200_OK,
            )

        except Exception as e:
            print("❌ Error in FleetPricingListView:")
            print(traceback.format_exc())
            return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# ================================================================
# 🔹 Coupon CRUD
# ================================================================
class CouponCreateView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [MethodRolePermission]
    allowed_roles = {"POST": ["admin"]}

    def post(self, request):
        serializer = CouponSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(
                {"message": "✅ Coupon created successfully", "data": serializer.data},
                status=status.HTTP_201_CREATED,
            )
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class CouponUpdateView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [MethodRolePermission]
    allowed_roles = {"PUT": ["admin"]}

    def put(self, request, pk):
        try:
            coupon = Coupon.objects.get(id=pk)
        except Coupon.DoesNotExist:
            raise NotFound(detail="Coupon not found")

        serializer = CouponSerializer(coupon, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(
                {"message": "✅ Coupon updated successfully", "data": serializer.data},
                status=status.HTTP_200_OK,
            )
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class CouponDetailView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [MethodRolePermission]
    allowed_roles = {"GET": ["admin", "partner", "customer"]}

    def get(self, request, pk):
        try:
            coupon = Coupon.objects.get(id=pk)
        except Coupon.DoesNotExist:
            raise NotFound(detail="Coupon not found")
        serializer = CouponSerializer(coupon)
        return Response(serializer.data, status=status.HTTP_200_OK)


class CouponListView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [MethodRolePermission]
    allowed_roles = {"GET": ["admin"]}

    def get(self, request):
        coupons = Coupon.objects.all().order_by("-created_at")
        serializer = CouponSerializer(coupons, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class CouponFilterView(APIView):
    """
    Suggests applicable coupons based on user input.
    """

    authentication_classes = [JWTAuthentication]
    permission_classes = [MethodRolePermission]
    allowed_roles = {"GET": ["admin", "partner", "customer"]}

    def get(self, request):
        price = request.GET.get("price")
        kms = request.GET.get("kms")
        hours = request.GET.get("hours")
        now = timezone.now()

        coupons = Coupon.objects.filter(is_active=True, valid_from__lte=now, valid_till__gte=now)
        applicable = []

        for c in coupons:
            if c.depends_on == "PRICE" and price and float(price) >= (c.min_price or 0):
                applicable.append(c)
            elif c.depends_on == "KMS" and kms and float(kms) >= (c.min_kms or 0):
                applicable.append(c)
            elif c.depends_on == "TIME" and hours and float(hours) >= (c.min_time_in_hours or 0):
                applicable.append(c)

        serializer = CouponSerializer(applicable, many=True)
        return Response(
            {"count": len(applicable), "message": "✅ Coupons fetched", "coupons": serializer.data},
            status=status.HTTP_200_OK,
        )


class PartnerAccessoriesListView(APIView):
    """
    Get all active & approved accessories for a vehicle's partner/pickup point.
    """

    def get(self, request):
        vehicle_id = request.query_params.get("vehicle_id")
        if not vehicle_id:
            return Response({"error": "Missing 'vehicle_id' parameter"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # ----------------------------------------------------------
            # 1️⃣ Validate and fetch vehicle
            # ----------------------------------------------------------
            vehicle = Vehicle.objects.get(id=vehicle_id)
            partner = getattr(vehicle, "partner", None)
            pickup_point = getattr(vehicle, "pickup_point", None)

            if not partner:
                raise NotFound("Partner not found for this vehicle.")
            if not pickup_point:
                raise NotFound("Pickup point not found for this vehicle.")

            # ----------------------------------------------------------
            # 2️⃣ Fetch all approved and active accessories for that partner/pickup
            # ----------------------------------------------------------
            accessories = Accessories.objects(
                partner=partner,
                pickup_point=pickup_point,
                status="Active",
                verification_status="Approved",
            )

            # ----------------------------------------------------------
            # 3️⃣ Build response list
            # ----------------------------------------------------------
            accessories_data = []
            for acc in accessories:
                # Safely get model_type
                model_type = None

                try:
                    # Case 1: acc.model is a ReferenceField → access directly
                    if hasattr(acc.model, "type"):
                        model_type = acc.model.type

                    # Case 2: acc.model is an ObjectId → fetch VehicleModel
                    elif acc.model:
                        model_obj = VehicleModel.objects(id=acc.model).first()
                        model_type = getattr(model_obj, "type", None) if model_obj else None

                except Exception as e:
                    print(f"⚠️ Unable to resolve model type for accessory {acc.id}: {e}")

                # Append cleaned data
                accessories_data.append({
                    "id": str(acc.id),
                    "name": acc.submodel_name or acc.model_name or "Unnamed Accessory",
                    "price": acc.price,
                    "type": model_type,
                    "image": acc.image_urls[0] if acc.image_urls else None,
                })

            # ----------------------------------------------------------
            # 4️⃣ Return response
            # ----------------------------------------------------------
            return Response(accessories_data, status=status.HTTP_200_OK)

        except Vehicle.DoesNotExist:
            raise NotFound("Vehicle not found.")
        except Exception as e:
            print("❌ Error in PartnerAccessoriesListView:", traceback.format_exc())
            return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

# ================================================================
# 🔹 Create Order (Customer only)
# ================================================================
class OrderCreateView(APIView):
    """
    Create a new order.
    """

    authentication_classes = [JWTAuthentication]
    permission_classes = [MethodRolePermission]
    allowed_roles = {"POST": ["admin", "partner", "customer"]}

    def post(self, request):
        try:
            user = request.user
            if user.role != "customer":
                return Response({"error": "Only customers can create orders"}, status=403)

            data = request.data.copy()
            data["customer_id"] = str(user.id)
            serializer = OrderSerializer(data=data)

            if serializer.is_valid():
                order = serializer.save()
                return Response(
                    {
                        "message": "✅ Order created successfully",
                        "order_id": str(order.id),
                        "overall_price": order.overall_price,
                        "price_after_discount": order.price_after_discount,
                    },
                    status=201,
                )
            return Response(serializer.errors, status=400)

        except Exception as e:
            print("❌ Error in OrderCreateView:", traceback.format_exc())
            return Response({"error": str(e)}, status=500)


# ================================================================
# 🔹 Get Customer Order by ID
# ================================================================
class CustomerOrderDetailView(APIView):
    """
    Get complete order details for a customer by order_id.
    """

    authentication_classes = [JWTAuthentication]
    permission_classes = [MethodRolePermission]
    allowed_roles = {"GET": ["admin", "partner", "customer"]}

    def get(self, request, order_id):
        try:
            user = request.user
            if user.role != "customer":
                return Response({"error": "Only customers can access this route"}, status=403)

            # Fetch the order
            order = Order.objects.filter(id=order_id, customer=user.id).first()
            if not order:
                return Response({"error": "Order not found"}, status=404)

            # Fetch related data
            vehicle = Vehicle.objects.filter(id=order.vehicle.id).first()
            pickup_point = getattr(order, "pickup_point", None)
            pricing = VehiclePricing.objects(vehicle=vehicle).first()

            # --------------------------
            # VEHICLE INFO
            # --------------------------
            vehicle_type = getattr(vehicle, "vehicle_type", "S").upper()
            vehicle_data = {
                "id": str(vehicle.id),
                "model_name": getattr(vehicle, "model_name", None),
                "image_url": (
                   str(vehicle.vehicle_images[0]) if getattr(vehicle, "vehicle_images", []) else None
                    if getattr(vehicle, "vehicle_images", [])
                    else None
                ),
                "type": vehicle_type,  # S / M / L
            }

            # --------------------------
            # PICKUP POINT
            # --------------------------
            pickup_data = {
                "name": getattr(pickup_point, "name", None),
                "city": getattr(pickup_point, "city", None),
                "location": getattr(pickup_point, "location", None),
            } if pickup_point else None

            # --------------------------
            # ACCESSORIES
            # --------------------------
            accessories_data = []
            for acc in getattr(order, "accessories", []):
                accessory = getattr(acc, "accessory", None)
                if accessory:
                    accessories_data.append({
                        "id": str(accessory.id),
                        "name": getattr(accessory, "name", getattr(accessory, "submodel_name", "Unknown")),
                        "image_url": (
                            str(accessory.image_urls[0]) if getattr(accessory, "image_urls", []) else None
                            if getattr(accessory, "image_urls", [])
                            else None
                        ),

                        "quantity": getattr(acc, "quantity", 1),
                        "price_per_unit": float(getattr(accessory, "price", 0)),
                        "total_price": float(getattr(accessory, "price", 0)) * getattr(acc, "quantity", 1),
                    })

            # --------------------------
            # COUPON
            # --------------------------
            coupon_data = None
            coupon = getattr(order, "coupon", None)
            if coupon:
                coupon_data = {
                    "code": getattr(coupon, "code", None),
                    "description": getattr(coupon, "description", None),
                    "discount_applied": float(order.overall_price) - float(order.price_after_discount),
                }

            # --------------------------
            # PRICING SUMMARY
            # --------------------------
            accessories_total = sum(a["total_price"] for a in accessories_data)
            base_vehicle_amount = float(order.overall_price) - accessories_total

            pricing_data = {
                "base_vehicle_amount": base_vehicle_amount,
                "accessories_total": accessories_total,
                "discount": float(order.overall_price) - float(order.price_after_discount),
                "total_payable_amount": float(order.price_after_discount),
            }

            km_info = None
            if pricing:
                type_map = {"S": "s", "M": "m", "L": "l"}
                vehicle_size = type_map.get(vehicle_type.upper(), "s")

                # Calculate total duration in hours
                duration_hours = (order.to_date - order.from_date).total_seconds() / 3600

                # Decide whether booking is hourly or monthly
                duration_type = "hourly"
                if duration_hours >= 24 * 30:  # 30 days threshold
                    duration_type = "monthly"

                # Pick correct field prefix
                base_km_field = f"{duration_type}_base_km_{vehicle_size}"
                extra_price_field = f"{duration_type}_extra_price_per_km_{vehicle_size}"

                base_km_limit = getattr(pricing, base_km_field, 0)
                extra_price_per_km = getattr(pricing, extra_price_field, 0)

                # Convert to float to avoid Decimal issues
                km_info = {
                    "base_km_limit": float(base_km_limit),
                    "extra_price_per_km": float(extra_price_per_km),
                }

                print(f"✅ Duration Type: {duration_type}")
                print(f"✅ Base KM Field: {base_km_field} = {base_km_limit}")
                print(f"✅ Extra KM Field: {extra_price_field} = {extra_price_per_km}")



            # --------------------------
            # FINAL RESPONSE
            # --------------------------
            return Response(
                {
                    "order_id": str(order.id),
                    "pickup_point": pickup_data,
                    "vehicle": vehicle_data,
                    "accessories": accessories_data,
                    "coupon": coupon_data,
                    "pricing": pricing_data,
                    "km_info": km_info,
                    "pickup_date_time": order.from_date,
                    "drop_date_time": order.to_date,
                    "status": getattr(order, "status", None),
                    "created_at": getattr(order, "created_at", None),
                },
                status=200,
            )

        except Exception as e:
            print("❌ Error in CustomerOrderDetailView:", traceback.format_exc())
            return Response({"error": str(e)}, status=500)

# ================================================================
# 🔹 Update Order (PATCH) — update coupon, dates, or cancel order
# ================================================================
class OrderUpdateView(APIView):
    """
    Allows customers to:
    - Update coupon
    - Update booking dates
    - Cancel the order (releasing the vehicle)
    """

    authentication_classes = [JWTAuthentication]
    permission_classes = [MethodRolePermission]
    allowed_roles = {"PATCH": ["customer", "admin"]}

    def patch(self, request, order_id):
        try:
            user = request.user

            # ✅ 1️⃣ Fetch Order
            order = Order.objects(id=order_id, customer=user.id).first()
            if not order:
                return Response({"error": "Order not found"}, status=status.HTTP_404_NOT_FOUND)

            data = request.data

            # ✅ 2️⃣ Handle Cancellation
            if data.get("status") and data["status"].lower() == "cancelled":
                if order.status == "Cancelled":
                    return Response({"message": "Order already cancelled."}, status=status.HTTP_400_BAD_REQUEST)

                vehicle = order.vehicle
                if vehicle:
                    vehicle.status = "Active"
                    vehicle.verification_status = "Approved"
                    vehicle.save()
                    print(f"✅ Vehicle {vehicle.id} reactivated after cancellation.")

                order.status = "Cancelled"
                order.save()
                return Response({"message": "✅ Order cancelled successfully."}, status=status.HTTP_200_OK)

            # ✅ 3️⃣ Update Booking Dates (if provided)
            if "from_date" in data:
                order.from_date = datetime.fromisoformat(data["from_date"])
            if "to_date" in data:
                order.to_date = datetime.fromisoformat(data["to_date"])

            # ✅ 4️⃣ Update Coupon (if provided)
            if "coupon_id" in data:
                coupon_id = data["coupon_id"]
                coupon = Coupon.objects(id=coupon_id).first()
                if not coupon:
                    return Response({"error": "Invalid coupon ID"}, status=status.HTTP_400_BAD_REQUEST)

                # Apply new coupon
                order.coupon = coupon
                if not coupon.is_valid():
                    return Response({"error": "Coupon is expired or inactive"}, status=status.HTTP_400_BAD_REQUEST)

                # Recalculate price
                order.apply_coupon()

            # ✅ 5️⃣ Save Updates
            order.updated_at = datetime.utcnow()
            order.save()

            return Response(
                {
                    "message": "✅ Order updated successfully",
                    "order_id": str(order.id),
                    "status": order.status,
                    "price_after_discount": float(order.price_after_discount),
                    "coupon_code": order.coupon.code if order.coupon else None,
                    "from_date": order.from_date,
                    "to_date": order.to_date,
                },
                status=status.HTTP_200_OK,
            )

        except Exception as e:
            print("❌ Error in OrderUpdateView:", traceback.format_exc())
            return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class OrderPaymentUpdateView(APIView):
    """
    Internal endpoint to update order after successful payment.
    Allowed roles: customer, admin
    """

    authentication_classes = [JWTAuthentication]
    permission_classes = [MethodRolePermission]
    allowed_roles = {"PATCH": ["customer", "admin"]}

    def patch(self, request, order_id):
        try:
            user = request.user

            # 🔒 Ensure user is customer or admin
            if user.role not in ["customer", "admin"]:
                return Response({"error": "Access denied"}, status=status.HTTP_403_FORBIDDEN)

            # 🧾 Fetch order
            order = Order.objects(id=order_id).first()
            if not order:
                return Response({"error": "Order not found"}, status=status.HTTP_404_NOT_FOUND)

            # ✅ Allow customers to update only their own orders
            if user.role == "customer" and str(order.customer.id) != str(user.id):
                return Response({"error": "You can update only your own orders"}, status=status.HTTP_403_FORBIDDEN)

            # 🪙 Update payment status
            payment_status = request.data.get("payment_status")
            if not payment_status:
                return Response({"error": "Missing 'payment_status' field"}, status=status.HTTP_400_BAD_REQUEST)

            if payment_status.upper() == "PAID":
                order.status = "Approved"
            else:
                order.status = "Declined"

            order.updated_at = datetime.utcnow()
            order.save()

            return Response(
                {
                    "message": f"✅ Order {order.id} marked as {order.status}",
                    "order_id": str(order.id),
                    "status": order.status,
                },
                status=status.HTTP_200_OK,
            )

        except Exception as e:
            print("❌ Error in OrderPaymentUpdateView:", traceback.format_exc())
            return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



def generate_booking_id(order):
    """Generate Booking ID with format:
       <LOC3><CU2><VEH4><NN> """

    # ---------------- Location Code (3 letters) ----------------
    if order.pickup_point and order.pickup_point.name:
        loc = order.pickup_point.name[:3].upper()
    else:
        loc = "LOC"

    # ---------------- Customer (2 letters) ----------------
    first = order.customer.first_name[:2].upper() if order.customer else "CU"

    # ---------------- Vehicle (4 letters) ----------------
    if order.vehicle:
        model_name = getattr(order.vehicle, "model_name", None) or \
                     getattr(order.vehicle.model, "name", "")
        veh = model_name[:4].upper() if model_name else "VEH0"
    else:
        veh = "VEH0"

    # ---------------- Unique 2 digit code ----------------
    unique = f"{random.randint(0, 99):02d}"

    return f"{loc}{first}{veh}{unique}"


class AdminBookingListView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [MethodRolePermission]
    allowed_roles = {"GET": ["admin"]}

    def get(self, request):
        orders = Order.objects().order_by("-created_at")

        updated_orders = []

        for order in orders:
            # ------------------------------------------------------------------
            # 🔍 If booking ID missing → generate one & save silently
            # ------------------------------------------------------------------
            if not getattr(order, "booking_id", None):
                booking_id = generate_booking_id(order)
                order.booking_id = booking_id
                order.save()
            
            updated_orders.append(order)

        serializer = AdminBookingListSerializer(updated_orders, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)