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 PickupGoogleMapsController extends GetxController{


  String? fromAddress;



  String? fromLatitude;
  String? fromLongitude;


  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 pickupPredictions = <Map<String, dynamic>>[].obs;
  final pickupSelectedPlace = {}.obs;
  final GooglePlacesService placesService = GooglePlacesService();


  CameraPosition? kGooglePlex;

  Completer<GoogleMapController> controllers = Completer();

  late GoogleMapController mapController;


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


  TextEditingController pickupAddressController =  TextEditingController();
  TextEditingController pickupStateController =  TextEditingController();
  TextEditingController pickupCityController =  TextEditingController();
  TextEditingController pickupSuburbController =  TextEditingController();
  TextEditingController pickupPostcodeController =  TextEditingController();


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

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

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

    }
  }

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

  getPickupAddressFromLatLng(double latitudes, double longitudes,locationAddress) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await placemarkFromCoordinates(latitudes, longitudes).then((List<Placemark> placemarks) {
      Placemark place = placemarks[0];
      pickupCityController.text = '${place.locality}' ?? '';
      pickupStateController.text = '${place.administrativeArea}' ?? '';
      pickupSuburbController.text = '${place.subLocality!.isNotEmpty?place.subLocality:place.street}';
      pickupPostcodeController.text ='${place.postalCode}' ?? '';
      pickupAddressController.text = locationAddress ?? '';
      fromAddress = pickupAddressController.text;
      fromLatitude = double.parse(latitudes.toString()).toString();
      fromLongitude = double.parse(longitudes.toString()).toString();

      kGooglePlex = CameraPosition(
        target: LatLng(double.parse(fromLatitude.toString()), double.parse(fromLongitude.toString())),
        zoom: 14.4746,
      );
      goToThePosition(kGooglePlex);
      pickupPredictions.clear();
      update();


      print('latitude $fromLatitude');
      print('longitude $fromLongitude');

    }).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];
      pickupCityController.text = place.locality ?? '';
      pickupStateController.text = place.administrativeArea ?? '';
      pickupSuburbController.text = '${place.subLocality??place.street}' ;
      pickupPostcodeController.text = place.postalCode ?? '';
      fromLatitude = double.parse(latitudes.toString()).toString();
      fromLongitude = double.parse(longitudes.toString()).toString();
      print('latitudegetAddressfromLatitude $fromLatitude');
      print('longitudegetAddressfromLongitude $fromLongitude');
      pickupAddressController.text  = '${place.street}, ${place.subLocality},${place.locality},${place.administrativeArea} ${place.subAdministrativeArea},${place.country},${place.postalCode}.';

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

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



  @override
  void onInit() {

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

}