import 'package:get/get.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 'package:mypoint_flutter_app/preference/data_preference.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../../preference/contact_storage_service.dart';
import '../voucher/models/product_brand_model.dart';
import '../voucher/models/product_model.dart';
import '../voucher/models/product_type.dart';

class TopUpViewModel extends RestfulApiViewModel {
  var histories = RxList<String>();
  final RxList<ProductBrandModel> topUpBrands = <ProductBrandModel>[].obs;
  final RxList<ProductModel> products = <ProductModel>[].obs;
  var selectedBrand = Rxn<ProductBrandModel>();
  var selectedProduct = Rxn<ProductModel>();
  final Map<String, List<ProductModel>> _allValue = {};
  var phoneNumber = ''.obs;

  @override
  void onInit() {
    super.onInit();
    final myPhone = DataPreference.instance.phone ?? '';
    phoneNumber.value = myPhone;
    ContactStorageService().getUsedContacts().then((value) {
      if (value.isNotEmpty) {
        histories.value = value;
      } else {
        histories.value = [myPhone];
      }
    });
    if (!histories.contains(myPhone)) {
      histories.value.insert(0, myPhone);
      ContactStorageService().saveUsedContact(myPhone);
    }
  }

  bool validatePhoneNumber() {
    final phone = phoneNumber.value.replaceAll(RegExp(r'\s+'), '');
    final regex = RegExp(r'^(0|\+84)(3[2-9]|5[6|8|9]|7[0|6-9]|8[1-5]|9[0-4|6-9])[0-9]{7}$');
    return regex.hasMatch(phone);
  }

  firstLoadTopUpData() async {
    _getTopUpBrands();
  }

  _getTopUpBrands() {
    showLoading();
    client.getTopUpBrands(ProductType.topupMobile).then((response) {
      topUpBrands.value = response.data ?? [];
      hideLoading();
      checkMobileNetwork();
    }).catchError((error) {
      hideLoading();
    });
  }

  checkMobileNetwork() {
    showLoading();
    client.checkMobileNetwork(phoneNumber.value).then((response) {
      final brandCode = response.data?.brand ?? '';
      final brand = topUpBrands.isNotEmpty
          ? topUpBrands.firstWhere(
            (brand) => brand.code == brandCode,
            orElse: () => topUpBrands.first,
          )
          : null;
      selectedBrand.value = brand;
      hideLoading();
      getTelcoDetail();
    }).catchError((error) {
      final first = topUpBrands.value.firstOrNull;
      if (first != null) {
        selectedBrand.value = first;
      }
      hideLoading();
      getTelcoDetail();
      print('Error checking mobile network: $error');
    });
  }

  Future<void> getTelcoDetail({String? selected}) async {
    final code = selectedBrand.value?.code;
    final id = selectedBrand.value?.id;
    if (code == null || id == null) return;
    void makeSelected(List<ProductModel> list) {
      bool didSelect = false;
      if (selected != null && selected.isNotEmpty) {
        for (var item in list) {
          final isMatch = item.id == int.tryParse(selected);
          if (isMatch) {
            selectedProduct.value = item;
            didSelect = true;
          }
        }
      }
      // Nếu chưa có item nào được chọn → mặc định chọn 100k
      if (!didSelect && selectedProduct.value == null) {
         final item100k = list.isNotEmpty
            ? list.firstWhere(
              (e) => e.amountToBePaid == 100000,
          orElse: () => list.first,
        ) : null;
        selectedProduct.value = item100k;
      }
    }
    // Dùng cache nếu có
    if (_allValue.containsKey(code)) {
      final cached = _allValue[code]!;
      products.value = cached;
      makeSelected(cached);
      return;
    }
    showLoading();
    final body = {
      "type": ProductType.topupMobile.value,
      "size": 200,
      "index": 0,
      "brand_id": selectedBrand.value?.id ?? 0,
    };
    try {
      final result = await client.getProducts(body);
      final data = result.data ?? [];
      _allValue[code] = data;
      products.value = result.data ?? [];
      hideLoading();
      makeSelected(data);
    } catch (error) {
      print("Error fetching all products: $error");
      hideLoading();
    }
  }
}