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';
import '../../../controller/home/device_tier.dart';
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());
  final LocationController locationController = Get.find<LocationController>();

  @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,

                // ✅ حدود الكاميرا كما هي
                cameraTargetBounds: CameraTargetBounds(controller.boundsdata),

                // ✅ Zoom أهدأ للأجهزة الضعيفة
                minMaxZoomPreference: controller.lowPerf
                    ? const MinMaxZoomPreference(6, 17)
                    : const MinMaxZoomPreference(6, 18),

                onLongPress: (argument) {
                  MyDialog().getDialog('Are you want to go to this site'.tr, '',
                      () async {
                    controller.clearPolyline();
                    if (controller.dataCarsLocationByPassenger != null) {
                      await controller.getDirectionMap(
                        '${controller.passengerLocation.latitude},${controller.passengerLocation.longitude}',
                        '${argument.latitude},${argument.longitude}',
                      );
                      Get.back();
                      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: 11),
                        instantInit: true,
                        snackPosition: SnackPosition.TOP,
                        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),
                        icon: const Icon(Icons.error),
                        shouldIconPulse: true,
                        maxWidth: double.infinity,
                        margin: const EdgeInsets.all(16),
                        padding: const EdgeInsets.all(16),
                        borderRadius: 8,
                        borderColor: AppColor.redColor,
                        borderWidth: 2,
                        backgroundColor: AppColor.secondaryColor,
                        leftBarIndicatorColor: AppColor.redColor,
                        boxShadows: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.25),
                            blurRadius: 4,
                            spreadRadius: 2,
                            offset: const Offset(0, 4),
                          ),
                        ],
                        backgroundGradient: const LinearGradient(
                          colors: [AppColor.redColor, AppColor.accentColor],
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                        ),
                        isDismissible: true,
                        showProgressIndicator: false,
                        dismissDirection: DismissDirection.up,
                        snackStyle: SnackStyle.GROUNDED,
                        forwardAnimationCurve: Curves.easeInToLinear,
                        reverseAnimationCurve: Curves.easeInOut,
                        animationDuration: const Duration(milliseconds: 4000),
                        barBlur: 8,
                        overlayColor: AppColor.primaryColor.withOpacity(0.5),
                      );
                    }
                  });
                },

                onTap: (argument) {
                  controller.hidePlaces();
                },

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

                // ✅ ماركرز (احرص أن الأيقونات محجّمة ومخزّنة Cache في الكنترولر)
                markers: controller.markers.toSet(),

                // ✅ بوليغونز كما هي
                polygons: controller.polygons,

                // ✅ Polyline مُبسّطة للأجهزة الضعيفة (الكنترولر يجهّز مجموعة مبسطة عند lowPerf)
                polylines: controller.lowPerf
                    ? controller.polyLinesLight
                        .toSet() // <- استخدم مجموعة خفيفة
                    : controller.polyLines.toSet(),

                // ✅ دوائر خفيفة على الأجهزة الضعيفة
                // circles: {
                //   Circle(
                //     circleId: const CircleId('circle_id'),
                //     center: controller.passengerLocation,
                //     radius: controller.lowPerf ? 80 : 100,
                //     fillColor:
                //         Colors.blue.withOpacity(controller.lowPerf ? 0.2 : 0.3),
                //     strokeColor: Colors.blue,
                //     strokeWidth: controller.lowPerf ? 1 : 2,
                //   ),
                // },

                // ✅ الوضع الخفيف: liteMode + تعطيل الطبقات المكلفة + خريطة Normal
                mapType: controller.lowPerf
                    ? MapType.normal
                    : (controller.mapType
                        ? MapType.satellite
                        : MapType.terrain),

                myLocationButtonEnabled: false,

                // ⚠️ liteMode (Android فقط): فعّله على الأجهزة الضعيفة
                // liteModeEnabled: controller.lowPerf,
                liteModeEnabled: Platform.isAndroid ? isLowEnd() : false,
                trafficEnabled: controller.mapTrafficON && !isLowEnd(),
                buildingsEnabled: !isLowEnd(),
                // ✅ تقليل الكلفة الرسومية

                mapToolbarEnabled: false,
                rotateGesturesEnabled: isLowEnd() ? false : true,
                tiltGesturesEnabled: false, // تعطيل الميلان لتقليل الحمل

                // ✅ Throttle لحركة الكاميرا على الأجهزة الضعيفة
                onCameraMove: (position) {
                  if (controller.lowPerf) {
                    controller.onCameraMoveThrottled(position);
                  } else {
                    // منطقك الحالي
                    int waypointsLength =
                        Get.find<WayPointController>().wayPoints.length;
                    int index = controller.wayPointIndex;
                    if (waypointsLength > 0) {
                      controller.placesCoordinate[index] =
                          '${position.target.latitude},${position.target.longitude}';
                    }
                    if (controller.startLocationFromMap == true) {
                      controller.newStartPointLocation = position.target;
                    } else if (controller.passengerStartLocationFromMap ==
                        true) {
                      controller.newStartPointLocation = position.target;
                    }
                    controller.newMyLocation = position.target;
                  }
                },

                myLocationEnabled: true,
              ),
            ),
    );
  }
}
