import 'dart:io';

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/commonWidgets.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:interactive_slider/interactive_slider.dart';
import 'package:provider/provider.dart';

import '../../Utils/dropdownTheme.dart';

class Nearbygenerators extends StatefulWidget {
  const Nearbygenerators({super.key});

  @override
  State<Nearbygenerators> createState() => _NearbygeneratorsState();
}

class _NearbygeneratorsState extends State<Nearbygenerators> {
  Dropdowntheme ddtheme = Dropdowntheme();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      var provider = Provider.of<Nearbygeneratorsprovider>(context,listen: false);
      provider.getLocationPermission(context);
    },);
  }

  // Future infoDialogue(BuildContext context) async {
  //
  //   return await showDialog(
  //     context: context,
  //     builder:
  //         (context) => Consumer<Nearbygeneratorsprovider>(
  //       builder: (context,provider,child) {
  //         return StatefulBuilder(
  //           builder:
  //               (context, setState) =>
  //               AlertDialog(
  //                 shape: RoundedRectangleBorder(
  //                   borderRadius: BorderRadius.circular(10.0),
  //                 ),
  //                 title: Column(
  //                   children: [
  //                     Row(
  //                       children: [
  //                         Expanded(
  //                           child: Align(
  //                             alignment: Alignment.topLeft,
  //                             child: Text(
  //                               'Filter',
  //                               style: TextStyle(
  //                                 color: Colors.black,
  //                                 fontWeight: FontWeight.w500,
  //                               ),
  //                             ),
  //                           ),
  //                         ),
  //                         InkWell(
  //                           child: SvgPicture.asset("assets/svg/ic_close.svg",height: 18,width: 18,),
  //                           onTap: () {
  //                             setState(() {
  //                               provider.currentValue = 0.0;
  //                               provider.selectedItem = "Active";
  //                             });
  //                             Navigator.pop(context);
  //                           },
  //                         ),
  //                       ],
  //                     ),
  //                     Divider(
  //                       color: Colors.grey,
  //                       thickness: 1.0,
  //                       height: 0.0,
  //                     ),
  //                   ],
  //                 ),
  //
  //                 content: Container(
  //                   height: 230,
  //                   child: Column(
  //                     children: [
  //                       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,
  //                             ),
  //                           ),
  //                         ],
  //                       ),
  //                       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.LoadNearbyGeneratorsAPI(context);
  //                           }, Duration(milliseconds: 500));
  //                         },
  //                       ),
  //                       Align(
  //                         alignment: Alignment.centerLeft,
  //                         child: Text(
  //                           'Status',
  //
  //                           style: TextStyle(
  //                             fontSize: 18.0,
  //                             fontWeight: FontWeight.w500,
  //                           ),
  //                         ),
  //                       ),
  //                       Container(
  //                         child: Row(
  //                           children: [
  //                             Expanded(
  //                               child: DropdownButton<String>(
  //                                 value: provider.selectedItem,
  //                                 items:
  //                                 <String>[
  //                                   'Active',
  //                                   'Inactive',
  //                                   'Suspense',
  //                                 ].map<DropdownMenuItem<String>>((String value,) {
  //                                   return DropdownMenuItem<String>(
  //                                     value: value,
  //                                     child: Text(value),
  //                                   );
  //                                 }).toList(),
  //                                 onChanged: (String? newValue) {
  //                                   setState(() {
  //                                     provider.selectedItem = newValue!;
  //                                   });
  //                                 },
  //                                 icon:  SvgPicture.asset("assets/svg/arrow_dropdown.svg",height: 25,width: 20,),
  //                                 iconSize: 12,
  //                                 iconEnabledColor:
  //                                 Colors
  //                                     .black, // Remove the default dropdown icon
  //                               ),
  //                             ),
  //                           ],
  //                         ),
  //                       ),
  //                       SizedBox(height: 30.0),
  //                       Container(
  //                         child: InkWell(
  //                           onTap: () {
  //                             provider.debounce(() {
  //                               provider.LoadNearbyGeneratorsAPI(context);
  //                               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(10.0),
  //                             ),
  //                             child: Text(
  //                               "Search",
  //                               textAlign: TextAlign.center,
  //                               style: TextStyle(
  //                                 fontFamily: 'Nexa',
  //                                 fontWeight: FontWeight.w700,
  //                               ),
  //                             ),
  //                           ),
  //                         ),
  //                       ),
  //                     ],
  //                   ),
  //                 ),
  //               ),
  //         );
  //       }),
  //     barrierDismissible: true,
  //   ) ??
  //       false;
  // }

  @override
  Widget build(BuildContext context) {
    debugPrint("Nearbygenerators widget rebuilt");
    return Consumer<Nearbygeneratorsprovider>(builder: (context, provider, child) {
      var sendWidget = GestureDetector(
          onTap: () {
            _showFilterBottomSheet(context);
          },
          child: SvgPicture.asset("assets/svg/filter_ic.svg",height: 25,));

      return WillPopScope(
        onWillPop: () => onBackPressed(context),
        child: SafeArea(
          top: false,
          bottom: Platform.isIOS?false:true,
          child: Scaffold(
            resizeToAvoidBottomInset: true,
            appBar: appbar2(context, "Nearby Generators",provider.resetAll,sendWidget),
            backgroundColor: AppColors.scaffold_bg_color,
            body: 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(
                            scrollGesturesEnabled: true,
                            rotateGesturesEnabled: true,

                            myLocationEnabled: true,
                            zoomGesturesEnabled: true,
                            zoomControlsEnabled: true,
                            gestureRecognizers: {
                              Factory<OneSequenceGestureRecognizer>(() => EagerGestureRecognizer()),
                              Factory<PanGestureRecognizer>(() => PanGestureRecognizer()),
                              Factory<ScaleGestureRecognizer>(() => ScaleGestureRecognizer()), // Prioritize pinch-to-zoom
                            },
                            initialCameraPosition: CameraPosition(
                              target: 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<Nearbygeneratorsprovider>(
                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),
                              Align(
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  'Status',

                                  style: TextStyle(
                                    fontSize: 18.0,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                              DropdownButtonHideUnderline(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: DropdownButton2<String>(
                                        isExpanded: true,
                                        hint: const Row(
                                          children: [
                                            Expanded(
                                              child: Text(
                                                'Select Complaint Status',
                                                style: TextStyle(
                                                  fontSize: 14,
                                                ),
                                                overflow: TextOverflow.ellipsis,
                                              ),
                                            ),
                                          ],
                                        ),
                                        items: <String>[
                                          'Active',
                                          'Inactive',
                                          'Suspense',
                                        ].map(
                                                (value) =>
                                                DropdownMenuItem<String>(
                                                  value: value,
                                                  child: Text(
                                                    value ?? '',
                                                    style: const TextStyle(
                                                      fontSize: 14,
                                                    ),
                                                    overflow: TextOverflow.ellipsis,
                                                  ),
                                                )).toList(),
                                        value: provider.selectedItem,
                                        onChanged: (String? newValue) {
                                          setState(() {
                                            provider.selectedItem = newValue!;
                                          });
                                        },
                                        buttonStyleData: ddtheme.buttonStyleData,
                                        iconStyleData: ddtheme.iconStyleData,
                                        menuItemStyleData: ddtheme.menuItemStyleData,
                                        dropdownStyleData: ddtheme.dropdownStyleData,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(height: 10,),
                              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(
                                padding: EdgeInsets.symmetric(horizontal: 4,vertical: 0),
                                min: 1.0,
                                max: 50.0,
                                enabled: true,

                                // backgroundColor: AppColors.app_blue,
                                foregroundColor: AppColors.app_blue,
                                  segmentDividerColor:Color(0xFFF6F6F8),
                                onChanged: (value) {
                                  provider.currentValue = value;
                                  // provider.debounce(() {
                                  //   provider.LoadNearbyGeneratorsAPI(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.LoadNearbyGeneratorsAPI(context);
                              //     }, Duration(milliseconds: 200));
                              //   },
                              // ),
                              SizedBox(height: 30.0),
                              Container(
                                child: InkWell(
                                  onTap: () {
                                    provider.debounce(() {
                                      provider.LoadNearbyGeneratorsAPI(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
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  );
                }
              ),
            );
          },
        );
      },
    );
  }
}
