import 'dart:io';

import 'package:flutter/material.dart';
import 'package:healthcare_user/common/settings.dart';
import 'package:google_maps_flutter_android/google_maps_flutter_android.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:location/location.dart' as locationmap;
import '../google_maps_place_picker_mb/src/models/pick_result.dart';
import '../google_maps_place_picker_mb/src/place_picker.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:healthcare_user/google_maps_place_picker_mb/google_maps_place_picker.dart';
import 'package:healthcare_user/keys.dart';



class UpdateMyLocation extends StatefulWidget {
  const UpdateMyLocation({Key? key}) : super(key: key);

  @override
  State<UpdateMyLocation> createState() => _UpdateMyLocationState();
}

class _UpdateMyLocationState extends State<UpdateMyLocation> {

  PickResult? selectedPlace;
  bool _mapsInitialized = false;
  final String _mapsRenderer = "latest";
  var kInitialPosition = const LatLng(15.462477, 78.717401);
  locationmap.Location location = locationmap.Location();
  final GoogleMapsFlutterPlatform mapsImplementation = GoogleMapsFlutterPlatform.instance;
  double lat=0;
  double lng=0;

  void initRenderer() {
    if (_mapsInitialized) return;
    if (mapsImplementation is GoogleMapsFlutterAndroid) {
      switch (_mapsRenderer) {
        case "legacy":
          (mapsImplementation as GoogleMapsFlutterAndroid)
              .initializeWithRenderer(AndroidMapRenderer.legacy);
          break;
        case "latest":
          (mapsImplementation as GoogleMapsFlutterAndroid)
              .initializeWithRenderer(AndroidMapRenderer.latest);
          break;
      }
    }
    setState(() {
      _mapsInitialized = true;
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppSettings.appBar('Update My Location'),
      body: Padding(
        padding: EdgeInsets.all(10),
        child: Column(
          children: [
            Row(
              children: [
                Text('Current Location :',style: labelTextStyle(),),
                SizedBox(width:MediaQuery.of(context).size.width * .02,),
                Expanded(child: Text(AppSettings.userAddress,style:valuesTextStyle(),))
              ],
            ),
            SizedBox(height:MediaQuery.of(context).size.height * .04,),
            Container(
                width:double.infinity,
                height: MediaQuery.of(context).size.height * .05,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    primary: buttonColors, // background
                    onPrimary: Colors.black, // foreground
                  ),
                  onPressed: () async{


                    //=============================================================================================

                    location.serviceEnabled().then((value) {
                      if (value) {
                        initRenderer();
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) {
                              return PlacePicker(
                                resizeToAvoidBottomInset: false,
                                hintText: "Find a place ...",
                                searchingText: "Please wait ...",
                                selectText: "Select place",
                                outsideOfPickAreaText: "Place not in area",
                                initialPosition: kInitialPosition,
                                useCurrentLocation: true,
                                selectInitialPosition: true,
                                usePinPointingSearch: true,
                                usePlaceDetailSearch: true,
                                zoomGesturesEnabled: true,
                                zoomControlsEnabled: true,
                                onMapCreated: (GoogleMapController controller) {},
                                onPlacePicked: (PickResult result) async {


                                  setState(() {
                                    selectedPlace = result;
                                    lat=selectedPlace!.geometry!.location.lat;
                                    lng=selectedPlace!.geometry!.location.lng;


                                    /*if(selectedPlace!.types!.length==1){
                                      userAddressCapturingController.text =
                                      selectedPlace!.formattedAddress!;
                                    }
                                    else{
                                      userAddressCapturingController.text =selectedPlace!.name!+', '+selectedPlace!.formattedAddress!;
                                    }*/
                                    Navigator.of(context).pop();
                                  });

                                  var payload = new Map<String, dynamic>();
                                  payload["latitude"] = lat;
                                  payload["longitude"] = lng;
                                  bool updateStatus = await AppSettings.updateLocation(payload);
                                  if(updateStatus){
                                    setState(() {
                                      if(selectedPlace!.types!.length==1){
                                        AppSettings.userAddress =
                                        selectedPlace!.formattedAddress!;
                                      }
                                      else{
                                        AppSettings.userAddress=selectedPlace!.name!+', '+selectedPlace!.formattedAddress!;
                                      }
                                    });

                                  }
                                  else{
                                    AppSettings.longFailedToast(
                                        "Failed to update location");
                                  }

                                },
                                onMapTypeChanged: (MapType mapType) {},
                                apiKey: Platform.isAndroid
                                    ? APIKeys.androidApiKey
                                    : APIKeys.iosApiKey,
                                forceAndroidLocationManager: true,
                              );
                            },
                          ),
                        );
                      } else {
                        showGeneralDialog(
                          context: context,
                          pageBuilder: (context, x, y) {
                            return Scaffold(
                              backgroundColor: Colors.grey.withOpacity(.5),
                              body: Center(
                                child: Container(
                                  width: double.infinity,
                                  height: 150,
                                  padding:
                                  const EdgeInsets.symmetric(horizontal: 20),
                                  child: Card(
                                    child: Padding(
                                      padding: const EdgeInsets.all(10.0),
                                      child: Column(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: [
                                          const Text(
                                            "Please enable the location",
                                            style: TextStyle(
                                              fontSize:18,
                                              fontWeight: FontWeight.w500,
                                            ),
                                          ),
                                          const SizedBox(
                                            height: 20,
                                          ),
                                          ElevatedButton(
                                            onPressed: () {
                                              Navigator.pop(context);
                                            },
                                            child: const Text("Cancel"),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            );
                          },
                        );
                      }
                    });

                  },
                  child: const Text('Update My Location'),
                )),



          ],
        ),
      )
    );

  }
}
