import 'package:elektronika/app/pages/profile/sub_pages/personal_info_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:loader_overlay/loader_overlay.dart';

import '../../../app.dart';

class AddressController extends GetxController {
  RxBool isLoading = false.obs;
  RxBool isAddingLoading = false.obs;
  RxBool hasError = false.obs;

  RxList<AddressModel> addresses = <AddressModel>[].obs;

  final addressForm = GlobalKey<FormState>();
  final TextEditingController nameCtrl = new TextEditingController();
  final TextEditingController surnameCtrl = new TextEditingController();
  final TextEditingController phoneCtrl = new TextEditingController();
  final TextEditingController addressCtrl = new TextEditingController();
  final TextEditingController cityCtrl = new TextEditingController();
  // final TextEditingController stateCtrl = new TextEditingController();

  List<StateModel> states = [];
  Rxn<StateModel> selectedState = Rxn<StateModel>();

  String locale = 'tm';

  @override
  void onInit() {
    debugPrint('AddressController onInit');
    getCurrentLocale();
    getStates();
    getAddresses();
    super.onInit();
  }

  @override
  void onClose() {
    nameCtrl.dispose();
    surnameCtrl.dispose();
    phoneCtrl.dispose();
    addressCtrl.dispose();
    cityCtrl.dispose();
    // stateCtrl.dispose();

    super.onClose();
  }

  void setUserInfo() {
    PersonalInfoController _personalInfoController = Get.put(PersonalInfoController());

    final isErrorOccurred = _personalInfoController.isErrorOccurred.value;

    if (!isErrorOccurred) {
      nameCtrl.text = _personalInfoController.nameCtrl.text;
      surnameCtrl.text = _personalInfoController.surnameCtrl.text;
      phoneCtrl.text = _personalInfoController.phoneCtrl.text;
    }
  }

  Future<void> getAddresses() async {
    isLoading.value = true;
    update();

    addresses.clear();

    final List<AddressModel>? addressList = await AddressesApi.get();
    isLoading.value = false;

    if (addressList == null) {
      hasError.value = true;
      update();
      return;
    }

    addresses.addAll(addressList);
    update();
  }

  Future<void> getStates() async {
    if (states.isNotEmpty) return;

    final newStates = await AddressesApi.getStates();
    if (newStates.isNotEmpty) {
      states = [...newStates];
      selectedState.value = states.first;
    }

    update();
  }

  Future<void> createAddress() async {
    if (addressForm.currentState!.validate()) {
      isAddingLoading.value = true;
      update();

      final maskedPhoneNumber = phoneCtrl.value.text;
      final phone = maskedPhoneNumber.replaceAll(RegExp(r'\D+'), '');

      List<String> addresses1 = [addressCtrl.text];

      final Map<String, dynamic> params = {
        'locale': await getLocale(),
        'first_name': nameCtrl.text,
        'last_name': surnameCtrl.text,
        'phone': phone,
        'address1': addresses1,
        'city': cityCtrl.text,
        'state': selectedState.value?.code,
      };

      final result = await AddressesApi.create(params);

      isAddingLoading.value = false;
      update();

      if (result == null) {
        showSnack('error'.tr, 'error_occurred'.tr, SnackType.ERROR);
        return;
      }

      addresses.add(result);
      update();
      Get.back();
    }
  }

  Future<void> deleteAddress(BuildContext context, AddressModel address) async {
    debugPrint('address id: ${address.id}');

    context.loaderOverlay.show();

    final result = await AddressesApi.delete(address.id);

    context.loaderOverlay.hide();

    if (result) {
      getAddresses();
    } else {
      showSnack('error'.tr, 'error_occurred'.tr, SnackType.ERROR);
    }
  }

  void onStateChange(StateModel? newValue) {
    debugPrint('onStateChange $newValue');
    selectedState.value = newValue;
    update();
  }

  Future<void> getCurrentLocale() async {
    locale = await getLocale();
  }
}
