import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:rasadyar_core/core.dart';
import 'package:rasadyar_core/data/services/network_status.dart';
import 'package:rasadyar_livestock/presentation/routes/app_pages.dart';

import 'logic.dart';

class MapWidget extends GetView<MapWidgetLogic> {
  const MapWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Stack(
        fit: StackFit.expand,
        children: [


          ObxValue((errorType) {
            if (errorType.isNotEmpty) {
              if (errorType.contains(ErrorLocationType.serviceDisabled)) {
                Future.microtask(() {
                  Get.defaultDialog(
                    title: 'خطا',
                    content: const Text('سرویس مکان‌یابی غیرفعال است'),
                    cancel: ROutlinedElevated(
                      text: 'بررسی مجدد',
                      width: 120,
                      textStyle: AppFonts.yekan16,
                      onPressed: () async {
                        var service = await controller.locationServiceEnabled();
                        if (service) {
                          controller.errorLocationType.remove(ErrorLocationType.serviceDisabled);
                          Get.back();
                        }
                        // Don't call Get.back() if service is still disabled
                      },
                    ),
                    confirm: RElevated(
                      text: 'روشن کردن',
                      textStyle: AppFonts.yekan16,
                      width: 120,
                      onPressed: () async {
                        var res = await Geolocator.openLocationSettings();
                        if (res) {
                          var service = await controller.locationServiceEnabled();
                          if (service) {
                            controller.errorLocationType.remove(ErrorLocationType.serviceDisabled);
                            Get.back();
                          }
                        }
                      },
                    ),
                    contentPadding: EdgeInsets.all(8),
                    onWillPop: () async {
                      return controller.errorLocationType.isEmpty;
                    },
                    barrierDismissible: false,
                  );
                });
              } else {
                Future.microtask(() {
                  Get.defaultDialog(
                    title: 'خطا',
                    content: const Text(' دسترسی به سرویس مکان‌یابی غیرفعال است'),
                    cancel: ROutlinedElevated(
                      text: 'بررسی مجدد',
                      width: 120,
                      textStyle: AppFonts.yekan16,
                      onPressed: () async {
                        await controller.checkPermission();
                      },
                    ),
                    confirm: RElevated(
                      text: 'اجازه دادن',
                      textStyle: AppFonts.yekan16,
                      width: 120,
                      onPressed: () async {
                        var res = await controller.checkPermission(request: true);
                        if (res) {
                          controller.errorLocationType.remove(ErrorLocationType.permissionDenied);
                          Get.back();
                        }
                      },
                    ),

                    contentPadding: EdgeInsets.all(8),
                    onWillPop: () async {
                      return controller.errorLocationType.isEmpty;
                    },
                    barrierDismissible: false,
                  );
                });
              }
            }
            return const SizedBox.shrink();
          }, controller.errorLocationType),

          ObxValue((currentLocation) {
            return FlutterMap(
              mapController: controller.animatedMapController.mapController,
              options: MapOptions(
                initialCenter: currentLocation.value,
                interactionOptions: const InteractionOptions(
                  flags: InteractiveFlag.all & ~InteractiveFlag.rotate,
                ),
                initialZoom: 15,
                onPositionChanged: (camera, hasGesture) {
                  controller.currentZoom.value = camera.zoom;
                  /* controller.debouncedUpdateVisibleMarkers(
                    center: camera.center,
                    zoom: camera.zoom,
                  );*/
                },
              ),

              children: [
                TileLayer(
                  urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
                  userAgentPackageName: 'ir.mnpc.rasadyar',
                 // tileProvider: controller.tileProvider,
                ),

                ObxValue((markers) {
                  return MarkerClusterLayerWidget(
                    options: MarkerClusterLayerOptions(
                      maxClusterRadius: 80,
                      size: const Size(40, 40),
                      alignment: Alignment.center,
                      padding: const EdgeInsets.all(50),
                      maxZoom: 18,
                      markers: buildMarkers(markers),
                      builder: (context, clusterMarkers) {
                        return Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20),
                            color: Colors.blue,
                          ),
                          child: Center(
                            child: Text(
                              clusterMarkers.length.toString(),
                              style: const TextStyle(color: Colors.white),
                            ),
                          ),
                        );
                      },
                    ),
                  );
                }, controller.markerLocations),
              ],
            );
          }, controller.currentLocation),

          Positioned(
            top: 15,
            left: 20,
            child: ObxValue((status) {
              return Text("Connection: ${status.value}", style: TextStyle(fontSize: 20));
            }, NetworkStatus().isConnected),
          ),

          // Uncomment the following lines to enable the search widget
          /* Positioned(
              top: 10,
              left: 20,
              right: 20,
              child: ObxValue((data) {
                if (data.value) {
                  return SearchWidget(
                    onSearchChanged: (data) {
                      controller.baseLogic.searchValue.value = data;
                    },
                  );
                } else {
                  return SizedBox.shrink();
                }
              }, controller.baseLogic.isSearchSelected),
            ),*/
        ],
      ),
    );
  }

  List<Marker> buildMarkers(RxList<LatLng> latLng) =>
      latLng
          .map(
            (element) =>
            Marker(
              point: element,
              child: IconButton(
                onPressed: () {
                  Get.bottomSheet(
                    detailsBottomSheet(),
                    isScrollControlled: true,
                    isDismissible: true,
                    ignoreSafeArea: false,
                  );
                },
                icon: Icon(CupertinoIcons.location_solid, color: AppColor.error),
              ),
            ),
      )
          .toList();

  Widget detailsBottomSheet() {
    return BaseBottomSheet(
      height: 250.h,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        spacing: 20,
        children: [
          Text('مشخصات محل', style: AppFonts.yekan16Bold),
          // Add more details here
          RElevated(
            text: 'ایجاد بازرسی',
            width: Get.width,
            height: 40.h,
            onPressed: () {
              Get.toNamed(LiveStockRoutes.requestTagging);
            },
          ),
        ],
      ),
    );
  }
}
