import 'package:get/get.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) {
      callApi<ProvinceAddressResponse>(
        request: () => client.locationProvinceGetList(),
        onSuccess: (data, _) {
          _loadFromProvince(data.items ?? []);
        },
        withLoading: false,
      );
    } else {
      callApi<DistrictAddressResponse>(
        request: () => client.locationDistrictGetList(provinceCode),
        onSuccess: (data, _) {
          _loadFromDistrict(data.items ?? []);
        },
        withLoading: false,
      );
    }
  }

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

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

  void search(String query) {
    if (query.isEmpty) {
      displayItems.assignAll(_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.assignAll(filteredItems);
  }

  void select(AddressBaseModel item) {
    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;
  }
}
