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 {
  const NearbyOpenLeads({super.key});

  @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: 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: 1.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,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
