import 'package:flutter/cupertino.dart';
import 'package:geocoding/geocoding.dart';
import 'package:get/get.dart';
import 'package:rounded_loading_button_plus/rounded_loading_button.dart';

import 'package:shared_preferences/shared_preferences.dart';
import '../../../../../../Data/Provider/Getcustomeraddress/Getcustomeraddressprovider.dart';
import '../../../../../../Data/Repository/Createcustomer/Createcustomerrepository.dart';
import '../../../../../../Globalwidgets/Googleplaces/Googleplaces.dart';
import '../../../../../../Helper/Constants/Apiconstants.dart';
import '../../../../../../Helper/location_service.dart';
import '../../../../../../Helper/toast.dart';
import '../../../../../../Model/Request/Authentication/Createuser/Createdeliveryaddress/Createdeliveryaddressrequest.dart';
import '../../../../../../Model/Response/Createcustomer/Createdeliveryaddress/Createdeliveryaddressresponsel.dart';
import '../../../../../../Model/Response/Getcustomeraddress/GetCustomerAddress.dart';
import '../../../../../../View/Createorder/Droplocation/Tabs/Allcustomers/Tenantcustomers/Customeraddress/Customeraddressview.dart';



class DropCustomerAddressController extends GetxController{

  String? latitude;
  String? longitude;
  String? address;

  String? customerName;
  String? customerContactNo;

  int locationId = 0;
  int roleId = 0;
  int? customerId;
  int? deliveryLocationId;

  int selectedAddressIndex = -1;

  List <CustomerAddressDetail> getCustomeraddress =[];


  bool loader = true;
  bool deliveryAddressList = false;

  var customerAddressInfo;


  TextEditingController searchController = TextEditingController();
  TextEditingController addressController = TextEditingController();
  TextEditingController suburbController = TextEditingController();
  TextEditingController cityController = TextEditingController();
  TextEditingController stateController = TextEditingController();
  TextEditingController postCodeController = TextEditingController();
  TextEditingController landmarkController = TextEditingController();
  TextEditingController doornoController = TextEditingController();

  final searchText = ''.obs;
  final predictions = <Map<String, dynamic>>[].obs;
  final selectedPlace = {}.obs;

  final GooglePlacesService placesService = GooglePlacesService();

  final RoundedLoadingButtonController btnController = RoundedLoadingButtonController();
  final RoundedLoadingButtonController submitBtnController = RoundedLoadingButtonController();

  CreateCustomerRepository createCustomerRepository = CreateCustomerRepository();

  GetCustomersAddressProvider getCustomersAddressProvider = GetCustomersAddressProvider();

  getDetails()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    roleId = prefs.getInt('roleId')??0;
    print('roleIdingetDetails $roleId');
    update();
  }

  getCustomerAddress()async{
    GetCustomerAddress? result = await getCustomersAddressProvider.getCustomerAddress('${ApiConstants.getCustomerAddress}?customerid=$customerId');
    getCustomeraddress = result?.details??[];
    loader = false;
    for (var i = 0; i < getCustomeraddress.length; i++) {
      if (getCustomeraddress[i].defaultaddress == '1') {
        deliveryLocationId = getCustomeraddress[i].locationid;
        print('getCustomerAddressforloop $deliveryLocationId');
        update();
      }
    }
    update();

    print('getCustomerAddressincontroller${result?.toJson()}');

  }

  describeValidation(){
    if(addressController.text.isEmpty){
      submitBtnController.reset();
      Toast.showToast("Delivery address should not be empty");
    }
    else if(suburbController.text.isEmpty){
      submitBtnController.reset();
      Toast.showToast("Suburb should not be empty!");
    }
    else if(stateController.text.isEmpty){
      submitBtnController.reset();
      Toast.showToast("State should not be empty!");
    }else if(postCodeController.text.isEmpty){
      submitBtnController.reset();
      Toast.showToast("Pin code should not be empty!");
    }

    else{
      submitBtnController.success();
      createDeliveryAddress();
    }
  }

  createDeliveryAddress()async {
    create(
        CreateDeliveryAddress(
          customerid:customerAddressInfo.customerid,
          address: addressController.text,
          suburb: suburbController.text,
          city: cityController.text,
          state: stateController.text,
          postcode: postCodeController.text,
          // countycode:"91",
          latitude: '$latitude',
          longitude: '$longitude',
          primaryaddress: 0,
        ));
  }

  create(CreateDeliveryAddress data )async{
    CreateDeliveryAddressResponse? result = await createCustomerRepository.createDeliveryAddress(data);
    if(result?.status == true){
      deliveryAddressList = false;
      getCustomerAddress();
      submitBtnController.reset();
      Get.to(CustomerDropAddressView(data: customerAddressInfo,));
      update();
    }
    print('CreateDeliveryAddress create ${result!.toJson()}');
  }

  void onSearchTextChanged(String text) async {
    searchText.value = text;
    if (text.length > 2) {
      try {
        final places = await placesService.getPlacesPredictions(text);
        predictions.assignAll(places);
        update();
      } catch (e) {
        print('Error fetching predictions: $e');
      }
    } else {
      predictions.clear();
      update();
    }
  }

  Future<void> getPlaceDetails(String placeId,locationAddress) async {
    try {
      final details = await placesService.getPlaceDetails(placeId);
      selectedPlace.value = details;
      print('getPlaceDetailslatitude ${selectedPlace['geometry']['location']['lat']}');
      print('getPlaceDetailslongitude ${selectedPlace['geometry']['location']['lng']}');
      getAddressFromLatLng(selectedPlace['geometry']['location']['lat'],selectedPlace['geometry']['location']['lng'],locationAddress);
    } catch (e) {
      print('Error fetching place details: $e');
    }
  }

  Future<void> getAddressFromLatLng(double latitudes, double longitudes,locationAddress) async {
    await placemarkFromCoordinates(latitudes, longitudes).then((List<Placemark> placemarks) {
      Placemark place = placemarks[0];
      latitude = double.parse(latitudes.toString()).toString();
      longitude = double.parse(longitudes.toString()).toString();
      cityController.text  = '${place.locality}';
      stateController.text  = '${place.administrativeArea}';
      suburbController.text  = (place.subLocality!.isNotEmpty?place.subLocality:place.street)!;
      postCodeController.text  = '${place.postalCode}';
      addressController.text = locationAddress;
      predictions.clear();
      update();
      print('latitude $latitude');
      print('longitude $longitude');
      print('subAdministrativeArea ${place.subAdministrativeArea}');
      print('subThoroughfare ${place.subThoroughfare}');
      print('currentLocationAddress ${ addressController.text}');
      print('streetss ${place.street}');

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

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
  }
}