import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../Globalwidgets/Googleplaces/Googleplaces.dart';
import '../../../../Helper/location_service.dart';



class DropGoogleMapsController extends GetxController{


  String? toAddress;



  String? toLatitude;
  String? toLongitude;


  String? country;
  String? dialCode;
  String? countryCode;
  String? googleApiKey;
  String? initialCountry;


  bool? isSuburbTrue = false;
  bool? isCity = false;

  List autoCompleteResult = [];


  List<LatLng> latlng = [];

  var address;

  static LatLng? center;
  static double? currentLatitude;
  static double? currentLongitude;

  Set<Marker>markers = {};
  Set<Polyline>polyline={};


  //Autocomplete

  final pickupSearchText = ''.obs;
  final dropSearchText = ''.obs;
  final pickupPredictions = <Map<String, dynamic>>[].obs;
  final pickupSelectedPlace = {}.obs;
  final dropPredictions = <Map<String, dynamic>>[].obs;
  final dropSelectedPlace = {}.obs;
  final GooglePlacesService placesService = GooglePlacesService();


  CameraPosition? kGooglePlex;

  Completer<GoogleMapController> controllers = Completer();

  late GoogleMapController mapController;


  // LocationService locationService = LocationService();
  TextEditingController searchController = TextEditingController();


  TextEditingController dropAddressController =  TextEditingController();
  TextEditingController dropStateController =  TextEditingController();
  TextEditingController dropCityController =  TextEditingController();
  TextEditingController dropSuburbController =  TextEditingController();
  TextEditingController dropPostcodeController =  TextEditingController();


  Future<void> goToThePosition(cameraPosition) async {
    final GoogleMapController controller = await controllers.future;
    controller.animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
  }

  onSearchDropTextChanged(String text) async {
    dropSearchText.value = text;
    if (text.length > 2) {
      try {
        final places = await placesService.getPlacesPredictions(text);
        // final places = await autocompletePlaces(text);
        dropPredictions.assignAll(places);
        update();

      } catch (e) {
        print('Error fetching predictions: $e');
      }
    } else {
      dropPredictions.clear();
      update();

    }
  }

  getDropPlaceDetails(String placeId,locationAddress) async {
    try {
      final details = await placesService.getPlaceDetails(placeId);
      dropSelectedPlace.value = details;
      print('getDropPlaceDetailslatitude ${dropSelectedPlace['geometry']['location']['lat']}');
      print('getDropPlaceDetailslongitude ${dropSelectedPlace['geometry']['location']['lng']}');
      getDropAddressFromLatLng(dropSelectedPlace['geometry']['location']['lat'],dropSelectedPlace['geometry']['location']['lng'],locationAddress);
    } catch (e) {
      print('Error fetching place details: $e');
    }
  }

  getDropAddressFromLatLng(double latitudes, double longitudes,locationAddress) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await placemarkFromCoordinates(latitudes, longitudes).then((List<Placemark> placemarks) {
      Placemark place = placemarks[0];
      dropCityController.text = '${place.locality}' ?? '';
      dropStateController.text = '${place.administrativeArea}' ?? '';
      dropSuburbController.text = '${place.subLocality!.isNotEmpty?place.subLocality:place.street}';
      dropPostcodeController.text ='${place.postalCode}' ?? '';
      dropAddressController.text = locationAddress ?? '';
      toAddress = dropAddressController.text;
      toLatitude = double.parse(latitudes.toString()).toString();
      toLongitude = double.parse(longitudes.toString()).toString();

      kGooglePlex = CameraPosition(
        target: LatLng(double.parse(toLatitude.toString()), double.parse(toLongitude.toString())),
        zoom: 14.4746,
      );
      goToThePosition(kGooglePlex);
      dropPredictions.clear();
      update();


      print('latitude $toLatitude');
      print('longitude $toLongitude');

    }).catchError((e) {
      debugPrint(e);
    });
  }





  getCountry() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    dialCode = prefs.getString('dialCode') ?? '';
    print(dialCode);
    googleApiKey = prefs.getString('googleApi');
    initialCountry = prefs.getString('location_Country');
    markers.add(Marker(
      markerId: MarkerId('Mylocation'),
      infoWindow: InfoWindow(title: 'My Location'),
      draggable: true,
      onDragEnd: (latLong) async {
        print('latLongDrag$latLong');
        center = latLong;
        getAddressFromLatLong(
            double.parse(latLong.latitude.toString()), double.parse(latLong.longitude.toString()));
        print("addressonDragEnd$address");
        update();
      },
      onDrag: (latLong) {
        center = latLong;
      },
      icon: BitmapDescriptor.defaultMarker,
      position: center!,
    ));
     getAddressFromLatLong(
        double.parse(currentLatitude.toString()), double.parse(currentLongitude.toString()));
    // number = PhoneNumber(isoCode: initialCountry);
    update();
    print('$googleApiKey google');

    // print(number);
  }


  Future<void> getAddressFromLatLong(double latitudes, double longitudes) async {
    print('getCurrentLocationAddressssssss');

    await placemarkFromCoordinates(
        latitudes, longitudes)
        .then((List<Placemark> placemarks) {
      Placemark place = placemarks[0];
      dropCityController.text = place.locality ?? '';
     dropStateController.text = place.administrativeArea ?? '';
     dropSuburbController.text = '${place.subLocality??place.street}' ;
      dropPostcodeController.text = place.postalCode ?? '';
      toLatitude = double.parse(latitudes.toString()).toString();
      toLongitude = double.parse(longitudes.toString()).toString();
      print('latitudegetAddresstoLatitude$toLatitude');
      print('longitudegetAddresstoLongitude$toLongitude');
      dropAddressController.text  = '${place.street}, ${place.subLocality},${place.locality},${place.administrativeArea} ${place.subAdministrativeArea},${place.country},${place.postalCode}.';

      print('dropAddressControllergetAddresstoLongitude ${dropAddressController.text}');
      update();

    }).catchError((e) {
      debugPrint(e);
    });
  }



  @override
  void onInit() {

    // TODO: implement onInit
    super.onInit();
  }

}