import 'package:country_currency_pickers/country.dart';
import 'package:country_currency_pickers/utils/utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:rounded_loading_button_plus/rounded_loading_button.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io';
import '../../../../../../../Data/Repository/Createcustomer/Createcustomerrepository.dart';
import '../../../../../../../Globalwidgets/Googleplaces/Googleplaces.dart';
import '../../../../../../../Helper/Locationservice/Locationservice.dart';
import '../../../../../../../Helper/location_service.dart';
import '../../../../../../../Helper/toast.dart';
import '../../../../../../../Model/Request/Createcustomer/Createcustomerrequest.dart';
import '../../../../../../../Model/Response/Createcustomer/Createcustomerresponse.dart';
import '../../../../../../../View/Createorder/Createorderview.dart';
import '../../../../../../Createorder/Createordercontroller.dart';
import '../../Tenantcustomercontroller.dart';


class AddDropCustomerController extends GetxController{

  String? latitude;
  String? longitude;

  String? suburb;
  String? city;
  String? state;
  String? postCode;

  int? tenantId;
  int? appLocationId;



  bool progress = true;

  TextEditingController customerFirstNameController = TextEditingController();
  TextEditingController customerLastNameController = TextEditingController();
  TextEditingController customerPhoneController = TextEditingController();
  TextEditingController addressController = TextEditingController();
  TextEditingController doorNoController = TextEditingController();
  TextEditingController landMarkController = TextEditingController();


  Position? resultPosition;

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

  Country selectedDialogCountry = CountryPickerUtils.getCountryByIsoCode('IN');

  final GooglePlacesService placesService = GooglePlacesService();

  final RoundedLoadingButtonController btnController = RoundedLoadingButtonController();

  CreateCustomerRepository createCustomerRepository = CreateCustomerRepository();

  TenantDropCustomerController tenantDropCustomerController = Get.put(TenantDropCustomerController());
  CreateOrderController createOrderController = Get.put(CreateOrderController());



  LocationService locationService = LocationService();



  getLocation() async {
    resultPosition = await locationService.getLocation();
    progress =false;
    update();
  }


  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,address) 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();
      city  = '${place.locality}';
      state  = '${place.administrativeArea}';
      suburb  = place.subLocality!.isNotEmpty?place.subLocality:place.street;
      postCode  = '${place.postalCode}';
      addressController.text = address;
      predictions.clear();
      update();
      print('latitude $latitude');
      print('longitude $longitude');
      print('eng $suburb');
      print('city $city');
      print('state $state');
      print('postalCode $postCode');
      print('subAdministrativeArea ${place.subAdministrativeArea}');
      print('subThoroughfare ${place.subThoroughfare}');
      print('currentLocationAddress ${addressController.text}');
      print('streetss ${place.street}');

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

  describeValidation(){
    if(customerFirstNameController.text.isEmpty){
      btnController.reset();
      Toast.showToast("Please enter your first name");
    }
    // else if(customerLastNameController.text.isEmpty){
    //   Toast.showToast("Please enter your last name");
    // }
    else if(customerPhoneController.text.isEmpty){
      btnController.reset();

      Toast.showToast("Please enter your phone number");
    }else if(addressController.text.isEmpty){
      btnController.reset();

      Toast.showToast("Please enter your address");
    }
    else if(latitude == null &&longitude == null){
      btnController.reset();
      Toast.showToast("Please enter correct address");
    }
    // else if(doorNoController.text.isEmpty){
    //   Toast.showToast("Please enter your door number");
    // }
    // else if(landMarkController.text.isEmpty){
    //   Toast.showToast("Please enter your landmark");
    // }
    else{
      btnController.success();
      createCustomer();
      update();
    }
  }

  createCustomer() async{
    var createdate = DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now());
    var updatedate = DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now());
    SharedPreferences prefs = await SharedPreferences.getInstance();
    tenantId = prefs.getInt('tenantId');
    appLocationId = prefs.getInt('appLocationId');

    print('tenantIdcreateCustomer$tenantId');
    String contactNo = customerPhoneController.text;
    print("contact............$contactNo");
    create(
        CreateCustomers(
            customerid:0,
            configid:1,
            tenantid: tenantId,
            firstname:customerFirstNameController.text,
            applocationid:appLocationId,
            profileimage:"",
            dialcode:"+91",
            contactno:customerPhoneController.text,
            devicetype:Platform.operatingSystem,
            // deviceid:"${prefs.getString('deviceId')}",
            // customertoken:"$fcmEntryToken",
            address:addressController.text,
            suburb:suburb,
            city:city,
            state:state,
            postcode:postCode,
            landmark:landMarkController.text,
            doorno:doorNoController.text,
            latitude:latitude,
            longitude:longitude,
            primaryaddress: 1,
        ));

  }

  create(CreateCustomers data )async{
    CreateCustomerResponse? result = await createCustomerRepository.createCustomer(data);

    if(result?.status == true){
      customerFirstNameController.clear();
      customerLastNameController.clear();
      customerPhoneController.clear();
      addressController.clear();
      doorNoController.clear();
      landMarkController.clear();
      tenantDropCustomerController.getCustomerByTenantId();
      btnController.reset();
      createOrderController.dropCustomerId = result?.details?.customerid;
      createOrderController.dropCustomerName = "${result?.details?.firstname}" + "${result?.details?.lastname}";
      createOrderController.dropCustomerContactNo = result?.details?.contactno;
      createOrderController.dropLocationId = result?.details?.deliverylocationid;
      createOrderController.dropTenantLocationId = result?.details?.tenantlocationid;
      createOrderController.toLatitude = result?.details?.latitude;
      createOrderController.toLongitude = result?.details?.longitude;
      createOrderController.toAddress =result?.details?.address;
      // Get.offAll(TenantDropCustomerView());
      Get.to(()=>CreateOrderView(isDashboard: false));
    }else{
      btnController.reset();
      Toast.showToast('${result?.message}');
    }
  }

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