import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../networking/restful_api_viewmodel.dart';
import 'location_address_screen.dart';
import 'models/district_address_model.dart';
import 'models/province_address_model.dart';

class AddressBaseModel {
  final String? code;
  final String? name;
  AddressBaseModel({this.code, this.name});
}

class LocationAddressViewModel extends RestfulApiViewModel {
  List<AddressBaseModel> _allItems = [];
  final RxList<AddressBaseModel> displayItems = <AddressBaseModel>[].obs;
  final RxString selectedCode = ''.obs;
  LocationAddressType type = LocationAddressType.province;
  String provinceCode = '';

  LocationAddressViewModel({this.type = LocationAddressType.province, this.provinceCode = ''});

  @override
  void onInit() {
    super.onInit();
    if (type == LocationAddressType.province) {
      client.locationProvinceGetList().then((value) {
        final data = value.data?.items ?? [];
          _loadFromProvince(data);
      });
    } else {
      client.locationDistrictGetList(provinceCode).then((value) {
        final data = value.data?.items ?? [];
        _loadFromDistrict(data);
      });
    }
  }

  void _loadFromProvince(List<ProvinceAddressModel> provinces) {
    _allItems = provinces.map((e) => AddressBaseModel(code: e.cityCode, name: e.cityName)).toList();
    displayItems.value = _allItems;
  }

  void _loadFromDistrict(List<DistrictAddressModel> districts) {
    _allItems = districts.map((e) => AddressBaseModel(code: e.districtCode, name: e.districtName)).toList();
    displayItems.value = _allItems;
  }

  void search(String query) {
    if (query.isEmpty) {
      displayItems.value = _allItems;
      return;
    }
    final lowerQuery = _removeDiacritics(query).toLowerCase();
    final filteredItems = _allItems.where((item) {
      final name = item.name ?? '';
      final normalized = _removeDiacritics(name).toLowerCase();
      return normalized.contains(lowerQuery);
    }).toList();
    displayItems.value = filteredItems;
  }

  void select(AddressBaseModel item) {
    print(" Selected code: ${item.code}");
    selectedCode.value = item.code ?? '';
    displayItems.refresh();
    Get.back(result: item);
  }

  String _removeDiacritics(String str) {
    const withDiacritics = 'àáảãạâầấẩẫậăằắẳẵặèéẻẽẹêềếểễệìíỉĩịòóỏõọôồốổỗộơờớởỡợùúủũụưừứửữựỳýỷỹỵđ'
        'ÀÁẢÃẠÂẦẤẨẪẬĂẰẮẲẴẶÈÉẺẼẸÊỀẾỂỄỆÌÍỈĨỊÒÓỎÕỌÔỒỐỔỖỘƠỜỚỞỠỢÙÚỦŨỤƯỪỨỬỮỰỲÝỶỸỴĐ';
    const withoutDiacritics = 'aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyyd'
        'AAAAAAAAAAAAAAAAAEEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOOOUUUUUUUUUUUYYYYYD';

    for (int i = 0; i < withDiacritics.length; i++) {
      str = str.replaceAll(withDiacritics[i], withoutDiacritics[i]);
    }
    return str;
  }
}
