import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:Intaleq/controller/home/points_for_rider_controller.dart';

import '../../../constant/colors.dart';
import '../../../constant/style.dart';
// import '../../../controller/functions/location_controller.dart'; // Un-comment if needed
// import '../../../controller/home/device_tier.dart'; // Removed to rely on Controller logic
import '../../../controller/home/map_passenger_controller.dart';
import '../../widgets/mycircular.dart';
import '../../widgets/mydialoug.dart';

class GoogleMapPassengerWidget extends StatelessWidget {
  GoogleMapPassengerWidget({super.key});

  final WayPointController wayPointController = Get.put(WayPointController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MapPassengerController>(
      builder: (controller) => controller.isLoading
          ? const MyCircularProgressIndicator()
          : Positioned(
              bottom: Get.height * .2,
              top: 0,
              left: 0,
              right: 0,
              child: GoogleMap(
                onMapCreated: controller.onMapCreated,

                // ✅ Camera Bounds
                cameraTargetBounds: CameraTargetBounds(controller.boundsdata),

                // ✅ Performance: Smoother zoom limits for low-end devices
                minMaxZoomPreference: controller.lowPerf
                    ? const MinMaxZoomPreference(6, 17)
                    : const MinMaxZoomPreference(6, 18),

                // ✅ Destination Selection on Long Press
                onLongPress: (LatLng argument) {
                  MyDialog().getDialog('Are you want to go to this site'.tr, '',
                      () async {
                    controller.clearPolyline();
                    // Ensure we have car data available before routing
                    // if (controller.dataCarsLocationByPassenger != null) {
// i use this check if needed
                    if (controller.carsLocationByPassenger.isNotEmpty) {
                      await controller.getDirectionMap(
                        '${controller.passengerLocation.latitude},${controller.passengerLocation.longitude}',
                        '${argument.latitude},${argument.longitude}',
                      );
                      Get.back(); // Close Dialog
                      await controller.bottomSheet();
                      controller.showBottomSheet1();
                    } else {
                      Get.back();
                      Get.snackbar(
                        'We Are Sorry That we dont have cars in your Location!'
                            .tr,
                        '',
                        colorText: AppColor.redColor,
                        duration: const Duration(seconds: 5),
                        backgroundColor: AppColor.secondaryColor,
                        icon: const Icon(Icons.error, color: AppColor.redColor),
                        titleText: Text('Error'.tr,
                            style: const TextStyle(color: AppColor.redColor)),
                        messageText: Text(
                            'We Are Sorry That we dont have cars in your Location!'
                                .tr,
                            style: AppStyle.title),
                      );
                    }
                  });
                },

                // ✅ Hide UI elements on tap
                onTap: (argument) {
                  controller.hidePlaces();
                },

                initialCameraPosition: CameraPosition(
                  target: controller.passengerLocation,
                  zoom: controller.lowPerf ? 14.5 : 15,
                ),

                // ✅ Markers
                markers: controller.markers.toSet(),

                // ✅ Polygons (e.g., University/Country borders)
                polygons: controller.polygons,

                // ✅ Polylines: Switch to lighter version if lowPerf is detected
                polylines: controller.lowPerf
                    ? controller.polyLinesLight.toSet()
                    : controller.polyLines.toSet(),

                // ✅ Map Type: Switch to Normal map on low-end devices to save RAM
                mapType: controller.lowPerf
                    ? MapType.normal
                    : (controller.mapType
                        ? MapType.satellite
                        : MapType
                            .normal), // Changed terrain default to normal for better performance

                // ✅ UI Settings for Performance
                myLocationButtonEnabled: false,
                mapToolbarEnabled: false,
                tiltGesturesEnabled:
                    false, // Disable tilt to save GPU resources

                // Lite Mode (Static image) only on very low-end Androids if needed,
                // but usually handled by lowPerf logic in mapType/Traffic
                liteModeEnabled: Platform.isAndroid && controller.lowPerf,

                trafficEnabled: controller.mapTrafficON && !controller.lowPerf,
                buildingsEnabled: !controller.lowPerf,
                rotateGesturesEnabled:
                    !controller.lowPerf, // Disable rotation on low-end

                // ✅ Camera Movement Logic
                onCameraMove: (CameraPosition position) {
                  // 1. Always update current view target (for pickers)
                  controller.newMyLocation = position.target;

                  // 2. Handle Drag-to-Select for specific states
                  if (controller.startLocationFromMap == true) {
                    controller.newStartPointLocation = position.target;
                  } else if (controller.passengerStartLocationFromMap == true) {
                    controller.newStartPointLocation = position.target;
                  }

                  // 3. Handle Waypoints Dragging
                  int waypointsLength =
                      Get.find<WayPointController>().wayPoints.length;
                  if (waypointsLength > 0 &&
                      controller.wayPointIndex >= 0 &&
                      controller.wayPointIndex <
                          controller.placesCoordinate.length) {
                    controller.placesCoordinate[controller.wayPointIndex] =
                        '${position.target.latitude},${position.target.longitude}';
                  }

                  // 4. Throttle heavy calculations (Reverse Geocoding / API calls)
                  if (controller.lowPerf) {
                    controller.onCameraMoveThrottled(position);
                  }
                },

                myLocationEnabled: false,
              ),
            ),
    );
  }
}
