// import 'dart:io';
//
// import 'package:connectivity_plus/connectivity_plus.dart';
// import 'package:dropdown_button2/dropdown_button2.dart';
// import 'package:flutter/foundation.dart';
// import 'package:flutter/gestures.dart';
// import 'package:flutter/material.dart';
// import 'package:flutter_svg/svg.dart';
// import 'package:generp/Notifiers/NearByGeneratorsProvider.dart';
// import 'package:generp/Utils/app_colors.dart';
// import 'package:generp/Utils/commonServices.dart';
// import 'package:generp/Utils/commonWidgets.dart';
// import 'package:google_maps_flutter/google_maps_flutter.dart';
// import 'package:interactive_slider/interactive_slider.dart';
// import 'package:provider/provider.dart';
//
// import '../../Notifiers/crmProvider/crmNearbyOpenLeadsProvider.dart';
// import '../../Utils/dropdownTheme.dart';
//
// class NearbyOpenLeads extends StatefulWidget {
//   final latitude;
//   final longitude;
//   const NearbyOpenLeads({super.key, this.latitude, this.longitude});
//
//   @override
//   State<NearbyOpenLeads> createState() => _NearbyOpenLeadsState();
// }
//
// class _NearbyOpenLeadsState extends State<NearbyOpenLeads> {
//   Map _source = {ConnectivityResult.mobile: true};
//   final MyConnectivity _connectivity = MyConnectivity.instance;
//
//   Dropdowntheme ddtheme = Dropdowntheme();
//   @override
//   void initState() {
//     // TODO: implement initState
//     super.initState();
//     _connectivity.initialise();
//     _connectivity.myStream.listen((source) {
//       setState(() => _source = source);
//     });
//     WidgetsBinding.instance.addPostFrameCallback((_) {
//       final provider = Provider.of<crmNearbyOpenLeadsProvider>(
//         context,
//         listen: false,
//       );
//       provider.getLocationPermission(context);
//     });
//   }
//
//   @override
//   void dispose() {
//     // TODO: implement dispose
//     super.dispose();
//     _connectivity.disposeStream();
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     switch (_source.keys.toList()[0]) {
//       case ConnectivityResult.mobile:
//         connection = 'Online';
//         break;
//       case ConnectivityResult.wifi:
//         connection = 'Online';
//         break;
//       case ConnectivityResult.none:
//       default:
//         connection = 'Offline';
//     }
//     return (connection == "Online")
//         ? Platform.isAndroid
//             ? WillPopScope(
//               onWillPop: () => onBackPressed(context),
//               child: SafeArea(
//                 top: false,
//                 bottom: true,
//                 child: _scaffold(context),
//               ),
//             )
//             : _scaffold(context)
//         : NoNetwork(context);
//   }
//
//   Widget _scaffold(BuildContext context) {
//     debugPrint("Nearbygenerators widget rebuilt");
//     return Consumer<crmNearbyOpenLeadsProvider>(
//       builder: (context, provider, child) {
//         var sendWidget = GestureDetector(
//           onTap: () {
//             _showFilterBottomSheet(context);
//           },
//           child: SvgPicture.asset("assets/svg/filter_ic.svg", height: 25),
//         );
//
//         return Scaffold(
//           resizeToAvoidBottomInset: true,
//           appBar: appbar2(
//             context,
//             "Nearby Leads (Open)",
//             provider.resetAll,
//             sendWidget,
//           ),
//           backgroundColor: AppColors.scaffold_bg_color,
//           body: SafeArea(
//             child: Container(
//               child: SingleChildScrollView(
//                 child: Column(
//                   children: [
//                     ClipRRect(
//                       // Apply border radius using ClipRRect
//                       borderRadius: BorderRadius.only(
//                         topLeft: Radius.circular(30.0),
//                         topRight: Radius.circular(30.0),
//                       ),
//                       // padding: EdgeInsets.fromLTRB(10, 20, 10, 20),
//                       child: Container(
//                         height: MediaQuery.of(context).size.height,
//                         child: Stack(
//                           children: [
//                             GoogleMap(
//                               myLocationEnabled: true,
//                               zoomGesturesEnabled: true,
//                               zoomControlsEnabled: true,
//                               gestureRecognizers: {
//
//                                 Factory<OneSequenceGestureRecognizer>(
//                                   () => EagerGestureRecognizer(),
//                                 ),
//                                 Factory<PanGestureRecognizer>(
//                                   () => PanGestureRecognizer(),
//                                 ),
//                                 Factory<ScaleGestureRecognizer>(
//                                   () => ScaleGestureRecognizer(),
//                                 ), // Prioritize pinch-to-zoom
//                               },
//                               initialCameraPosition: CameraPosition(
//                                 target: widget.latitude!=null||widget.longitude!=null?
//                                 LatLng(widget.latitude,widget.longitude):
//                                 provider.startLocation,
//                                 zoom: 14.0,
//                               ),
//                               markers: provider.markers.toSet(),
//                               mapType: MapType.normal,
//                               onMapCreated: (controller) {
//                                 setState(() {
//                                   provider.mapController = controller;
//                                 });
//                               },
//                               onCameraMove: (position) {
//                                 provider.onCameraMove(context, position);
//                               },
//                             ),
//                           ],
//                         ),
//                       ),
//                     ),
//                   ],
//                 ),
//               ),
//             ),
//           ),
//         );
//       },
//     );
//   }
//
//   Future<void> _showFilterBottomSheet(BuildContext context) {
//     return showModalBottomSheet(
//       useSafeArea: true,
//       isDismissible: true,
//       isScrollControlled: true,
//       showDragHandle: true,
//
//       enableDrag: true,
//       context: context,
//       builder: (context) {
//         return StatefulBuilder(
//           builder: (context, setState) {
//             return SafeArea(
//               child: Consumer<crmNearbyOpenLeadsProvider>(
//                 builder: (context, provider, child) {
//                   return Container(
//                     margin: EdgeInsets.only(
//                       bottom: 15,
//                       left: 15,
//                       right: 15,
//                       top: 15,
//                     ),
//                     padding: EdgeInsets.only(
//                       bottom: MediaQuery.of(context).viewInsets.bottom,
//                     ),
//
//                     child: SingleChildScrollView(
//                       child: Column(
//                         mainAxisSize: MainAxisSize.min,
//                         children: [
//                           Column(
//                             crossAxisAlignment: CrossAxisAlignment.start,
//                             children: [
//                               Text(
//                                 "Filter",
//                                 style: TextStyle(
//                                   color: AppColors.app_blue,
//                                   fontFamily: "JakartaSemiBold",
//                                   fontSize: 16,
//                                 ),
//                               ),
//                               SizedBox(height: 15),
//
//                               Row(
//                                 children: [
//                                   Text(
//                                     "Radius",
//                                     style: TextStyle(
//                                       fontSize: 18.0,
//                                       fontWeight: FontWeight.w500,
//                                     ),
//                                   ),
//                                   Spacer(),
//                                   Text(
//                                     '${provider.currentValue.toStringAsFixed(2)} KM',
//                                     style: TextStyle(
//                                       fontSize: 18.0,
//                                       fontWeight: FontWeight.w500,
//                                     ),
//                                   ),
//                                 ],
//                               ),
//                               InteractiveSlider(
//                                 min: 0.0,
//                                 max: 50.0,
//                                 padding: EdgeInsets.symmetric(
//                                   horizontal: 0,
//                                   vertical: 0,
//                                 ),
//                                 iconSize: 0.0,
//                                 enabled: true,
//                                 // backgroundColor: AppColors.app_blue,
//                                 foregroundColor: AppColors.app_blue,
//                                 segmentDividerColor: Color(0xFFF6F6F8),
//                                 onChanged: (value) {
//                                   provider.currentValue = value;
//                                   // provider.debounce(() {
//                                   //   provider.LoadNearbyOpenLeadsAPI(context);
//                                   // }, Duration(milliseconds: 200));
//                                 },
//                               ),
//                               // Slider(
//                               //   value: provider.currentValue,
//                               //   max: 100,
//                               //   divisions: 100,
//                               //
//                               //   label: provider.currentValue.toStringAsFixed(2),
//                               //   inactiveColor: Color(0xFFD7D7D7),
//                               //   activeColor: AppColors.cyan_blue,
//                               //   onChanged: (value) {
//                               //     provider.currentValue = value;
//                               //     provider.debounce(() {
//                               //       provider.LoadNearbyOpenLeadsAPI(context);
//                               //     }, Duration(milliseconds: 200));
//                               //   },
//                               // ),
//                               SizedBox(height: 30.0),
//                               Container(
//                                 child: InkWell(
//                                   onTap: () {
//                                     provider.debounce(() {
//                                       provider.LoadNearbyOpenLeadsAPI(
//                                         context,
//                                         provider.currentValue,
//                                       );
//                                       Navigator.pop(context);
//                                     }, Duration(milliseconds: 500));
//                                   },
//                                   child: Container(
//                                     alignment: Alignment.center,
//                                     height: 45,
//                                     margin: EdgeInsets.only(
//                                       left: 15.0,
//                                       right: 15.0,
//                                     ),
//                                     decoration: BoxDecoration(
//                                       borderRadius: BorderRadius.circular(14.0),
//                                       color: AppColors.app_blue,
//                                     ),
//                                     child: Text(
//                                       "Search",
//                                       textAlign: TextAlign.center,
//                                       style: TextStyle(
//                                         fontFamily: 'JakartaMedium',
//                                         color: Colors.white,
//                                       ),
//                                     ),
//                                   ),
//                                 ),
//                               ),
//                             ],
//                           ),
//                         ],
//                       ),
//                     ),
//                   );
//                 },
//               ),
//             );
//           },
//         );
//       },
//     );
//   }
// }

import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/NearByGeneratorsProvider.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:interactive_slider/interactive_slider.dart';
import 'package:provider/provider.dart';

import '../../Notifiers/crmProvider/crmNearbyOpenLeadsProvider.dart';
import '../../Utils/dropdownTheme.dart';

class NearbyOpenLeads extends StatefulWidget {
  final double? latitude;
  final double? longitude;
  const NearbyOpenLeads({super.key, this.latitude, this.longitude});

  @override
  State<NearbyOpenLeads> createState() => _NearbyOpenLeadsState();
}

class _NearbyOpenLeadsState extends State<NearbyOpenLeads> {
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

  Dropdowntheme ddtheme = Dropdowntheme();

  @override
  void initState() {
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final provider = Provider.of<crmNearbyOpenLeadsProvider>(
        context,
        listen: false,
      );
      provider.getLocationPermission(context);
    });
  }

  @override
  void dispose() {
    _connectivity.disposeStream();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    String connection;
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.mobile:
        connection = 'Online';
        break;
      case ConnectivityResult.wifi:
        connection = 'Online';
        break;
      case ConnectivityResult.none:
      default:
        connection = 'Offline';
    }
    return (connection == "Online")
        ? Platform.isAndroid
        ? WillPopScope(
      onWillPop: () => onBackPressed(context),
      child: SafeArea(
        top: false,
        bottom: true,
        child: _buildScreen(context),
      ),
    )
        : _buildScreen(context)
        : NoNetwork(context);
  }

  Widget _buildScreen(BuildContext context) {
    return Consumer<crmNearbyOpenLeadsProvider>(
      builder: (context, provider, child) {

        // {
        //   return Scaffold(
        //     backgroundColor: AppColors.scaffold_bg_color,
        //     body: Center(
        //       child: Column(
        //         mainAxisAlignment: MainAxisAlignment.center,
        //         children: [
        //           CircularProgressIndicator(color: AppColors.app_blue),
        //           SizedBox(height: 16),
        //           Text(
        //             'Loading nearby leads...',
        //             style: TextStyle(fontSize: 16, color: AppColors.app_blue),
        //           ),
        //         ],
        //       ),
        //     ),
        //   );
        // }

        // Full UI when markers are loaded or filter is applied
        var sendWidget = GestureDetector(
          onTap: () {
            _showFilterBottomSheet(context);
          },
          child: SvgPicture.asset("assets/svg/filter_ic.svg", height: 25),
        );

        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: appbar2(
            context,
            "Nearby Leads (Open)",
            provider.resetAll,
            sendWidget,
          ),
          backgroundColor: AppColors.scaffold_bg_color,
          body: SafeArea(
            child: Stack(
              children: [
                Container(
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(30.0),
                            topRight: Radius.circular(30.0),
                          ),
                          child: Container(
                            height: MediaQuery.of(context).size.height,
                            child: Stack(
                              children: [
                                GoogleMap(
                                  myLocationEnabled: true,
                                  zoomGesturesEnabled: true,
                                  zoomControlsEnabled: true,
                                  gestureRecognizers: {
                                    Factory<OneSequenceGestureRecognizer>(
                                          () => EagerGestureRecognizer(),
                                    ),
                                    Factory<PanGestureRecognizer>(
                                          () => PanGestureRecognizer(),
                                    ),
                                    Factory<ScaleGestureRecognizer>(
                                          () => ScaleGestureRecognizer(),
                                    ),
                                  },
                                  initialCameraPosition: CameraPosition(
                                    target: widget.latitude != null && widget.longitude != null
                                        ? LatLng(widget.latitude!, widget.longitude!)
                                        : provider.startLocation,
                                    zoom: 14.0,
                                  ),
                                  markers: provider.markers.toSet(),
                                  mapType: MapType.normal,
                                  onMapCreated: (controller) {
                                    provider.mapController = controller;
                                  },
                                  onCameraMove: (position) {
                                    provider.onCameraMove(context, position);
                                  },
                                  onTap: (position) {
                                    provider.mapController?.hideMarkerInfoWindow(
                                      provider.markers.isNotEmpty
                                          ? provider.markers.first.markerId
                                          : MarkerId(''),
                                    );
                                  },
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                if (provider.isLoading || (provider.markers.isEmpty))...[
                   Container(
                     width: MediaQuery.of(context).size.width,
                     height: MediaQuery.of(context).size.height,
                     color: Colors.white38,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        CircularProgressIndicator(color: AppColors.app_blue),
                        SizedBox(height: 16),
                        Text(
                          'Loading nearby leads...',
                          style: TextStyle(fontSize: 16, color: AppColors.app_blue),
                        ),
                      ],
                    ),
                  )
                ]
              ],
            ),
          ),
        );
      },
    );
  }

  Future<void> _showFilterBottomSheet(BuildContext context) {
    return showModalBottomSheet(
      useSafeArea: true,
      isDismissible: true,
      isScrollControlled: true,
      showDragHandle: true,
      enableDrag: true,
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return SafeArea(
              child: Consumer<crmNearbyOpenLeadsProvider>(
                builder: (context, provider, child) {
                  return Container(
                    margin: EdgeInsets.only(
                      bottom: 15,
                      left: 15,
                      right: 15,
                      top: 15,
                    ),
                    padding: EdgeInsets.only(
                      bottom: MediaQuery.of(context).viewInsets.bottom,
                    ),
                    child: SingleChildScrollView(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                "Filter",
                                style: TextStyle(
                                  color: AppColors.app_blue,
                                  fontFamily: "JakartaSemiBold",
                                  fontSize: 16,
                                ),
                              ),
                              SizedBox(height: 15),
                              Row(
                                children: [
                                  Text(
                                    "Radius",
                                    style: TextStyle(
                                      fontSize: 18.0,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                  Spacer(),
                                  Text(
                                    '${provider.currentValue.toStringAsFixed(2)} KM',
                                    style: TextStyle(
                                      fontSize: 18.0,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ],
                              ),
                              InteractiveSlider(
                                min: 0.0,
                                max: 50.0,
                                padding: EdgeInsets.symmetric(
                                  horizontal: 0,
                                  vertical: 0,
                                ),
                                iconSize: 0.0,
                                initialProgress: provider.currentValue/50,
                                enabled: true,
                                foregroundColor: AppColors.app_blue,
                                segmentDividerColor: Color(0xFFF6F6F8),
                                onChanged: (value) {
                                  setState(() {
                                    provider.currentValue = value;
                                  });
                                },
                              ),
                              SizedBox(height: 30.0),
                              Container(
                                child: InkWell(
                                  onTap: () {
                                    provider.applyFilter(context, provider.currentValue);
                                    Navigator.pop(context);
                                  },
                                  child: Container(
                                    alignment: Alignment.center,
                                    height: 45,
                                    margin: EdgeInsets.only(
                                      left: 15.0,
                                      right: 15.0,
                                    ),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(14.0),
                                      color: AppColors.app_blue,
                                    ),
                                    child: Text(
                                      "Search",
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                        fontFamily: 'JakartaMedium',
                                        color: Colors.white,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}